Whamcloud - gitweb
1e100423698f866ba342d57ef6bfba6c4ae5fefa
[fs/lustre-release.git] / lustre / utils / lfs.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * lustre/utils/lfs.c
32  *
33  * Author: Peter J. Braam <braam@clusterfs.com>
34  * Author: Phil Schwan <phil@clusterfs.com>
35  * Author: Robert Read <rread@clusterfs.com>
36  */
37
38 /* for O_DIRECTORY */
39 #ifndef _GNU_SOURCE
40 #define _GNU_SOURCE
41 #endif
42
43 #include <stdlib.h>
44 #include <stdio.h>
45 #include <inttypes.h>
46 #include <getopt.h>
47 #include <string.h>
48 #include <mntent.h>
49 #include <unistd.h>
50 #include <errno.h>
51 #include <err.h>
52 #include <pwd.h>
53 #include <grp.h>
54 #include <sys/ioctl.h>
55 #include <sys/quota.h>
56 #include <sys/time.h>
57 #include <sys/types.h>
58 #include <sys/stat.h>
59 #include <sys/param.h>
60 #include <sys/xattr.h>
61 #include <fcntl.h>
62 #include <dirent.h>
63 #include <time.h>
64 #include <ctype.h>
65 #include <zlib.h>
66 #include <libgen.h>
67 #include <asm/byteorder.h>
68 #include "lfs_project.h"
69
70 #include <libcfs/util/string.h>
71 #include <libcfs/util/ioctl.h>
72 #include <libcfs/util/parser.h>
73 #include <libcfs/util/string.h>
74 #include <lustre/lustreapi.h>
75 #include <linux/lustre/lustre_ver.h>
76 #include <linux/lustre/lustre_param.h>
77 #include <linux/lnet/nidstr.h>
78 #include <lnetconfig/cyaml.h>
79 #include "lstddef.h"
80
81 #ifndef NSEC_PER_SEC
82 # define NSEC_PER_SEC 1000000000UL
83 #endif
84 #define ONE_MB 0x100000
85
86 /* all functions */
87 static int lfs_find(int argc, char **argv);
88 static int lfs_getstripe(int argc, char **argv);
89 static int lfs_getdirstripe(int argc, char **argv);
90 static int lfs_setdirstripe(int argc, char **argv);
91 static int lfs_rmentry(int argc, char **argv);
92 static int lfs_unlink_foreign(int argc, char **argv);
93 static int lfs_osts(int argc, char **argv);
94 static int lfs_mdts(int argc, char **argv);
95 static int lfs_df(int argc, char **argv);
96 static int lfs_getname(int argc, char **argv);
97 static int lfs_check(int argc, char **argv);
98 #ifdef HAVE_SYS_QUOTA_H
99 static int lfs_setquota(int argc, char **argv);
100 static int lfs_quota(int argc, char **argv);
101 static int lfs_project(int argc, char **argv);
102 #endif
103 static int lfs_flushctx(int argc, char **argv);
104 static int lfs_poollist(int argc, char **argv);
105 static int lfs_changelog(int argc, char **argv);
106 static int lfs_changelog_clear(int argc, char **argv);
107 static int lfs_fid2path(int argc, char **argv);
108 static int lfs_path2fid(int argc, char **argv);
109 static int lfs_rmfid(int argc, char **argv);
110 static int lfs_data_version(int argc, char **argv);
111 static int lfs_hsm_state(int argc, char **argv);
112 static int lfs_hsm_set(int argc, char **argv);
113 static int lfs_hsm_clear(int argc, char **argv);
114 static int lfs_hsm_action(int argc, char **argv);
115 static int lfs_hsm_archive(int argc, char **argv);
116 static int lfs_hsm_restore(int argc, char **argv);
117 static int lfs_hsm_release(int argc, char **argv);
118 static int lfs_hsm_remove(int argc, char **argv);
119 static int lfs_hsm_cancel(int argc, char **argv);
120 static int lfs_swap_layouts(int argc, char **argv);
121 static int lfs_mv(int argc, char **argv);
122 static int lfs_ladvise(int argc, char **argv);
123 static int lfs_getsom(int argc, char **argv);
124 static int lfs_heat_get(int argc, char **argv);
125 static int lfs_heat_set(int argc, char **argv);
126 static int lfs_mirror(int argc, char **argv);
127 static inline int lfs_mirror_resync(int argc, char **argv);
128 static inline int lfs_mirror_verify(int argc, char **argv);
129 static inline int lfs_mirror_read(int argc, char **argv);
130 static inline int lfs_mirror_write(int argc, char **argv);
131 static inline int lfs_mirror_copy(int argc, char **argv);
132 static int lfs_pcc_attach(int argc, char **argv);
133 static int lfs_pcc_attach_fid(int argc, char **argv);
134 static int lfs_pcc_detach(int argc, char **argv);
135 static int lfs_pcc_detach_fid(int argc, char **argv);
136 static int lfs_pcc_state(int argc, char **argv);
137 static int lfs_pcc(int argc, char **argv);
138
139 enum stats_flag {
140         STATS_ON,
141         STATS_OFF,
142 };
143
144 static int lfs_migrate_to_dom(int fd_src, int fd_dst, char *name,
145                               __u64 migration_flags,
146                               unsigned long long bandwidth_bytes_sec,
147                               enum stats_flag stats_flag,
148                               long stats_interval_sec);
149
150 struct pool_to_id_cbdata {
151         const char *pool;
152         __u32 id;
153 };
154
155 static int find_comp_id_by_pool(struct llapi_layout *layout, void *cbdata);
156 static int find_mirror_id_by_pool(struct llapi_layout *layout, void *cbdata);
157
158 enum setstripe_origin {
159         SO_SETSTRIPE,
160         SO_MIGRATE,
161         SO_MIGRATE_MDT,
162         SO_MIRROR_CREATE,
163         SO_MIRROR_EXTEND,
164         SO_MIRROR_SPLIT,
165         SO_MIRROR_DELETE,
166 };
167
168 static int lfs_setstripe_internal(int argc, char **argv,
169                                   enum setstripe_origin opc);
170
171 static inline int lfs_setstripe(int argc, char **argv)
172 {
173         return lfs_setstripe_internal(argc, argv, SO_SETSTRIPE);
174 }
175
176 static inline int lfs_setstripe_migrate(int argc, char **argv)
177 {
178         return lfs_setstripe_internal(argc, argv, SO_MIGRATE);
179 }
180
181 static inline int lfs_mirror_create(int argc, char **argv)
182 {
183         return lfs_setstripe_internal(argc, argv, SO_MIRROR_CREATE);
184 }
185
186 static inline int lfs_mirror_extend(int argc, char **argv)
187 {
188         return lfs_setstripe_internal(argc, argv, SO_MIRROR_EXTEND);
189 }
190
191 static inline int lfs_mirror_split(int argc, char **argv)
192 {
193         return lfs_setstripe_internal(argc, argv, SO_MIRROR_SPLIT);
194 }
195
196 static inline int lfs_mirror_delete(int argc, char **argv)
197 {
198         return lfs_setstripe_internal(argc, argv, SO_MIRROR_DELETE);
199 }
200
201 /* Setstripe and migrate share mostly the same parameters */
202 #define SSM_CMD_COMMON(cmd) \
203         "usage: "cmd" [--component-end|-E COMP_END]\n"                  \
204         "                 [--copy=LUSTRE_SRC]\n"                        \
205         "                 [--extension-size|--ext-size|-z SIZE]\n"      \
206         "                 [--help|-h] [--layout|-L PATTERN]\n"          \
207         "                 [--layout|-L PATTERN]\n"                      \
208         "                 [--mirror-count|-N[MIRROR_COUNT]]\n"          \
209         "                 [--ost|-o OST_INDICES]\n"                     \
210         "                 [--overstripe-count|-C STRIPE_COUNT]\n"       \
211         "                 [--pool|-p POOL_NAME]\n"                      \
212         "                 [--stripe-count|-c STRIPE_COUNT]\n"           \
213         "                 [--stripe-index|-i START_OST_IDX]\n"          \
214         "                 [--stripe-size|-S STRIPE_SIZE]\n"             \
215         "                 [--yaml|-y YAML_TEMPLATE_FILE]\n"
216
217 #define MIRROR_EXTEND_USAGE                                             \
218         "                 {--mirror-count|-N[MIRROR_COUNT]}\n"          \
219         "                 [SETSTRIPE_OPTIONS|-f|--file VICTIM_FILE]\n"  \
220         "                 [--no-verify]\n"
221
222 #define SETSTRIPE_USAGE                                                 \
223         SSM_CMD_COMMON("setstripe")                                     \
224         MIRROR_EXTEND_USAGE                                             \
225         "                 DIRECTORY|FILENAME\n"
226
227 #define MIGRATE_USAGE                                                   \
228         SSM_CMD_COMMON("migrate  ")                                     \
229         "                 [--block|-b] [--non-block|-n]\n"              \
230         "                 [--non-direct|-D] [--verbose|-v]\n"           \
231         "                 FILENAME\n"
232
233 #define SETDIRSTRIPE_USAGE                                              \
234         "               [--mdt-count|-c stripe_count>\n"                \
235         "               [--help|-h] [--mdt-hash|-H mdt_hash]\n"         \
236         "               [--mdt-index|-i mdt_index[,mdt_index,...]\n"    \
237         "               [--default|-D] [--mode|-o mode]\n"              \
238         "               [--max-inherit|-X max_inherit]\n"               \
239         "               [--max-inherit-rr max_inherit_rr] <dir>\n"      \
240         "To create dir with a foreign (free format) layout :\n"         \
241         "setdirstripe|mkdir --foreign[=FOREIGN_TYPE] -x|-xattr STRING " \
242         "               [--mode|-o MODE] [--flags HEX] DIRECTORY\n"
243
244 /**
245  * command_t mirror_cmdlist - lfs mirror commands.
246  */
247 command_t mirror_cmdlist[] = {
248         { .pc_name = "create", .pc_func = lfs_mirror_create,
249           .pc_help = "Create a mirrored file.\n"
250                 "usage: lfs mirror create --mirror-count|-N[MIRROR_COUNT]\n"
251                 "           [SETSTRIPE_OPTIONS] ... FILENAME|DIRECTORY ...\n" },
252         { .pc_name = "delete", .pc_func = lfs_mirror_delete,
253           .pc_help = "Delete a mirror from a file.\n"
254         "usage: lfs mirror delete {--mirror-id <mirror_id> |\n"
255         "\t               --component-id|--comp-id|-I COMP_ID |\n"
256         "\t               -p <pool>} MIRRORED_FILE ...\n"
257         },
258         { .pc_name = "extend", .pc_func = lfs_mirror_extend,
259           .pc_help = "Extend a mirrored file.\n"
260                 "usage: lfs mirror extend "
261                 "{--mirror-count|-N[MIRROR_COUNT]} [--no-verify] "
262                 "[SETSTRIPE_OPTIONS|-f VICTIM_FILE] ... FILENAME ...\n" },
263         { .pc_name = "split", .pc_func = lfs_mirror_split,
264           .pc_help = "Split a mirrored file.\n"
265         "usage: lfs mirror split {--mirror-id MIRROR_ID |\n"
266         "\t             --component-id|-I COMP_ID|-p POOL} [--destroy|-d]\n"
267         "\t             [-f NEW_FILE] MIRRORED_FILE ...\n" },
268         { .pc_name = "read", .pc_func = lfs_mirror_read,
269           .pc_help = "Read the content of a specified mirror of a file.\n"
270                 "usage: lfs mirror read {--mirror-id|-N MIRROR_ID}\n"
271                 "\t\t[--outfile|-o <output_file>] <mirrored_file>\n" },
272         { .pc_name = "write", .pc_func = lfs_mirror_write,
273           .pc_help = "Write to a specified mirror of a file.\n"
274                 "usage: lfs mirror write {--mirror-id|-N MIRROR_ID}\n"
275                 "\t\t[--inputfile|-i <input_file>] <mirrored_file>\n" },
276         { .pc_name = "copy", .pc_func = lfs_mirror_copy,
277           .pc_help = "Copy a specified mirror to other mirror(s) of a file.\n"
278                 "usage: lfs mirror copy {--read-mirror|-i MIRROR_ID0}\n"
279                 "\t\t{--write-mirror|-o MIRROR_ID1[,...]} <mirrored_file>\n" },
280         { .pc_name = "resync", .pc_func = lfs_mirror_resync,
281           .pc_help = "Resynchronizes out-of-sync mirrored file(s).\n"
282                 "usage: lfs mirror resync [--only MIRROR_ID[,...]>]\n"
283                 "\t\t<mirrored_file> [<mirrored_file2>...]\n" },
284         { .pc_name = "verify", .pc_func = lfs_mirror_verify,
285           .pc_help = "Verify mirrored file(s).\n"
286                 "usage: lfs mirror verify [--only MIRROR_ID[,...]]\n"
287                 "\t\t[--verbose|-v] <mirrored_file> [<mirrored_file2> ...]\n" },
288         { .pc_help = NULL }
289 };
290
291 /**
292  * command_t pcc_cmdlist - lfs pcc commands.
293  */
294 command_t pcc_cmdlist[] = {
295         { .pc_name = "attach", .pc_func = lfs_pcc_attach,
296           .pc_help = "Attach given files to the Persistent Client Cache.\n"
297                 "usage: lfs pcc attach <--id|-i NUM> <file> ...\n"
298                 "\t-i: archive id for RW-PCC\n" },
299         { .pc_name = "attach_fid", .pc_func = lfs_pcc_attach_fid,
300           .pc_help = "Attach given files into PCC by FID(s).\n"
301                 "usage: lfs pcc attach_id {--id|-i NUM} {--mnt|-m MOUNTPOINT} FID ...\n"
302                 "\t-i: archive id for RW-PCC\n"
303                 "\t-m: Lustre mount point\n" },
304         { .pc_name = "state", .pc_func = lfs_pcc_state,
305           .pc_help = "Display the PCC state for given files.\n"
306                 "usage: lfs pcc state <file> ...\n" },
307         { .pc_name = "detach", .pc_func = lfs_pcc_detach,
308           .pc_help = "Detach given files from the Persistent Client Cache.\n"
309                 "usage: lfs pcc detach <file> ...\n" },
310         { .pc_name = "detach_fid", .pc_func = lfs_pcc_detach_fid,
311           .pc_help = "Detach given files from PCC by FID(s).\n"
312                 "usage: lfs pcc detach_fid <mntpath> <fid>...\n" },
313         { .pc_help = NULL }
314 };
315
316 /* all available commands */
317 command_t cmdlist[] = {
318         {"setstripe", lfs_setstripe, 0,
319          "To create a file with specified striping/composite layout, or\n"
320          "create/replace the default layout on an existing directory:\n"
321          SSM_CMD_COMMON("setstripe")
322          "                 [--mode MODE]\n"
323          "                 <directory|filename>\n"
324          " or\n"
325          "To add component(s) to an existing composite file:\n"
326          SSM_CMD_COMMON("setstripe --component-add")
327          "To totally delete the default striping from an existing directory:\n"
328          "usage: setstripe [--delete|-d] <directory>\n"
329          " or\n"
330          "To create a mirrored file or set s default mirror layout on a directory:\n"
331          "usage: setstripe {--mirror-count|-N}[MIRROR_COUNT] [SETSTRIPE_OPTIONS] <directory|filename>\n"
332          " or\n"
333          "To delete the last component(s) from an existing composite file\n"
334          "(note that this will also delete any data in those components):\n"
335          "usage: setstripe --component-del [--component-id|-I COMP_ID]\n"
336          "                               [--component-flags|-F COMP_FLAGS]\n"
337          "                               <filename>\n"
338          "\tCOMP_ID:     Unique component ID to delete\n"
339          "\tCOMP_FLAGS:  'init' indicating all instantiated components\n"
340          "\t             '^init' indicating all uninstantiated components\n"
341          "\t-I and -F cannot be specified at the same time\n"
342          " or\n"
343          "To set or clear flags on a specific component\n"
344          "(note that this command can only be applied to mirrored files:\n"
345          "usage: setstripe --comp-set {-I COMP_ID|--comp-flags=COMP_FLAGS}\n"
346          "                            <filename>\n"
347          " or\n"
348          "To create a file with a foreign (free format) layout:\n"
349          "usage: setstripe --foreign[=FOREIGN_TYPE]\n"
350          "                 --xattr|-x LAYOUT_STRING [--flags HEX]\n"
351          "                 [--mode MODE] <filename>\n"},
352         {"getstripe", lfs_getstripe, 0,
353          "To list the layout pattern for a given file or files in a\n"
354          "directory or recursively for all files in a directory tree.\n"
355          "usage: getstripe [--ost|-O UUID] [--quiet|-q] [--verbose|-v]\n"
356          "                 [--stripe-count|-c] [--stripe-index|-i] [--fid|-F]\n"
357          "                 [--pool|-p] [--stripe-size|-S] [--directory|-d]\n"
358          "                 [--mdt-index|-m] [--recursive|-r] [--raw|-R]\n"
359          "                 [--layout|-L] [--generation|-g] [--yaml|-y]\n"
360          "                 [--help|-h] [--hex-idx]\n"
361          "                 [--component-id|-I[=COMP_ID]]\n"
362          "                 [--component-flags[=COMP_FLAGS]]\n"
363          "                 [--component-count]\n"
364          "                 [--extension-size|--ext-size|-z]\n"
365          "                 [--component-start[=[+-]COMP_START]]\n"
366          "                 [--component-end[=[+-]COMP_END]|-E[[+-]comp_end]]\n"
367          "                 [[!] --mirror-index=[+-]INDEX |\n"
368          "                 [!] --mirror-id=[+-]MIRROR_ID] [--mirror-count|-N]\n"
369          "                 [--no-follow]\n"
370          "                 <directory|filename> ..."},
371         {"setdirstripe", lfs_setdirstripe, 0,
372          "Create striped directory on specified MDT, same as mkdir.\n"
373          "May be restricted to root or group users, depending on settings.\n"
374          "usage: setdirstripe [OPTION] <directory>\n"
375          SETDIRSTRIPE_USAGE},
376         {"getdirstripe", lfs_getdirstripe, 0,
377          "To list the layout pattern info for a given directory\n"
378          "or recursively for all directories in a directory tree.\n"
379          "usage: getdirstripe [--mdt-count|-c] [--mdt-index|-m|-i]\n"
380          "                    [--help|-h] [--hex-idx] [--mdt-hash|-H]\n"
381          "                    [--obd|-O UUID] [--recursive|-r] [--raw|-R]\n"
382          "                    [--yaml|-y] [--verbose|-v] [--default|-D]\n"
383          "                    [--max-inherit|-X]\n"
384          "                    [--max-inherit-rr] <dir> ..."},
385         {"mkdir", lfs_setdirstripe, 0,
386          "Create striped directory on specified MDT, same as setdirstripe.\n"
387          "usage: mkdir [OPTION] <directory>\n"
388          SETDIRSTRIPE_USAGE},
389         {"rm_entry", lfs_rmentry, 0,
390          "To remove the name entry of the remote directory. Note: This\n"
391          "command will only delete the name entry, i.e. the remote directory\n"
392          "will become inaccessable after this command. This can only be done\n"
393          "by the administrator\n"
394          "usage: rm_entry <dir>\n"},
395         {"rmentry", lfs_rmentry, 0, "remove a dir entry, same as 'rm_entry'\n"},
396         {"unlink_foreign", lfs_unlink_foreign, 0,
397          "To remove the foreign file/dir.\n"
398          "Note: This is for files/dirs prevented to be removed using\n"
399          "unlink/rmdir, but works also for regular ones\n"
400          "usage: unlink_foreign <foreign_dir/file> [<foreign_dir/file> ...]\n"},
401         {"pool_list", lfs_poollist, 0,
402          "List pools or pool OSTs\n"
403          "usage: pool_list <fsname>[.<pool>] | <pathname>\n"},
404         {"find", lfs_find, 0,
405          "find files matching given attributes recursively in directory tree.\n"
406          "usage: find <directory|filename> ...\n"
407          "     [[!] --atime|-A [+-]N[smhdwy]] [[!] --btime|-B [+-]N[smhdwy]]\n"
408          "     [[!] --ctime|-C [+-]N[smhdwy]] [[!] --mtime|-M [+-]N[smhdwy]]\n"
409          "     [[!] --blocks|-b N] [[!] --component-count [+-]<comp_cnt>]\n"
410          "     [[!] --component-start [+-]N[kMGTPE]]\n"
411          "     [[!] --component-end|-E [+-]N[kMGTPE]]\n"
412          "     [[!] --component-flags {init,stale,prefer,offline,nosync,extension}]\n"
413          "     [[!] --extension-size|--ext-size|-z [+-]N[kMGT]]\n"
414          "     [[!] --foreign[=<foreign_type>]]\n"
415          "     [[!] --gid|-g|--group|-G <gid>|<gname>] [--help|-h]\n"
416          "     [[!] --layout|-L released,raid0,mdt] [--lazy|-l] [[!] --links [+-]n]\n"
417          "     [--maxdepth|-D N] [[!] --mdt-count|-T [+-]<stripes>]\n"
418          "     [[!] --mdt-hash|-H <[^][blm],[^]fnv_1a_64,all_char,crush,...>\n"
419          "     [[!] --mdt-index|--mdt|-m <uuid|index,...>]\n"
420          "     [[!] --mirror-count|-N [+-]<n>]\n"
421          "     [[!] --mirror-state <[^]state>]\n"
422          "     [[!] --name|-n <pattern>] [[!] --newer[XY] <reference>]\n"
423          "     [[!] --ost|-O <uuid|index,...>] [[!] --perm [/-]mode]\n"
424          "     [[!] --pool <pool>] [--print|-P] [--print0|-0] [--printf <format>]\n"
425          "     [[!] --projid <projid>] [[!] --size|-s [+-]N[bkMGTPE]]\n"
426          "     [[!] --stripe-count|-c [+-]<stripes>]\n"
427          "     [[!] --stripe-index|-i <index,...>]\n"
428          "     [[!] --stripe-size|-S [+-]N[kMGT]] [[!] --type|-t <filetype>]\n"
429          "     [[!] --uid|-u|--user|-U <uid>|<uname>]\n"
430          "\t !: used before an option indicates 'NOT' requested attribute\n"
431          "\t -: used before a value indicates less than requested value\n"
432          "\t +: used before a value indicates more than requested value\n"
433          "\t ^: used before a flag indicates to exclude it\n"},
434         {"check", lfs_check, 0,
435          "Display the status of MGTs, MDTs or OSTs (as specified in the command)\n"
436          "or all the servers (MGTs, MDTs and OSTs) [for specified path only].\n"
437          "usage: check {mgts|osts|mdts|all} [path]"},
438         {"osts", lfs_osts, 0, "list OSTs connected to client "
439          "[for specified path only]\n" "usage: osts [path]"},
440         {"mdts", lfs_mdts, 0, "list MDTs connected to client "
441          "[for specified path only]\n" "usage: mdts [path]"},
442         {"df", lfs_df, 0,
443          "report filesystem disk space usage or inodes usage "
444          "of each MDS and all OSDs or a batch belonging to a specific pool.\n"
445          "Usage: df [--inodes|-i] [--human-readable|-h] [--lazy|-l]\n"
446          "          [--pool|-p <fsname>[.<pool>]] [path]"},
447         {"getname", lfs_getname, 0,
448          "list instances and specified mount points [for specified path only]\n"
449          "Usage: getname [--help|-h] [--instance|-i] [--fsname|-n] [path ...]"},
450 #ifdef HAVE_SYS_QUOTA_H
451         {"setquota", lfs_setquota, 0, "Set filesystem quotas.\n"
452          "usage: setquota [-t][-D] {-u|-U|-g|-G|-p|-P} {-b|-B|-i|-I LIMIT} [--pool POOL] FILESYSTEM\n"
453          "       setquota {-u|-g|-p} --delete FILESYSTEM\n"},
454         {"quota", lfs_quota, 0, "Display disk usage and limits.\n"
455          "usage: quota [-q] [-v] [-h] [-o OBD_UUID|-i MDT_IDX|-I OST_IDX]\n"
456          "             [{-u|-g|-p} UNAME|UID|GNAME|GID|PROJID]\n"
457          "             [--pool <OST pool name>] <filesystem>\n"
458          "       quota -t <-u|-g|-p> [--pool <OST pool name>] <filesystem>\n"
459          "       quota [-q] [-v] [h] {-U|-G|-P} [--pool <OST pool name>] <filesystem>"},
460         {"project", lfs_project, 0,
461          "Change or list project attribute for specified file or directory.\n"
462          "usage: project [-d|-r] <file|directory...>\n"
463          "         list project ID and flags on file(s) or directories\n"
464          "       project [-p id] [-s] [-r] <file|directory...>\n"
465          "         set project ID and/or inherit flag for specified file(s) or directories\n"
466          "       project -c [-d|-r [-p id] [-0]] <file|directory...>\n"
467          "         check project ID and flags on file(s) or directories, print outliers\n"
468          "       project -C [-d|-r] [-k] <file|directory...>\n"
469          "         clear the project inherit flag and ID on the file or directory\n"
470         },
471 #endif
472         {"flushctx", lfs_flushctx, 0,
473          "Flush security context for current user.\n"
474          "usage: flushctx [-k] [-r] [mountpoint...]"},
475         {"changelog", lfs_changelog, 0,
476          "Show the metadata changes on an MDT."
477          "\nusage: changelog <mdtname> [startrec [endrec]]"},
478         {"changelog_clear", lfs_changelog_clear, 0,
479          "Indicate that old changelog records up to <endrec> are no longer of "
480          "interest to consumer <id>, allowing the system to free up space.\n"
481          "An <endrec> of 0 means all records.\n"
482          "usage: changelog_clear <mdtname> <id> <endrec>"},
483         {"fid2path", lfs_fid2path, 0,
484          "Resolve the full path(s) for given FID(s). For a specific hardlink "
485          "specify link number <linkno>.\n"
486          "usage: fid2path [--print-fid|-f] [--print-link|-c] [--link|-l <linkno>] "
487          "[--print0|-0] <fsname|root> <fid>..."},
488         {"path2fid", lfs_path2fid, 0, "Display the fid(s) for a given path(s).\n"
489          "usage: path2fid [--parents] <path> ..."},
490         {"rmfid", lfs_rmfid, 0, "Remove file(s) by FID(s)\n"
491          "usage: rmfid <fsname|rootpath> <fid> ..."},
492         {"data_version", lfs_data_version, 0, "Display file data version for "
493          "a given path.\n" "usage: data_version [-n|-r|-w] <path>"},
494         {"hsm_state", lfs_hsm_state, 0, "Display the HSM information (states, "
495          "undergoing actions) for given files.\n usage: hsm_state <file> ..."},
496         {"hsm_set", lfs_hsm_set, 0, "Set HSM user flag on specified files.\n"
497          "usage: hsm_set [--norelease] [--noarchive] [--dirty] [--exists] "
498          "[--archived] [--lost] [--archive-id NUM] <file> ..."},
499         {"hsm_clear", lfs_hsm_clear, 0, "Clear HSM user flag on specified "
500          "files.\n"
501          "usage: hsm_clear [--norelease] [--noarchive] [--dirty] [--exists] "
502          "[--archived] [--lost] <file> ..."},
503         {"hsm_action", lfs_hsm_action, 0, "Display current HSM request for "
504          "given files.\n" "usage: hsm_action <file> ..."},
505         {"hsm_archive", lfs_hsm_archive, 0,
506          "Archive file to external storage.\n"
507          "usage: hsm_archive [--filelist FILELIST] [--data DATA] [--archive NUM] "
508          "<file> ..."},
509         {"hsm_restore", lfs_hsm_restore, 0,
510          "Restore file from external storage.\n"
511          "usage: hsm_restore [--filelist FILELIST] [--data DATA] <file> ..."},
512         {"hsm_release", lfs_hsm_release, 0,
513          "Release files from Lustre.\n"
514          "usage: hsm_release [--filelist FILELIST] [--data DATA] <file> ..."},
515         {"hsm_remove", lfs_hsm_remove, 0,
516          "Remove file copy from external storage.\n"
517          "usage: hsm_remove [--filelist FILELIST] [--data DATA] "
518          "[--archive NUM]\n"
519          "                  (FILE [FILE ...] | "
520          "--mntpath MOUNTPATH FID [FID ...])\n"
521          "\n"
522          "Note: To remove an archived copy of a file already deleted from a "
523          "Lustre FS, the\n"
524          "--mntpath option and a list of FIDs must be specified"
525         },
526         {"hsm_cancel", lfs_hsm_cancel, 0,
527          "Cancel requests related to specified files.\n"
528          "usage: hsm_cancel [--filelist FILELIST] [--data DATA] <file> ..."},
529         {"swap_layouts", lfs_swap_layouts, 0, "Swap layouts between 2 files.\n"
530          "usage: swap_layouts <path1> <path2>"},
531         {"migrate", lfs_setstripe_migrate, 0,
532          "migrate directories and their inodes between MDTs.\n"
533          "usage: migrate [--mdt-count|-c STRIPE_COUNT] [--directory|-d]\n"
534          "               [--mdt-hash|-H HASH_TYPE]\n"
535          "               [--mdt-index|-m START_MDT_INDEX] [--verbose|-v]\n"
536          "               DIRECTORY\n"
537          "\n"
538          "migrate file objects from one OST layout to another\n"
539          "(may be not safe with concurent writes).\n"
540          MIGRATE_USAGE },
541         {"mv", lfs_mv, 0,
542          "To move directories between MDTs. This command is deprecated, "
543          "use \"migrate\" instead.\n"
544          "usage: mv <directory|filename> [--mdt-index|-m MDT_INDEX] "
545          "[--verbose|-v]\n"},
546         {"ladvise", lfs_ladvise, 0,
547          "Provide servers with advice about access patterns for a file.\n"
548          "usage: ladvise [--advice|-a ADVICE] [--start|-s START[kMGT]]\n"
549          "               [--background|-b] [--unset|-u]\n\n"
550          "               {--end|-e END[kMGT]|--length|-l LENGTH[kMGT]}\n"
551          "               {[--mode|-m [READ,WRITE]}\n"
552          "               <file> ...\n"},
553         {"mirror", lfs_mirror, mirror_cmdlist,
554          "lfs commands used to manage files with mirrored components:\n"
555          "lfs mirror create - create a mirrored file or directory\n"
556          "lfs mirror extend - add mirror(s) to an existing file\n"
557          "lfs mirror split  - split a mirror from an existing mirrored file\n"
558          "lfs mirror resync - resynchronize out-of-sync mirrored file(s)\n"
559          "lfs mirror read   - read a mirror content of a mirrored file\n"
560          "lfs mirror write  - write to a mirror of a mirrored file\n"
561          "lfs mirror copy   - copy a mirror to other mirror(s) of a file\n"
562          "lfs mirror verify - verify mirrored file(s)\n"},
563         {"getsom", lfs_getsom, 0, "To list the SOM info for a given file.\n"
564          "usage: getsom [-s] [-b] [-f] <path>\n"
565          "\t-s: Only show the size value of the SOM data for a given file\n"
566          "\t-b: Only show the blocks value of the SOM data for a given file\n"
567          "\t-f: Only show the flags value of the SOM data for a given file\n"},
568         {"heat_get", lfs_heat_get, 0,
569          "To get heat of files.\n"
570          "usage: heat_get <file> ...\n"},
571         {"heat_set", lfs_heat_set, 0,
572          "To set heat flags of files.\n"
573          "usage: heat_set [--clear|-c] [--off|-o] [--on|-O] <file> ...\n"
574          "\t--clear|-c: Clear file heat for given files\n"
575          "\t--off|-o:   Turn off file heat for given files\n"
576          "\t--on|-O:    Turn on file heat for given files\n"},
577         {"pcc", lfs_pcc, pcc_cmdlist,
578          "lfs commands used to interact with PCC features:\n"
579          "lfs pcc attach - attach given files to Persistent Client Cache\n"
580          "lfs pcc attach_fid - attach given files into PCC by FID(s)\n"
581          "lfs pcc state  - display the PCC state for given files\n"
582          "lfs pcc detach - detach given files from Persistent Client Cache\n"
583          "lfs pcc detach_fid - detach given files from PCC by FID(s)\n"},
584         { 0, 0, 0, NULL }
585 };
586
587 static int check_hashtype(const char *hashtype)
588 {
589         int type_num = atoi(hashtype);
590         int i;
591
592         /* numeric hash type */
593         if (hashtype && lmv_is_known_hash_type(type_num))
594                 return type_num;
595         /* string hash type */
596         for (i = LMV_HASH_TYPE_ALL_CHARS; i < ARRAY_SIZE(mdt_hash_name); i++)
597                 if (strcmp(hashtype, mdt_hash_name[i]) == 0)
598                         return i;
599
600         return 0;
601 }
602
603 static uint32_t check_foreign_type_name(const char *foreign_type_name)
604 {
605         uint32_t i;
606
607         for (i = 0; i < LU_FOREIGN_TYPE_UNKNOWN; i++) {
608                 if (!lu_foreign_types[i].lft_name)
609                         break;
610                 if (strcmp(foreign_type_name,
611                            lu_foreign_types[i].lft_name) == 0)
612                         return lu_foreign_types[i].lft_type;
613         }
614
615         return LU_FOREIGN_TYPE_UNKNOWN;
616 }
617
618 static const char *error_loc = "syserror";
619
620 static int
621 migrate_open_files(const char *name, __u64 migration_flags,
622                    const struct llapi_stripe_param *param,
623                    struct llapi_layout *layout, int *fd_src_ptr,
624                    int *fd_dst_ptr)
625 {
626         int                      fd_src = -1;
627         int                      fd_dst = -1;
628         int                      rflags;
629         int                      mdt_index;
630         int                      random_value;
631         char                     parent[PATH_MAX];
632         char                     volatile_file[PATH_MAX];
633         char                    *ptr;
634         int                      rc;
635         struct stat              st;
636         struct stat              stv;
637
638         if (!param && !layout) {
639                 error_loc = "layout information";
640                 return -EINVAL;
641         }
642
643         /* search for file directory pathname */
644         if (strlen(name) > sizeof(parent) - 1) {
645                 error_loc = "source file name";
646                 return -ERANGE;
647         }
648
649         strncpy(parent, name, sizeof(parent));
650         ptr = strrchr(parent, '/');
651         if (!ptr) {
652                 if (!getcwd(parent, sizeof(parent))) {
653                         error_loc = "getcwd";
654                         return -errno;
655                 }
656         } else {
657                 if (ptr == parent) /* leading '/' */
658                         ptr = parent + 1;
659                 *ptr = '\0';
660         }
661
662         /* even if the file is only read, WR mode is nedeed to allow
663          * layout swap on fd
664          */
665         /* Allow migrating even without the key on encrypted files */
666         rflags = O_RDWR | O_NOATIME | O_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                       enum stats_flag stats_flag,
795                       ssize_t read_bytes, size_t write_bytes,
796                       off_t file_size_bytes)
797 {
798         struct timespec diff = timespec_sub(start_time, now);
799
800         if (stats_flag == STATS_ON && ((diff.tv_sec != 0) ||
801                 (diff.tv_nsec != 0)) && file_size_bytes != 0)
802                 printf("- { seconds: %li, rmbps: %5.2g, wmbps: %5.2g, copied: %lu, size: %lu, pct: %lu%% }\n",
803                         diff.tv_sec,
804                         (double) read_bytes/((ONE_MB * diff.tv_sec) +
805                                 ((ONE_MB * diff.tv_nsec)/NSEC_PER_SEC)),
806                         (double) write_bytes/((ONE_MB * diff.tv_sec) +
807                                 ((ONE_MB * diff.tv_nsec)/NSEC_PER_SEC)),
808                         write_bytes/ONE_MB,
809                         file_size_bytes/ONE_MB,
810                         ((write_bytes*100)/file_size_bytes));
811 }
812
813 static int migrate_copy_data(int fd_src, int fd_dst, int (*check_file)(int),
814                              unsigned long long bandwidth_bytes_sec,
815                              enum stats_flag stats_flag,
816                              long stats_interval_sec, off_t file_size_bytes)
817 {
818         struct llapi_layout *layout;
819         size_t buf_size = 64 * ONE_MB;
820         uint64_t stripe_size = ONE_MB;
821         void *buf = NULL;
822         off_t pos = 0;
823         off_t data_end = 0;
824         size_t page_size = sysconf(_SC_PAGESIZE);
825         bool sparse;
826         int rc;
827         size_t write_bytes = 0;
828         ssize_t read_bytes = 0;
829         struct timespec start_time;
830         struct timespec now;
831         struct timespec last_bw_print;
832
833         layout = llapi_layout_get_by_fd(fd_src, 0);
834         if (layout) {
835                 rc = llapi_layout_stripe_size_get(layout, &stripe_size);
836                 if (rc == 0) {
837                         /* We like big bufs */
838                         if (stripe_size > buf_size)
839                                 buf_size = stripe_size;
840                         else
841                                 /* Trim to stripe_size multiple */
842                                 buf_size -= buf_size % stripe_size;
843                 }
844
845                 llapi_layout_free(layout);
846         }
847
848         /* limit transfer size to what can be sent in one second */
849         if (bandwidth_bytes_sec && bandwidth_bytes_sec < buf_size)
850                 buf_size = (bandwidth_bytes_sec + stripe_size - 1) &
851                         ~(stripe_size - 1);
852
853         /* Use a page-aligned buffer for direct I/O */
854         rc = posix_memalign(&buf, page_size, buf_size);
855         if (rc != 0)
856                 return -rc;
857
858         sparse = llapi_file_is_sparse(fd_src);
859         if (sparse) {
860                 rc = ftruncate(fd_dst, pos);
861                 if (rc < 0) {
862                         rc = -errno;
863                         return rc;
864                 }
865         }
866
867         clock_gettime(CLOCK_REALTIME, &start_time);
868         now = last_bw_print = start_time;
869
870         while (1) {
871                 off_t data_off;
872                 size_t to_read, to_write;
873                 ssize_t rsize;
874
875                 if (sparse && pos >= data_end) {
876                         size_t data_size;
877
878                         data_off = llapi_data_seek(fd_src, pos, &data_size);
879                         if (data_off < 0) {
880                                 /* Non-fatal, switch to full copy */
881                                 sparse = false;
882                                 continue;
883                         }
884                         /* hole at the end of file, truncate up to it */
885                         if (!data_size) {
886                                 rc = ftruncate(fd_dst, data_off);
887                                 if (rc < 0)
888                                         goto out;
889                         }
890                         pos = data_off & ~(page_size - 1);
891                         data_end = data_off + data_size;
892                         to_read = ((data_end - pos - 1) | (page_size - 1)) + 1;
893                         to_read = MIN(to_read, buf_size);
894                 } else {
895                         to_read = buf_size;
896                 }
897
898                 if (check_file) {
899                         rc = check_file(fd_src);
900                         if (rc < 0)
901                                 goto out;
902                 }
903
904                 rsize = pread(fd_src, buf, to_read, pos);
905                 read_bytes += rsize;
906                 if (rsize < 0) {
907                         rc = -errno;
908                         goto out;
909                 }
910                 /* EOF */
911                 if (rsize == 0)
912                         break;
913
914                 to_write = rsize;
915                 while (to_write > 0) {
916                         unsigned long long write_target;
917                         ssize_t written;
918                         struct timespec diff;
919
920                         written = pwrite(fd_dst, buf, to_write, pos);
921                         if (written < 0) {
922                                 rc = -errno;
923                                 goto out;
924                         }
925                         pos += written;
926                         to_write -= written;
927                         write_bytes += written;
928
929                         if (bandwidth_bytes_sec == 0)
930                                 continue;
931
932                         clock_gettime(CLOCK_REALTIME, &now);
933                         diff = timespec_sub(&start_time, &now);
934                         write_target = ((bandwidth_bytes_sec * diff.tv_sec) +
935                                 ((bandwidth_bytes_sec *
936                                 diff.tv_nsec)/NSEC_PER_SEC));
937
938                         if (write_target < write_bytes) {
939                                 unsigned long long excess;
940                                 struct timespec delay = { 0, 0 };
941
942                                 excess = write_bytes - write_target;
943
944                                 if (excess == 0)
945                                         continue;
946
947                                 delay.tv_sec = excess / bandwidth_bytes_sec;
948                                 delay.tv_nsec = (excess % bandwidth_bytes_sec) *
949                                         NSEC_PER_SEC / bandwidth_bytes_sec;
950
951                                 do {
952                                         rc = clock_nanosleep(CLOCK_REALTIME, 0,
953                                                              &delay, &delay);
954                                 } while (rc < 0 && errno == EINTR);
955
956                                 if (rc < 0) {
957                                         if (stats_flag == STATS_OFF)
958                                                 fprintf(stderr,
959                                                         "error %s: delay for bandwidth control failed: %s\n",
960                                                         progname,
961                                                         strerror(-rc));
962                                         rc = 0;
963                                 }
964                         }
965                 }
966
967                 clock_gettime(CLOCK_REALTIME, &now);
968                 if ((write_bytes != file_size_bytes) &&
969                         (now.tv_sec >= last_bw_print.tv_sec +
970                         stats_interval_sec)) {
971                         stats_log(&now, &start_time, stats_flag,
972                                   read_bytes, write_bytes,
973                                   file_size_bytes);
974                         last_bw_print = now;
975                 }
976
977                 if (rc || rsize < to_read)
978                         break;
979         }
980
981         /* Output at least one log, regardless of stats_interval */
982         clock_gettime(CLOCK_REALTIME, &now);
983         stats_log(&now, &start_time, stats_flag,
984                   read_bytes, write_bytes,
985                   file_size_bytes);
986
987         rc = fsync(fd_dst);
988         if (rc < 0)
989                 rc = -errno;
990 out:
991         /* Try to avoid page cache pollution after migration. */
992         (void)posix_fadvise(fd_src, 0, 0, POSIX_FADV_DONTNEED);
993         (void)posix_fadvise(fd_dst, 0, 0, POSIX_FADV_DONTNEED);
994
995         free(buf);
996         return rc;
997 }
998
999 static int migrate_set_timestamps(int fd, const struct stat *st)
1000 {
1001         struct timeval tv[2] = {
1002                 {.tv_sec = st->st_atime},
1003                 {.tv_sec = st->st_mtime}
1004         };
1005
1006         return futimes(fd, tv);
1007 }
1008
1009 static int migrate_block(int fd_src, int fd_dst,
1010                          unsigned long long bandwidth_bytes_sec,
1011                          enum stats_flag stats_flag,
1012                          long stats_interval_sec)
1013 {
1014         struct stat st;
1015         __u64   dv1;
1016         int     gid;
1017         int     rc;
1018         int     rc2;
1019
1020         do
1021                 gid = random();
1022         while (gid == 0);
1023
1024
1025         /* The grouplock blocks all concurrent accesses to the file. */
1026         rc = llapi_group_lock(fd_src, gid);
1027         if (rc < 0) {
1028                 error_loc = "cannot get group lock";
1029                 return rc;
1030         }
1031
1032         rc = fstat(fd_src, &st);
1033         if (rc < 0) {
1034                 error_loc = "cannot stat source file";
1035                 rc = -errno;
1036                 goto out_unlock;
1037         }
1038
1039         /*
1040          * LL_DV_RD_FLUSH should not be set, otherwise the servers will try to
1041          * get extent locks on the OST objects. This will conflict with our
1042          * extent group locks.
1043          */
1044         rc = llapi_get_data_version(fd_src, &dv1, 0);
1045         if (rc < 0) {
1046                 error_loc = "cannot get dataversion";
1047                 goto out_unlock;
1048         }
1049
1050         rc = migrate_copy_data(fd_src, fd_dst, NULL, bandwidth_bytes_sec,
1051                                stats_flag, stats_interval_sec,
1052                                st.st_size);
1053         if (rc < 0) {
1054                 error_loc = "data copy failed";
1055                 goto out_unlock;
1056         }
1057
1058         /* Make sure we keep original atime/mtime values */
1059         rc = migrate_set_timestamps(fd_dst, &st);
1060         if (rc < 0) {
1061                 error_loc = "set target file timestamp failed";
1062                 goto out_unlock;
1063         }
1064
1065         /*
1066          * swap layouts
1067          * for a migration we need to check data version on file did
1068          * not change.
1069          *
1070          * Pass in gid=0 since we already own grouplock.
1071          */
1072         rc = llapi_fswap_layouts_grouplock(fd_src, fd_dst, dv1, 0, 0,
1073                                            SWAP_LAYOUTS_CHECK_DV1);
1074         if (rc == -EAGAIN) {
1075                 error_loc = "file changed";
1076                 goto out_unlock;
1077         } else if (rc < 0) {
1078                 error_loc = "cannot swap layout";
1079                 goto out_unlock;
1080         }
1081
1082 out_unlock:
1083         rc2 = llapi_group_unlock(fd_src, gid);
1084         if (rc2 < 0 && rc == 0) {
1085                 error_loc = "unlock group lock";
1086                 rc = rc2;
1087         }
1088
1089         return rc;
1090 }
1091
1092 /**
1093  * Internal helper for migrate_copy_data(). Check lease and report error if
1094  * need be.
1095  *
1096  * \param[in]  fd           File descriptor on which to check the lease.
1097  *
1098  * \retval 0       Migration can keep on going.
1099  * \retval -errno  Error occurred, abort migration.
1100  */
1101 static int check_lease(int fd)
1102 {
1103         int rc;
1104
1105         rc = llapi_lease_check(fd);
1106         if (rc > 0)
1107                 return 0; /* llapi_check_lease returns > 0 on success. */
1108
1109         return -EBUSY;
1110 }
1111
1112 static int migrate_nonblock(int fd_src, int fd_dst,
1113                             unsigned long long bandwidth_bytes_sec,
1114                             enum stats_flag stats_flag,
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, stats_flag,
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                         enum stats_flag stats_flag, 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, migration_flags,
1381                                         bandwidth_bytes_sec, stats_flag,
1382                                         stats_interval_sec);
1383                 if (rc)
1384                         error_loc = "cannot migrate to DOM layout";
1385                 goto out_closed;
1386         }
1387
1388         if (stats_flag == STATS_ON)
1389                 printf("%s:\n", name);
1390
1391         if (!(migration_flags & LLAPI_MIGRATION_NONBLOCK)) {
1392                 /*
1393                  * Blocking mode (forced if servers do not support file lease).
1394                  * It is also the default mode, since we cannot distinguish
1395                  * between a broken lease and a server that does not support
1396                  * atomic swap/close (LU-6785)
1397                  */
1398                 rc = migrate_block(fd_src, fd_dst, bandwidth_bytes_sec,
1399                                    stats_flag, stats_interval_sec);
1400                 goto out;
1401         }
1402
1403         rc = llapi_lease_acquire(fd_src, LL_LEASE_RDLCK);
1404         if (rc < 0) {
1405                 error_loc = "cannot get lease";
1406                 goto out;
1407         }
1408
1409         rc = migrate_nonblock(fd_src, fd_dst, bandwidth_bytes_sec, stats_flag,
1410                               stats_interval_sec);
1411         if (rc < 0) {
1412                 llapi_lease_release(fd_src);
1413                 goto out;
1414         }
1415
1416         /*
1417          * Atomically put lease, swap layouts and close.
1418          * for a migration we need to check data version on file did
1419          * not change.
1420          */
1421         rc = llapi_fswap_layouts(fd_src, fd_dst, 0, 0, SWAP_LAYOUTS_CLOSE);
1422         if (rc < 0) {
1423                 error_loc = "cannot swap layout";
1424                 goto out;
1425         }
1426
1427 out:
1428         if (fd_src >= 0)
1429                 close(fd_src);
1430
1431         if (fd_dst >= 0)
1432                 close(fd_dst);
1433 out_closed:
1434         if (rc < 0)
1435                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1436                         progname, name, error_loc, strerror(-rc));
1437         else if (migration_flags & LLAPI_MIGRATION_VERBOSE)
1438                 printf("%s\n", name);
1439
1440         return rc;
1441 }
1442
1443 static int comp_str2flags(char *string, __u32 *flags, __u32 *neg_flags)
1444 {
1445         char *name;
1446         char *dup_string = NULL;
1447         int rc = 0;
1448
1449         *flags = 0;
1450         *neg_flags = 0;
1451
1452         if (!string || !string[0])
1453                 return -EINVAL;
1454
1455         dup_string = strdup(string);
1456         if (!dup_string) {
1457                 llapi_printf(LLAPI_MSG_ERROR,
1458                              "%s: insufficient memory\n",
1459                              progname);
1460                 return -ENOMEM;
1461         }
1462
1463         for (name = strtok(dup_string, ","); name; name = strtok(NULL, ",")) {
1464                 bool found = false;
1465                 int i;
1466
1467                 for (i = 0; i < ARRAY_SIZE(comp_flags_table); i++) {
1468                         __u32 comp_flag = comp_flags_table[i].cfn_flag;
1469                         const char *comp_name = comp_flags_table[i].cfn_name;
1470
1471                         if (strcmp(name, comp_name) == 0) {
1472                                 *flags |= comp_flag;
1473                                 found = true;
1474                         } else if (strncmp(name, "^", 1) == 0 &&
1475                                    strcmp(name + 1, comp_name) == 0) {
1476                                 *neg_flags |= comp_flag;
1477                                 found = true;
1478                         }
1479                 }
1480                 if (!found) {
1481                         llapi_printf(LLAPI_MSG_ERROR,
1482                                      "%s: component flag '%s' not supported\n",
1483                                      progname, name);
1484                         rc = -EINVAL;
1485                         goto out_free;
1486                 }
1487         }
1488
1489         if (!*flags && !*neg_flags)
1490                 rc = -EINVAL;
1491
1492         /* don't allow to set and exclude the same flag */
1493         if (*flags & *neg_flags)
1494                 rc = -EINVAL;
1495
1496 out_free:
1497         free(dup_string);
1498         return rc;
1499 }
1500
1501 static int mdthash_input(char *string, __u32 *inflags,
1502                          __u32 *exflags, __u32 *type)
1503 {
1504         char *name;
1505         struct mhf_list {
1506                 char *name;
1507                 __u32 flag;
1508         } mhflist[] = {
1509                 {"migrating", LMV_HASH_FLAG_MIGRATION},
1510                 {"bad_type", LMV_HASH_FLAG_BAD_TYPE},
1511                 {"badtype", LMV_HASH_FLAG_BAD_TYPE},
1512                 {"lost_lmv", LMV_HASH_FLAG_LOST_LMV},
1513                 {"lostlmv", LMV_HASH_FLAG_LOST_LMV},
1514         };
1515
1516         if (string == NULL)
1517                 return -EINVAL;
1518
1519         *inflags = 0;
1520         *exflags = 0;
1521         *type = 0;
1522         for (name = strtok(string, ","); name; name = strtok(NULL, ",")) {
1523                 bool found = false;
1524                 int i;
1525
1526                 for (i = 0; i < ARRAY_SIZE(mhflist); i++) {
1527                         if (strcmp(name, mhflist[i].name) == 0 ||
1528                             name[0] == mhflist[i].name[0]) {
1529                                 *inflags |= mhflist[i].flag;
1530                                 found = true;
1531                         } else if (name[0] == '^' &&
1532                                    (strcmp(name + 1, mhflist[i].name) == 0 ||
1533                                     name[1] == mhflist[i].name[0])) {
1534                                 *exflags |= mhflist[i].flag;
1535                                 found = true;
1536                         }
1537                 }
1538                 if (!found) {
1539                         i = check_hashtype(name);
1540                         if (i > 0) {
1541                                 *type |= 1 << i;
1542                                 continue;
1543                         }
1544                         llapi_printf(LLAPI_MSG_ERROR,
1545                                      "%s: invalid mdt_hash value '%s'\n",
1546                                      progname, name);
1547                         return -EINVAL;
1548                 }
1549         }
1550
1551         /* don't allow to include and exclude the same flag */
1552         if (*inflags & *exflags) {
1553                 llapi_printf(LLAPI_MSG_ERROR,
1554                              "%s: include and exclude same flag '%s'\n",
1555                              progname, string);
1556                 return -EINVAL;
1557         }
1558
1559         return 0;
1560 }
1561
1562 static int mirror_str2state(char *string, __u16 *state, __u16 *neg_state)
1563 {
1564         if (!string)
1565                 return -EINVAL;
1566
1567         *state = 0;
1568         *neg_state = 0;
1569
1570         if (strncmp(string, "^", 1) == 0) {
1571                 *neg_state = llapi_layout_string_flags(string + 1);
1572                 if (*neg_state != 0)
1573                         return 0;
1574         } else {
1575                 *state = llapi_layout_string_flags(string);
1576                 if (*state != 0)
1577                         return 0;
1578         }
1579
1580         llapi_printf(LLAPI_MSG_ERROR,
1581                      "%s: mirrored file state '%s' not supported\n",
1582                      progname, string);
1583         return -EINVAL;
1584 }
1585
1586 /**
1587  * struct mirror_args - Command-line arguments for mirror(s).
1588  * @m_count:  Number of mirrors to be created with this layout.
1589  * @m_flags:  Mirror level flags, only 'prefer' is supported.
1590  * @m_layout: Mirror layout.
1591  * @m_file:   A victim file. Its layout will be split and used as a mirror.
1592  * @m_next:   Point to the next node of the list.
1593  *
1594  * Command-line arguments for mirror(s) will be parsed and stored in
1595  * a linked list that consists of this structure.
1596  */
1597 struct mirror_args {
1598         __u32                   m_count;
1599         __u32                   m_flags;
1600         struct llapi_layout     *m_layout;
1601         const char              *m_file;
1602         struct mirror_args      *m_next;
1603         bool                    m_inherit;
1604 };
1605
1606 /**
1607  * enum mirror_flags - Flags for extending a mirrored file.
1608  * @MF_NO_VERIFY: Indicates not to verify the mirror(s) from victim file(s)
1609  *             in case the victim file(s) contains the same data as the
1610  *             original mirrored file.
1611  * @MF_DESTROY: Indicates to delete the mirror from the mirrored file.
1612  * @MF_COMP_ID: specified component id instead of mirror id
1613  *
1614  * Flags for extending a mirrored file.
1615  */
1616 enum mirror_flags {
1617         MF_NO_VERIFY    = 0x1,
1618         MF_DESTROY      = 0x2,
1619         MF_COMP_ID      = 0x4,
1620         MF_COMP_POOL    = 0x8,
1621 };
1622
1623 /**
1624  * mirror_create_sanity_check() - Check mirror list.
1625  * @list:  A linked list that stores the mirror arguments.
1626  *
1627  * This function does a sanity check on @list for creating
1628  * a mirrored file.
1629  *
1630  * Return: 0 on success or a negative error code on failure.
1631  */
1632 static int mirror_create_sanity_check(const char *fname,
1633                                       struct mirror_args *list,
1634                                       bool check_fname)
1635 {
1636         int rc = 0;
1637         bool has_m_file = false;
1638         bool has_m_layout = false;
1639
1640         if (!list)
1641                 return -EINVAL;
1642
1643         if (fname && check_fname) {
1644                 struct llapi_layout *layout;
1645
1646                 layout = llapi_layout_get_by_path(fname, 0);
1647                 if (!layout) {
1648                         fprintf(stderr,
1649                                 "error: %s: file '%s' couldn't get layout\n",
1650                                 progname, fname);
1651                         return -ENODATA;
1652                 }
1653
1654                 rc = llapi_layout_sanity(layout, false, true);
1655
1656                 llapi_layout_free(layout);
1657
1658                 if (rc) {
1659                         llapi_layout_sanity_perror(rc);
1660                         return rc;
1661                 }
1662         }
1663
1664         while (list) {
1665                 if (list->m_file) {
1666                         has_m_file = true;
1667                         llapi_layout_free(list->m_layout);
1668
1669                         list->m_layout =
1670                                 llapi_layout_get_by_path(list->m_file, 0);
1671                         if (!list->m_layout) {
1672                                 fprintf(stderr,
1673                                         "error: %s: file '%s' has no layout\n",
1674                                         progname, list->m_file);
1675                                 return -ENODATA;
1676                         }
1677                 } else {
1678                         has_m_layout = true;
1679                         if (!list->m_layout) {
1680                                 fprintf(stderr, "error: %s: no mirror layout\n",
1681                                         progname);
1682                                 return -EINVAL;
1683                         }
1684                 }
1685
1686                 rc = llapi_layout_sanity(list->m_layout, false, true);
1687                 if (rc) {
1688                         llapi_layout_sanity_perror(rc);
1689                         return rc;
1690                 }
1691
1692                 list = list->m_next;
1693         }
1694
1695         if (has_m_file && has_m_layout) {
1696                 fprintf(stderr,
1697                         "error: %s: -f <victim_file> option should not be specified with setstripe options\n",
1698                         progname);
1699                 return -EINVAL;
1700         }
1701
1702         return 0;
1703 }
1704
1705 static int mirror_set_flags(struct llapi_layout *layout, void *cbdata)
1706 {
1707         __u32 mirror_flags = *(__u32 *)cbdata;
1708         uint32_t flags;
1709         int rc;
1710
1711         rc = llapi_layout_comp_flags_get(layout, &flags);
1712         if (rc < 0)
1713                 return rc;
1714
1715         if (!flags) {
1716                 rc = llapi_layout_comp_flags_set(layout, mirror_flags);
1717                 if (rc)
1718                         return rc;
1719         }
1720
1721         return LLAPI_LAYOUT_ITER_CONT;
1722 }
1723
1724 /**
1725  * mirror_create() - Create a mirrored file.
1726  * @fname:        The file to be created.
1727  * @mirror_list:  A linked list that stores the mirror arguments.
1728  *
1729  * This function creates a mirrored file @fname with the mirror(s)
1730  * from @mirror_list.
1731  *
1732  * Return: 0 on success or a negative error code on failure.
1733  */
1734 static int mirror_create(char *fname, struct mirror_args *mirror_list)
1735 {
1736         struct llapi_layout *layout = NULL;
1737         struct mirror_args *cur_mirror = NULL;
1738         uint16_t mirror_count = 0;
1739         int i = 0;
1740         int rc = 0;
1741
1742         rc = mirror_create_sanity_check(fname, mirror_list, false);
1743         if (rc)
1744                 return rc;
1745
1746         cur_mirror = mirror_list;
1747         while (cur_mirror) {
1748                 rc = llapi_layout_comp_iterate(cur_mirror->m_layout,
1749                                                mirror_set_flags,
1750                                                &cur_mirror->m_flags);
1751                 if (rc) {
1752                         rc = -errno;
1753                         fprintf(stderr, "%s: failed to set mirror flags\n",
1754                                 progname);
1755                         goto error;
1756                 }
1757
1758                 for (i = 0; i < cur_mirror->m_count; i++) {
1759                         rc = llapi_layout_merge(&layout, cur_mirror->m_layout);
1760                         if (rc) {
1761                                 rc = -errno;
1762                                 fprintf(stderr,
1763                                         "error: %s: merge layout failed: %s\n",
1764                                         progname, strerror(errno));
1765                                 goto error;
1766                         }
1767                 }
1768                 mirror_count += cur_mirror->m_count;
1769                 cur_mirror = cur_mirror->m_next;
1770         }
1771
1772         if (!layout) {
1773                 fprintf(stderr, "error: %s: layout is NULL\n", progname);
1774                 return -EINVAL;
1775         }
1776
1777         rc = llapi_layout_mirror_count_set(layout, mirror_count);
1778         if (rc) {
1779                 rc = -errno;
1780                 fprintf(stderr, "error: %s: set mirror count failed: %s\n",
1781                         progname, strerror(errno));
1782                 goto error;
1783         }
1784
1785         rc = lfs_component_create(fname, O_CREAT | O_WRONLY, 0666,
1786                                   layout);
1787         if (rc >= 0) {
1788                 close(rc);
1789                 rc = 0;
1790         }
1791
1792 error:
1793         llapi_layout_free(layout);
1794         return rc;
1795 }
1796
1797 /**
1798  * Compare files and check lease on @fd.
1799  *
1800  * \retval bytes number of bytes are the same
1801  */
1802 static ssize_t mirror_file_compare(int fd_src, int fd_dst)
1803 {
1804         const size_t buflen = 4 * 1024 * 1024; /* 4M */
1805         void *buf;
1806         ssize_t bytes_done = 0;
1807         ssize_t bytes_read = 0;
1808
1809         buf = malloc(buflen * 2);
1810         if (!buf)
1811                 return -ENOMEM;
1812
1813         while (1) {
1814                 if (!llapi_lease_check(fd_src)) {
1815                         bytes_done = -EBUSY;
1816                         break;
1817                 }
1818
1819                 bytes_read = read(fd_src, buf, buflen);
1820                 if (bytes_read <= 0)
1821                         break;
1822
1823                 if (bytes_read != read(fd_dst, buf + buflen, buflen))
1824                         break;
1825
1826                 /*
1827                  * XXX: should compute the checksum on each buffer and then
1828                  * compare checksum to avoid cache collision
1829                  */
1830                 if (memcmp(buf, buf + buflen, bytes_read))
1831                         break;
1832
1833                 bytes_done += bytes_read;
1834         }
1835
1836         free(buf);
1837
1838         return bytes_done;
1839 }
1840
1841 static int mirror_extend_file(const char *fname, const char *victim_file,
1842                               enum mirror_flags mirror_flags)
1843 {
1844         int fd = -1;
1845         int fdv = -1;
1846         struct stat stbuf;
1847         struct stat stbuf_v;
1848         struct ll_ioc_lease *data = NULL;
1849         int rc;
1850
1851         fd = open(fname, O_RDWR);
1852         if (fd < 0) {
1853                 error_loc = "open source file";
1854                 rc = -errno;
1855                 goto out;
1856         }
1857
1858         fdv = open(victim_file, O_RDWR);
1859         if (fdv < 0) {
1860                 error_loc = "open target file";
1861                 rc = -errno;
1862                 goto out;
1863         }
1864
1865         if (fstat(fd, &stbuf) || fstat(fdv, &stbuf_v)) {
1866                 error_loc = "stat source or target file";
1867                 rc = -errno;
1868                 goto out;
1869         }
1870
1871         if (stbuf.st_dev != stbuf_v.st_dev) {
1872                 error_loc = "stat source and target file";
1873                 rc = -EXDEV;
1874                 goto out;
1875         }
1876
1877         /* mirrors should be of the same size */
1878         if (stbuf.st_size != stbuf_v.st_size) {
1879                 error_loc = "file sizes don't match";
1880                 rc = -EINVAL;
1881                 goto out;
1882         }
1883
1884         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1885         if (rc < 0) {
1886                 error_loc = "cannot get lease";
1887                 goto out;
1888         }
1889
1890         if (!(mirror_flags & MF_NO_VERIFY)) {
1891                 ssize_t ret;
1892                 /* mirrors should have the same contents */
1893                 ret = mirror_file_compare(fd, fdv);
1894                 if (ret != stbuf.st_size) {
1895                         error_loc = "file busy or contents don't match";
1896                         rc = ret < 0 ? ret : -EINVAL;
1897                         goto out;
1898                 }
1899         }
1900
1901         /* Get rid of caching pages from clients */
1902         rc = llapi_file_flush(fd);
1903         if (rc < 0) {
1904                 error_loc = "cannot get data version";
1905                 goto out;
1906         }
1907
1908         rc = llapi_file_flush(fdv);
1909         if (rc < 0) {
1910                 error_loc = "cannot get data version";
1911                 goto out;
1912         }
1913
1914         rc = migrate_set_timestamps(fd, &stbuf);
1915         if (rc < 0) {
1916                 error_loc = "cannot set source file timestamp";
1917                 goto out;
1918         }
1919
1920         /* Atomically put lease, merge layouts and close. */
1921         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1922         if (!data) {
1923                 error_loc = "memory allocation";
1924                 goto out;
1925         }
1926         data->lil_mode = LL_LEASE_UNLCK;
1927         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1928         data->lil_count = 1;
1929         data->lil_ids[0] = fdv;
1930         rc = llapi_lease_set(fd, data);
1931         if (rc < 0) {
1932                 error_loc = "cannot merge layout";
1933                 goto out;
1934         } else if (rc == 0) {
1935                 rc = -EBUSY;
1936                 error_loc = "lost lease lock";
1937                 goto out;
1938         }
1939         rc = 0;
1940
1941 out:
1942         if (data)
1943                 free(data);
1944         if (fd >= 0)
1945                 close(fd);
1946         if (fdv >= 0)
1947                 close(fdv);
1948         if (!rc)
1949                 (void) unlink(victim_file);
1950         if (rc < 0)
1951                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1952                         progname, fname, error_loc, strerror(-rc));
1953         return rc;
1954 }
1955
1956 static int mirror_extend_layout(char *name, struct llapi_layout *m_layout,
1957                                 bool inherit, uint32_t flags,
1958                                 unsigned long long bandwidth_bytes_sec,
1959                                 enum stats_flag stats_flag,
1960                                 long stats_interval_sec)
1961 {
1962         struct llapi_layout *f_layout = NULL;
1963         struct ll_ioc_lease *data = NULL;
1964         struct stat st;
1965         int fd_src = -1;
1966         int fd_dst = -1;
1967         int rc = 0;
1968
1969         if (inherit) {
1970                 f_layout = llapi_layout_get_by_path(name, 0);
1971                 if (!f_layout) {
1972                         rc = -EINVAL;
1973                         fprintf(stderr, "%s: cannot get layout\n", progname);
1974                         goto out;
1975                 }
1976                 rc = llapi_layout_get_last_init_comp(f_layout);
1977                 if (rc) {
1978                         fprintf(stderr, "%s: cannot get the last init comp\n",
1979                                 progname);
1980                         goto out;
1981                 }
1982                 rc = llapi_layout_mirror_inherit(f_layout, m_layout);
1983                 if (rc) {
1984                         fprintf(stderr,
1985                                 "%s: cannot inherit from the last init comp\n",
1986                                 progname);
1987                         goto out;
1988                 }
1989         }
1990
1991         llapi_layout_comp_flags_set(m_layout, flags);
1992         rc = migrate_open_files(name,
1993                              LLAPI_MIGRATION_NONDIRECT | LLAPI_MIGRATION_MIRROR,
1994                              NULL, m_layout, &fd_src, &fd_dst);
1995         if (rc < 0)
1996                 goto out;
1997
1998         rc = llapi_lease_acquire(fd_src, LL_LEASE_RDLCK);
1999         if (rc < 0) {
2000                 error_loc = "cannot get lease";
2001                 goto out;
2002         }
2003
2004         rc = fstat(fd_src, &st);
2005         if (rc < 0) {
2006                 error_loc = "cannot stat source file";
2007                 goto out;
2008         }
2009
2010         if (stats_flag)
2011                 printf("%s:\n", name);
2012
2013         rc = migrate_nonblock(fd_src, fd_dst, bandwidth_bytes_sec, stats_flag,
2014                               stats_interval_sec);
2015         if (rc < 0) {
2016                 llapi_lease_release(fd_src);
2017                 goto out;
2018         }
2019
2020         rc = migrate_set_timestamps(fd_src, &st);
2021         if (rc < 0) {
2022                 error_loc = "cannot set source file timestamp";
2023                 goto out;
2024         }
2025
2026         /* Atomically put lease, merge layouts and close. */
2027         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
2028         if (!data) {
2029                 error_loc = "memory allocation";
2030                 goto out;
2031         }
2032         data->lil_mode = LL_LEASE_UNLCK;
2033         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
2034         data->lil_count = 1;
2035         data->lil_ids[0] = fd_dst;
2036         rc = llapi_lease_set(fd_src, data);
2037         if (rc < 0) {
2038                 error_loc = "cannot merge layout";
2039                 goto out;
2040         } else if (rc == 0) {
2041                 rc = -EBUSY;
2042                 error_loc = "lost lease lock";
2043                 goto out;
2044         }
2045         rc = 0;
2046
2047 out:
2048         if (data)
2049                 free(data);
2050         if (fd_src >= 0)
2051                 close(fd_src);
2052         if (fd_dst >= 0)
2053                 close(fd_dst);
2054         if (rc < 0)
2055                 fprintf(stderr, "error: %s: %s: %s: %s\n",
2056                         progname, name, error_loc, strerror(-rc));
2057         return rc;
2058 }
2059
2060 static int mirror_extend(char *fname, struct mirror_args *mirror_list,
2061                          enum mirror_flags mirror_flags,
2062                          unsigned long long bandwidth_bytes_sec,
2063                          enum stats_flag stats_flag, long stats_interval_sec)
2064 {
2065         int rc = 0;
2066
2067         while (mirror_list) {
2068                 if (mirror_list->m_file) {
2069                         rc = mirror_extend_file(fname, mirror_list->m_file,
2070                                                 mirror_flags);
2071                 } else {
2072                         __u32 mirror_count = mirror_list->m_count;
2073
2074                         while (mirror_count > 0) {
2075                                 rc = mirror_extend_layout(fname,
2076                                                         mirror_list->m_layout,
2077                                                         mirror_list->m_inherit,
2078                                                         mirror_list->m_flags,
2079                                                         bandwidth_bytes_sec,
2080                                                         stats_flag,
2081                                                         stats_interval_sec);
2082                                 if (rc)
2083                                         break;
2084
2085                                 --mirror_count;
2086                         }
2087                 }
2088                 if (rc)
2089                         break;
2090
2091                 mirror_list = mirror_list->m_next;
2092         }
2093
2094         return rc;
2095 }
2096
2097 static int find_mirror_id(struct llapi_layout *layout, void *cbdata)
2098 {
2099         uint32_t id;
2100         int rc;
2101
2102         rc = llapi_layout_mirror_id_get(layout, &id);
2103         if (rc < 0)
2104                 return rc;
2105
2106         if ((__u16)id == *(__u16 *)cbdata)
2107                 return LLAPI_LAYOUT_ITER_STOP;
2108
2109         return LLAPI_LAYOUT_ITER_CONT;
2110 }
2111
2112 static int find_comp_id(struct llapi_layout *layout, void *cbdata)
2113 {
2114         uint32_t id;
2115         int rc;
2116
2117         rc = llapi_layout_comp_id_get(layout, &id);
2118         if (rc < 0)
2119                 return rc;
2120
2121         if (id == *(__u32 *)cbdata)
2122                 return LLAPI_LAYOUT_ITER_STOP;
2123
2124         return LLAPI_LAYOUT_ITER_CONT;
2125 }
2126
2127 static int find_mirror_id_by_pool(struct llapi_layout *layout, void *cbdata)
2128 {
2129         char buf[LOV_MAXPOOLNAME + 1];
2130         struct pool_to_id_cbdata *d = (void *)cbdata;
2131         uint32_t id;
2132         int rc;
2133
2134         rc = llapi_layout_pool_name_get(layout, buf, sizeof(buf));
2135         if (rc < 0)
2136                 return rc;
2137         if (strcmp(d->pool, buf))
2138                 return LLAPI_LAYOUT_ITER_CONT;
2139
2140         rc = llapi_layout_mirror_id_get(layout, &id);
2141         if (rc < 0)
2142                 return rc;
2143         d->id = id;
2144
2145         return LLAPI_LAYOUT_ITER_STOP;
2146 }
2147
2148 static int find_comp_id_by_pool(struct llapi_layout *layout, void *cbdata)
2149 {
2150         char buf[LOV_MAXPOOLNAME + 1];
2151         struct pool_to_id_cbdata *d = (void *)cbdata;
2152         uint32_t id;
2153         int rc;
2154
2155         rc = llapi_layout_pool_name_get(layout, buf, sizeof(buf));
2156         if (rc < 0)
2157                 return rc;
2158         if (strcmp(d->pool, buf))
2159                 return LLAPI_LAYOUT_ITER_CONT;
2160
2161         rc = llapi_layout_comp_id_get(layout, &id);
2162         if (rc < 0)
2163                 return rc;
2164         d->id = id;
2165
2166         return LLAPI_LAYOUT_ITER_STOP;
2167 }
2168
2169 struct collect_ids_data {
2170         __u16   *cid_ids;
2171         int     cid_count;
2172         __u16   cid_exclude;
2173 };
2174
2175 static int collect_mirror_id(struct llapi_layout *layout, void *cbdata)
2176 {
2177         struct collect_ids_data *cid = cbdata;
2178         uint32_t id;
2179         int rc;
2180
2181         rc = llapi_layout_mirror_id_get(layout, &id);
2182         if (rc < 0)
2183                 return rc;
2184
2185         if ((__u16)id != cid->cid_exclude) {
2186                 int i;
2187
2188                 for (i = 0; i < cid->cid_count; i++) {
2189                         /* already collected the mirror id */
2190                         if (id == cid->cid_ids[i])
2191                                 return LLAPI_LAYOUT_ITER_CONT;
2192                 }
2193                 cid->cid_ids[cid->cid_count] = id;
2194                 cid->cid_count++;
2195         }
2196
2197         return LLAPI_LAYOUT_ITER_CONT;
2198 }
2199
2200 /**
2201  * last_non_stale_mirror() - Check if a mirror is the last non-stale mirror.
2202  * @mirror_id: Mirror id to be checked.
2203  * @layout:    Mirror component list.
2204  *
2205  * This function checks if a mirror with specified @mirror_id is the last
2206  * non-stale mirror of a layout @layout.
2207  *
2208  * Return: true or false.
2209  */
2210 static inline
2211 bool last_non_stale_mirror(__u16 mirror_id, struct llapi_layout *layout)
2212 {
2213         __u16 mirror_ids[128] = { 0 };
2214         struct collect_ids_data cid = { .cid_ids = mirror_ids,
2215                                         .cid_count = 0,
2216                                         .cid_exclude = mirror_id, };
2217         int i;
2218
2219         llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
2220
2221         for (i = 0; i < cid.cid_count; i++) {
2222                 struct llapi_resync_comp comp_array[1024] = { { 0 } };
2223                 int comp_size = 0;
2224
2225                 comp_size = llapi_mirror_find_stale(layout, comp_array,
2226                                                     ARRAY_SIZE(comp_array),
2227                                                     &mirror_ids[i], 1);
2228                 if (comp_size == 0)
2229                         return false;
2230         }
2231
2232         return true;
2233 }
2234
2235 static int mirror_split(const char *fname, __u32 id, const char *pool,
2236                         enum mirror_flags mflags, const char *victim_file)
2237 {
2238         struct llapi_layout *layout;
2239         char parent[PATH_MAX];
2240         char victim[PATH_MAX];
2241         int flags = O_CREAT | O_EXCL | O_LOV_DELAY_CREATE | O_NOFOLLOW;
2242         char *ptr;
2243         struct ll_ioc_lease *data;
2244         uint16_t mirror_count;
2245         __u32 mirror_id;
2246         int mdt_index;
2247         int fd, fdv;
2248         bool purge = true; /* delete mirror by setting fdv=fd */
2249         bool is_encrypted;
2250         int rc;
2251
2252         if (victim_file && (strcmp(fname, victim_file) == 0)) {
2253                 fprintf(stderr,
2254                         "error %s: the source file '%s' and -f file are the same\n",
2255                         progname, fname);
2256                 return -EINVAL;
2257         }
2258
2259         /* check fname contains mirror with mirror_id/comp_id */
2260         layout = llapi_layout_get_by_path(fname, 0);
2261         if (!layout) {
2262                 fprintf(stderr,
2263                         "error %s: file '%s' couldn't get layout\n",
2264                         progname, fname);
2265                 return -EINVAL;
2266         }
2267
2268         rc = llapi_layout_sanity(layout, false, true);
2269         if (rc) {
2270                 llapi_layout_sanity_perror(rc);
2271                 goto free_layout;
2272         }
2273
2274         rc = llapi_layout_mirror_count_get(layout, &mirror_count);
2275         if (rc) {
2276                 fprintf(stderr,
2277                         "error %s: file '%s' couldn't get mirror count\n",
2278                         progname, fname);
2279                 goto free_layout;
2280         }
2281         if (mirror_count < 2) {
2282                 fprintf(stderr,
2283                         "error %s: file '%s' has %d component, cannot split\n",
2284                         progname, fname, mirror_count);
2285                 goto free_layout;
2286         }
2287
2288         if (mflags & MF_COMP_POOL) {
2289                 struct pool_to_id_cbdata data = { .pool = pool };
2290
2291                 rc = llapi_layout_comp_iterate(layout, find_mirror_id_by_pool,
2292                                                &data);
2293                 mirror_id = data.id;
2294         } else if (mflags & MF_COMP_ID) {
2295                 rc = llapi_layout_comp_iterate(layout, find_comp_id, &id);
2296                 mirror_id = mirror_id_of(id);
2297         } else {
2298                 rc = llapi_layout_comp_iterate(layout, find_mirror_id, &id);
2299                 mirror_id = id;
2300         }
2301         if (rc < 0) {
2302                 fprintf(stderr, "error %s: failed to iterate layout of '%s'\n",
2303                         progname, fname);
2304                 goto free_layout;
2305         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
2306                 if (mflags & MF_COMP_POOL) {
2307                         fprintf(stderr,
2308                                 "error %s: file '%s' does not contain mirror with pool '%s'\n",
2309                                 progname, fname, pool);
2310                         goto free_layout;
2311                 } else if (mflags & MF_COMP_ID) {
2312                         fprintf(stderr,
2313                                 "error %s: file '%s' does not contain mirror with comp-id %u\n",
2314                                 progname, fname, id);
2315                         goto free_layout;
2316                 } else {
2317                         fprintf(stderr,
2318                                 "error %s: file '%s' does not contain mirror with id %u\n",
2319                                 progname, fname, id);
2320                         goto free_layout;
2321                 }
2322         }
2323
2324         if (!victim_file && mflags & MF_DESTROY)
2325                 /* Allow mirror split even without the key on encrypted files,
2326                  * and in this case of a 'split -d', open file with O_DIRECT
2327                  * (no IOs will be done).
2328                  */
2329                 fd = open(fname, O_RDWR | O_DIRECT | O_CIPHERTEXT);
2330         else
2331                 fd = open(fname, O_RDWR);
2332
2333         if (fd < 0) {
2334                 fprintf(stderr,
2335                         "error %s: open file '%s' failed: %s\n",
2336                         progname, fname, strerror(errno));
2337                 goto free_layout;
2338         }
2339
2340         /* get victim file directory pathname */
2341         if (strlen(fname) > sizeof(parent) - 1) {
2342                 fprintf(stderr, "error %s: file name of '%s' too long\n",
2343                         progname, fname);
2344                 rc = -ERANGE;
2345                 goto close_fd;
2346         }
2347         strncpy(parent, fname, sizeof(parent));
2348         ptr = strrchr(parent, '/');
2349         if (!ptr) {
2350                 if (!getcwd(parent, sizeof(parent))) {
2351                         fprintf(stderr, "error %s: getcwd failed: %s\n",
2352                                 progname, strerror(errno));
2353                         rc = -errno;
2354                         goto close_fd;
2355                 }
2356         } else {
2357                 if (ptr == parent)
2358                         ptr = parent + 1;
2359                 *ptr = '\0';
2360         }
2361
2362         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
2363         if (rc < 0) {
2364                 fprintf(stderr, "%s: cannot get MDT index of '%s'\n",
2365                         progname, fname);
2366                 goto close_fd;
2367         }
2368
2369         rc = llapi_file_is_encrypted(fd);
2370         if (rc < 0) {
2371                 fprintf(stderr, "%s: cannot get flags of '%s': %d\n",
2372                         progname, fname, rc);
2373                 goto close_fd;
2374         }
2375         is_encrypted = rc;
2376
2377 again:
2378         if (!victim_file) {
2379                 /* use a temp file to store the splitted layout */
2380                 if (mflags & MF_DESTROY) {
2381                         char file_path[PATH_MAX];
2382                         unsigned int rnumber;
2383                         int open_flags;
2384
2385                         if (last_non_stale_mirror(mirror_id, layout)) {
2386                                 rc = -EUCLEAN;
2387                                 fprintf(stderr,
2388                                         "%s: cannot destroy the last non-stale mirror of file '%s'\n",
2389                                         progname, fname);
2390                                 goto close_fd;
2391                         }
2392
2393                         if (purge) {
2394                                 /* don't use volatile file for mirror destroy */
2395                                 fdv = fd;
2396                         } else {
2397                                 /**
2398                                  * try the old way to delete mirror using
2399                                  * volatile file.
2400                                  */
2401                                 do {
2402                                         rnumber = random();
2403                                         rc = snprintf(file_path,
2404                                                       sizeof(file_path),
2405                                                       "%s/" LUSTRE_VOLATILE_HDR ":%.4X:%.4X:fd=%.2d",
2406                                                       parent, mdt_index,
2407                                                       rnumber, fd);
2408                                         if (rc < 0 ||
2409                                             rc >= sizeof(file_path)) {
2410                                                 fdv = -ENAMETOOLONG;
2411                                                 break;
2412                                         }
2413
2414                                         open_flags = O_RDWR |
2415                                              (O_LOV_DELAY_CREATE & ~O_ACCMODE) |
2416                                              O_CREAT | O_EXCL | O_NOFOLLOW |
2417                                              /* O_DIRECT for mirror split -d */
2418                                              O_DIRECT |
2419                                              /* Allow split without the key */
2420                                              O_CIPHERTEXT;
2421                                         fdv = open(file_path, open_flags,
2422                                                    S_IRUSR | S_IWUSR);
2423                                         if (fdv < 0)
2424                                                 rc = -errno;
2425                                 } while (fdv < 0 && rc == -EEXIST);
2426                         }
2427                 } else {
2428                         if (is_encrypted) {
2429                                 rc = -1;
2430                                 fprintf(stderr,
2431                                         "error %s: not permitted on encrypted file '%s': %d\n",
2432                                         progname, fname, rc);
2433                                 goto close_fd;
2434                         }
2435
2436                         snprintf(victim, sizeof(victim), "%s.mirror~%u",
2437                                  fname, mirror_id);
2438                         fdv = open(victim, flags, S_IRUSR | S_IWUSR);
2439                 }
2440         } else {
2441                 /* user specified victim file */
2442                 if (is_encrypted) {
2443                         rc = -1;
2444                         fprintf(stderr,
2445                                 "error %s: not permitted on encrypted file '%s': %d\n",
2446                                 progname, fname, rc);
2447                         goto close_fd;
2448                 }
2449                 fdv = open(victim_file, flags, S_IRUSR | S_IWUSR);
2450         }
2451
2452         if (fdv < 0) {
2453                 fprintf(stderr,
2454                         "error %s: create victim file failed: %s\n",
2455                         progname, strerror(errno));
2456                 goto close_fd;
2457         }
2458
2459         /* get lease lock of fname */
2460         rc = llapi_lease_acquire(fd, LL_LEASE_WRLCK);
2461         if (rc < 0) {
2462                 fprintf(stderr,
2463                         "error %s: cannot get lease of file '%s': %d\n",
2464                         progname, fname, rc);
2465                 goto close_victim;
2466         }
2467
2468         /* Atomatically put lease, split layouts and close. */
2469         data = malloc(offsetof(typeof(*data), lil_ids[2]));
2470         if (!data) {
2471                 rc = -ENOMEM;
2472                 goto close_victim;
2473         }
2474
2475         data->lil_mode = LL_LEASE_UNLCK;
2476         data->lil_flags = LL_LEASE_LAYOUT_SPLIT;
2477         data->lil_count = 2;
2478         data->lil_ids[0] = fdv;
2479         data->lil_ids[1] = mirror_id;
2480         rc = llapi_lease_set(fd, data);
2481         if (rc <= 0) {
2482                 if ((rc == -EINVAL || rc == -EBUSY) && purge) {
2483                         /* could be old MDS which prohibit fd==fdv */
2484                         purge = false;
2485                         goto again;
2486
2487                 }
2488                 if (rc == 0) /* lost lease lock */
2489                         rc = -EBUSY;
2490                 fprintf(stderr,
2491                         "error %s: cannot split '%s': %s\n",
2492                         progname, fname, strerror(-rc));
2493         } else {
2494                 rc = 0;
2495         }
2496         free(data);
2497
2498 close_victim:
2499         if (!purge)
2500                 close(fdv);
2501 close_fd:
2502         close(fd);
2503 free_layout:
2504         llapi_layout_free(layout);
2505         return rc;
2506 }
2507
2508 static inline
2509 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
2510                            __u16 *mirror_ids, int ids_nr);
2511
2512 static int lfs_migrate_to_dom(int fd_src, int fd_dst, char *name,
2513                               __u64 migration_flags,
2514                               unsigned long long bandwidth_bytes_sec,
2515                               enum stats_flag stats_flag,
2516                               long stats_interval_sec)
2517 {
2518         struct ll_ioc_lease *data = NULL;
2519         int rc;
2520
2521         rc = llapi_lease_acquire(fd_src, LL_LEASE_RDLCK);
2522         if (rc < 0) {
2523                 error_loc = "cannot get lease";
2524                 goto out_close;
2525         }
2526
2527         if (stats_flag)
2528                 printf("%s:\n", name);
2529
2530         rc = migrate_nonblock(fd_src, fd_dst, bandwidth_bytes_sec, stats_flag,
2531                               stats_interval_sec);
2532         if (rc < 0)
2533                 goto out_release;
2534
2535         /* Atomically put lease, merge layouts, resync and close. */
2536         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
2537         if (!data) {
2538                 error_loc = "memory allocation";
2539                 goto out_release;
2540         }
2541         data->lil_mode = LL_LEASE_UNLCK;
2542         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
2543         data->lil_count = 1;
2544         data->lil_ids[0] = fd_dst;
2545         rc = llapi_lease_set(fd_src, data);
2546         if (rc < 0) {
2547                 error_loc = "cannot merge layout";
2548                 goto out_close;
2549         } else if (rc == 0) {
2550                 rc = -EBUSY;
2551                 error_loc = "lost lease lock";
2552                 goto out_close;
2553         }
2554         close(fd_src);
2555         close(fd_dst);
2556
2557         rc = lfs_mirror_resync_file(name, data, NULL, 0);
2558         if (rc) {
2559                 error_loc = "cannot resync file";
2560                 goto out;
2561         }
2562
2563         /* delete first mirror now */
2564         rc = mirror_split(name, 1, NULL, MF_DESTROY, NULL);
2565         if (rc < 0)
2566                 error_loc = "cannot delete old layout";
2567         goto out;
2568
2569 out_release:
2570         llapi_lease_release(fd_src);
2571 out_close:
2572         close(fd_src);
2573         close(fd_dst);
2574 out:
2575         if (rc < 0)
2576                 fprintf(stderr, "error: %s: %s: %s: %s\n",
2577                         progname, name, error_loc, strerror(-rc));
2578         else if (migration_flags & LLAPI_MIGRATION_VERBOSE)
2579                 printf("%s\n", name);
2580         if (data)
2581                 free(data);
2582         return rc;
2583 }
2584
2585 /**
2586  * Parse a string containing an target index list into an array of integers.
2587  *
2588  * The input string contains a comma delimited list of individual
2589  * indices and ranges, for example "1,2-4,7". Add the indices into the
2590  * \a tgts array and remove duplicates.
2591  *
2592  * \param[out] tgts             array to store indices in
2593  * \param[in] size              size of \a tgts array
2594  * \param[in] offset            starting index in \a tgts
2595  * \param[in] arg               string containing OST index list
2596  * \param[in/out] overstriping  index list may contain duplicates
2597  *
2598  * \retval positive    number of indices in \a tgts
2599  * \retval -EINVAL     unable to parse \a arg
2600  */
2601 static int parse_targets(__u32 *tgts, int size, int offset, char *arg,
2602                          unsigned long long *pattern)
2603 {
2604         int rc;
2605         int nr = offset;
2606         int slots = size - offset;
2607         char *ptr = NULL;
2608         bool overstriped = false;
2609         bool end_of_loop;
2610
2611         if (!arg)
2612                 return -EINVAL;
2613
2614         end_of_loop = false;
2615         while (!end_of_loop) {
2616                 int start_index = 0;
2617                 int end_index = 0;
2618                 int i;
2619                 char *endptr = NULL;
2620
2621                 rc = -EINVAL;
2622
2623                 ptr = strchrnul(arg, ',');
2624
2625                 end_of_loop = *ptr == '\0';
2626                 *ptr = '\0';
2627
2628                 errno = 0;
2629                 start_index = strtol(arg, &endptr, 0);
2630                 if (endptr == arg) /* no data at all */
2631                         break;
2632                 if (errno != 0 || start_index < -1 ||
2633                     (*endptr != '-' && *endptr != '\0'))
2634                         break;
2635
2636                 end_index = start_index;
2637                 if (*endptr == '-') {
2638                         errno = 0;
2639                         end_index = strtol(endptr + 1, &endptr, 0);
2640                         if (errno != 0 || *endptr != '\0' || end_index < -1)
2641                                 break;
2642                         if (end_index < start_index)
2643                                 break;
2644                 }
2645
2646                 for (i = start_index; i <= end_index && slots > 0; i++) {
2647                         int j;
2648
2649                         /* remove duplicate */
2650                         for (j = 0; j < offset; j++) {
2651                                 if (tgts[j] == i && pattern &&
2652                                     *pattern == LLAPI_LAYOUT_OVERSTRIPING)
2653                                         overstriped = true;
2654                                 else if (tgts[j] == i)
2655                                         return -EINVAL;
2656                         }
2657
2658                         j = offset;
2659
2660                         if (j == offset) { /* check complete */
2661                                 tgts[nr++] = i;
2662                                 --slots;
2663                         }
2664                 }
2665
2666                 if (slots == 0 && i < end_index)
2667                         break;
2668
2669                 *ptr = ',';
2670                 arg = ++ptr;
2671                 offset = nr;
2672                 rc = 0;
2673         }
2674         if (!end_of_loop && ptr)
2675                 *ptr = ',';
2676
2677         if (!overstriped && pattern)
2678                 *pattern = LLAPI_LAYOUT_DEFAULT;
2679
2680         return rc < 0 ? rc : nr;
2681 }
2682
2683 struct lfs_setstripe_args {
2684         unsigned long long       lsa_comp_end;
2685         unsigned long long       lsa_stripe_size;
2686         unsigned long long       lsa_extension_size;
2687         long long                lsa_stripe_count;
2688         long long                lsa_stripe_off;
2689         __u32                    lsa_comp_flags;
2690         __u32                    lsa_comp_neg_flags;
2691         unsigned long long       lsa_pattern;
2692         unsigned int             lsa_mirror_count;
2693         int                      lsa_nr_tgts;
2694         bool                     lsa_first_comp;
2695         bool                     lsa_extension_comp;
2696         __u32                   *lsa_tgts;
2697         char                    *lsa_pool_name;
2698 };
2699
2700 static inline void setstripe_args_init(struct lfs_setstripe_args *lsa)
2701 {
2702         unsigned int mirror_count = lsa->lsa_mirror_count;
2703         bool first_comp = lsa->lsa_first_comp;
2704
2705         memset(lsa, 0, sizeof(*lsa));
2706
2707         lsa->lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
2708         lsa->lsa_stripe_count = LLAPI_LAYOUT_DEFAULT;
2709         lsa->lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2710         lsa->lsa_pattern = LLAPI_LAYOUT_RAID0;
2711         lsa->lsa_pool_name = NULL;
2712
2713         lsa->lsa_mirror_count = mirror_count;
2714         lsa->lsa_first_comp = first_comp;
2715 }
2716
2717 /**
2718  * setstripe_args_init_inherit() - Initialize and inherit stripe options.
2719  * @lsa: Stripe options to be initialized and inherited.
2720  *
2721  * This function initializes stripe options in @lsa and inherit
2722  * stripe_size, stripe_count and OST pool_name options.
2723  *
2724  * Return: void.
2725  */
2726 static inline void setstripe_args_init_inherit(struct lfs_setstripe_args *lsa)
2727 {
2728         unsigned long long stripe_size;
2729         long long stripe_count;
2730         char *pool_name = NULL;
2731
2732         stripe_size = lsa->lsa_stripe_size;
2733         stripe_count = lsa->lsa_stripe_count;
2734         pool_name = lsa->lsa_pool_name;
2735
2736         setstripe_args_init(lsa);
2737
2738         lsa->lsa_stripe_size = stripe_size;
2739         lsa->lsa_stripe_count = stripe_count;
2740         lsa->lsa_pool_name = pool_name;
2741 }
2742
2743 static inline bool setstripe_args_specified(struct lfs_setstripe_args *lsa)
2744 {
2745         return (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT ||
2746                 lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ||
2747                 lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
2748                 lsa->lsa_pattern != LLAPI_LAYOUT_RAID0 ||
2749                 lsa->lsa_comp_end != 0);
2750 }
2751
2752 static int lsa_args_stripe_count_check(struct lfs_setstripe_args *lsa)
2753 {
2754         if (lsa->lsa_nr_tgts) {
2755                 if (lsa->lsa_nr_tgts < 0 ||
2756                     lsa->lsa_nr_tgts >= LOV_MAX_STRIPE_COUNT) {
2757                         fprintf(stderr, "Invalid nr_tgts(%d)\n",
2758                                 lsa->lsa_nr_tgts);
2759                         errno = EINVAL;
2760                         return -1;
2761                 }
2762
2763                 if (lsa->lsa_stripe_count > 0 &&
2764                     lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
2765                     lsa->lsa_stripe_count != LLAPI_LAYOUT_WIDE &&
2766                     lsa->lsa_nr_tgts != lsa->lsa_stripe_count) {
2767                         fprintf(stderr, "stripe_count(%lld) != nr_tgts(%d)\n",
2768                                 lsa->lsa_stripe_count,
2769                                 lsa->lsa_nr_tgts);
2770                         errno = EINVAL;
2771                         return -1;
2772                 }
2773         }
2774
2775         return 0;
2776
2777 }
2778
2779 /**
2780  * comp_args_to_layout() - Create or extend a composite layout.
2781  * @composite:       Pointer to the composite layout.
2782  * @lsa:             Stripe options for the new component.
2783  *
2784  * This function creates or extends a composite layout by adding a new
2785  * component with stripe options from @lsa.
2786  *
2787  * When modified, adjust llapi_stripe_param_verify() if needed as well.
2788  *
2789  * Return: 0 on success or an error code on failure.
2790  */
2791 static int comp_args_to_layout(struct llapi_layout **composite,
2792                                struct lfs_setstripe_args *lsa,
2793                                bool set_extent)
2794 {
2795         struct llapi_layout *layout = *composite;
2796         uint64_t prev_end = 0;
2797         uint64_t size;
2798         int i = 0, rc;
2799
2800 new_comp:
2801         if (!layout) {
2802                 layout = llapi_layout_alloc();
2803                 if (!layout) {
2804                         fprintf(stderr, "Alloc llapi_layout failed. %s\n",
2805                                 strerror(errno));
2806                         errno = ENOMEM;
2807                         return -1;
2808                 }
2809                 *composite = layout;
2810                 lsa->lsa_first_comp = true;
2811         } else {
2812                 uint64_t start;
2813
2814                 /*
2815                  * Get current component extent, current component
2816                  * must be the tail component.
2817                  */
2818                 rc = llapi_layout_comp_extent_get(layout, &start, &prev_end);
2819                 if (rc) {
2820                         fprintf(stderr, "Get comp extent failed. %s\n",
2821                                 strerror(errno));
2822                         return rc;
2823                 }
2824
2825                 if (lsa->lsa_first_comp) {
2826                         prev_end = 0;
2827                         rc = llapi_layout_add_first_comp(layout);
2828                 } else {
2829                         rc = llapi_layout_comp_add(layout);
2830                 }
2831                 if (rc) {
2832                         fprintf(stderr, "Add component failed. %s\n",
2833                                 strerror(errno));
2834                         return rc;
2835                 }
2836         }
2837
2838         rc = llapi_layout_comp_flags_set(layout, lsa->lsa_comp_flags);
2839         if (rc) {
2840                 fprintf(stderr, "Set flags 0x%x failed: %s\n",
2841                         lsa->lsa_comp_flags, strerror(errno));
2842                 return rc;
2843         }
2844
2845         if (set_extent) {
2846                 uint64_t comp_end = lsa->lsa_comp_end;
2847
2848                 /*
2849                  * The extendable component is 0-length, so it can be removed
2850                  * if there is insufficient space to extend it.
2851                  */
2852                 if (lsa->lsa_extension_comp)
2853                         comp_end = prev_end;
2854
2855                 rc = llapi_layout_comp_extent_set(layout, prev_end,
2856                                                   comp_end);
2857                 if (rc) {
2858                         fprintf(stderr, "Set extent [%lu, %lu) failed. %s\n",
2859                                 prev_end, comp_end, strerror(errno));
2860                         return rc;
2861                 }
2862         }
2863         /* reset lsa_first_comp */
2864         lsa->lsa_first_comp = false;
2865
2866         /* Data-on-MDT component setting */
2867         if (lsa->lsa_pattern == LLAPI_LAYOUT_MDT) {
2868                 /* Yaml support */
2869                 if (lsa->lsa_stripe_count == 0)
2870                         lsa->lsa_stripe_count = LLAPI_LAYOUT_DEFAULT;
2871                 if (lsa->lsa_stripe_size == lsa->lsa_comp_end)
2872                         lsa->lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
2873                 if (lsa->lsa_stripe_off == -1 ||
2874                     lsa->lsa_stripe_off == 0)
2875                         lsa->lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2876                 /*
2877                  * In case of Data-on-MDT patterns the only extra option
2878                  * applicable is stripe size option.
2879                  */
2880                 if (lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
2881                         fprintf(stderr,
2882                                 "Option 'stripe-count' can't be specified with Data-on-MDT component: %lld\n",
2883                                 lsa->lsa_stripe_count);
2884                         errno = EINVAL;
2885                         return -1;
2886                 }
2887                 if (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT &&
2888                     lsa->lsa_stripe_size != lsa->lsa_comp_end - prev_end) {
2889                         fprintf(stderr,
2890                                 "Option 'stripe-size' can't be specified with Data-on-MDT component: %llu\n",
2891                                 lsa->lsa_stripe_size);
2892                         errno = EINVAL;
2893                         return -1;
2894                 }
2895                 if (lsa->lsa_nr_tgts != 0) {
2896                         fprintf(stderr,
2897                                 "Option 'ost-list' can't be specified with Data-on-MDT component: '%i'\n",
2898                                 lsa->lsa_nr_tgts);
2899                         errno = EINVAL;
2900                         return -1;
2901                 }
2902                 if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT) {
2903                         fprintf(stderr,
2904                                 "Option 'stripe-offset' can't be specified with Data-on-MDT component: %lld\n",
2905                                 lsa->lsa_stripe_off);
2906                         errno = EINVAL;
2907                         return -1;
2908                 }
2909                 if (lsa->lsa_pool_name != 0) {
2910                         fprintf(stderr,
2911                                 "Option 'pool' can't be specified with Data-on-MDT component: '%s'\n",
2912                                 lsa->lsa_pool_name);
2913                         errno = EINVAL;
2914                         return -1;
2915                 }
2916
2917                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2918                 if (rc) {
2919                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2920                                 lsa->lsa_pattern,
2921                                 strerror(errno));
2922                         return rc;
2923                 }
2924                 /* Data-on-MDT component has always single stripe up to end */
2925                 lsa->lsa_stripe_size = lsa->lsa_comp_end;
2926         } else if (lsa->lsa_pattern == LLAPI_LAYOUT_OVERSTRIPING) {
2927                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2928                 if (rc) {
2929                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2930                                 lsa->lsa_pattern,
2931                                 strerror(errno));
2932                         return rc;
2933                 }
2934         }
2935
2936         size = lsa->lsa_comp_flags & LCME_FL_EXTENSION ?
2937                 lsa->lsa_extension_size : lsa->lsa_stripe_size;
2938
2939         if (lsa->lsa_comp_flags & LCME_FL_EXTENSION)
2940                 rc = llapi_layout_extension_size_set(layout, size);
2941         else
2942                 rc = llapi_layout_stripe_size_set(layout, size);
2943
2944         if (rc) {
2945                 fprintf(stderr, "Set stripe size %lu failed: %s\n",
2946                         size, strerror(errno));
2947                 return rc;
2948         }
2949
2950         rc = llapi_layout_stripe_count_set(layout, lsa->lsa_stripe_count);
2951         if (rc) {
2952                 fprintf(stderr, "Set stripe count %lld failed: %s\n",
2953                         lsa->lsa_stripe_count, strerror(errno));
2954                 return rc;
2955         }
2956
2957         if (lsa->lsa_pool_name) {
2958                 rc = llapi_layout_pool_name_set(layout, lsa->lsa_pool_name);
2959                 if (rc) {
2960                         fprintf(stderr, "Set pool name: %s failed. %s\n",
2961                                 lsa->lsa_pool_name, strerror(errno));
2962                         return rc;
2963                 }
2964         } else {
2965                 rc = llapi_layout_pool_name_set(layout, "");
2966                 if (rc) {
2967                         fprintf(stderr, "Clear pool name failed: %s\n",
2968                                 strerror(errno));
2969                         return rc;
2970                 }
2971         }
2972
2973         rc = lsa_args_stripe_count_check(lsa);
2974         if (rc)
2975                 return rc;
2976
2977         if (lsa->lsa_nr_tgts > 0) {
2978                 bool found = false;
2979
2980                 for (i = 0; i < lsa->lsa_nr_tgts; i++) {
2981                         rc = llapi_layout_ost_index_set(layout, i,
2982                                                         lsa->lsa_tgts[i]);
2983                         if (rc)
2984                                 break;
2985
2986                         /* Make sure stripe offset is in OST list. */
2987                         if (lsa->lsa_tgts[i] == lsa->lsa_stripe_off)
2988                                 found = true;
2989                 }
2990                 if (!found) {
2991                         fprintf(stderr, "Invalid stripe offset '%lld', not in the target list",
2992                                 lsa->lsa_stripe_off);
2993                         errno = EINVAL;
2994                         return -1;
2995                 }
2996         } else if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT &&
2997                    lsa->lsa_stripe_off != -1) {
2998                 rc = llapi_layout_ost_index_set(layout, 0, lsa->lsa_stripe_off);
2999         }
3000         if (rc) {
3001                 fprintf(stderr, "Set ost index %d failed. %s\n",
3002                         i, strerror(errno));
3003                 return rc;
3004         }
3005
3006         /* Create the second, virtual component of extension space */
3007         if (lsa->lsa_extension_comp) {
3008                 lsa->lsa_comp_flags |= LCME_FL_EXTENSION;
3009                 lsa->lsa_extension_comp = false;
3010                 goto new_comp;
3011         }
3012
3013         return rc;
3014 }
3015
3016 static int build_component(struct llapi_layout **layout,
3017                            struct lfs_setstripe_args *lsa, bool set_extent)
3018 {
3019         int rc;
3020
3021         rc = comp_args_to_layout(layout, lsa, set_extent);
3022         if (rc)
3023                 return rc;
3024
3025         if (lsa->lsa_mirror_count > 0) {
3026                 rc = llapi_layout_mirror_count_set(*layout,
3027                                                    lsa->lsa_mirror_count);
3028                 if (rc)
3029                         return rc;
3030
3031                 rc = llapi_layout_flags_set(*layout, LCM_FL_RDONLY);
3032                 if (rc)
3033                         return rc;
3034                 lsa->lsa_mirror_count = 0;
3035         }
3036
3037         return rc;
3038 }
3039
3040 static int build_prev_component(struct llapi_layout **layout,
3041                                 struct lfs_setstripe_args *prev,
3042                                 struct lfs_setstripe_args *lsa,
3043                                 bool set_extent)
3044 {
3045         int extension = lsa->lsa_comp_flags & LCME_FL_EXTENSION;
3046         int rc;
3047
3048         if (prev->lsa_stripe_size) {
3049                 if (extension) {
3050                         prev->lsa_comp_end = lsa->lsa_comp_end;
3051                         prev->lsa_extension_size = lsa->lsa_extension_size;
3052                         prev->lsa_extension_comp = true;
3053                 }
3054
3055                 rc = build_component(layout, prev, true);
3056                 if (rc)
3057                         return rc;
3058         }
3059
3060         /*
3061          * Copy lsa to previous lsa;
3062          * if this is an extension component, make the previous invalid;
3063          */
3064         if (extension)
3065                 prev->lsa_stripe_size = 0;
3066         else
3067                 *prev = *lsa;
3068
3069         return 0;
3070 }
3071
3072 #ifndef LCME_TEMPLATE_FLAGS
3073 #define LCME_TEMPLATE_FLAGS     (LCME_FL_PREF_RW | LCME_FL_NOSYNC | \
3074                                  LCME_FL_EXTENSION)
3075 #endif
3076
3077 static int build_layout_from_yaml_node(struct cYAML *node,
3078                                        struct llapi_layout **layout,
3079                                        struct lfs_setstripe_args *lsa,
3080                                        struct lfs_setstripe_args *prevp)
3081 {
3082         struct lfs_setstripe_args prev = { 0 };
3083         __u32 *osts = lsa->lsa_tgts;
3084         char *string;
3085         int rc = 0;
3086
3087         if (!prevp)
3088                 prevp = &prev;
3089
3090         while (node) {
3091                 string = node->cy_string;
3092
3093                 if (node->cy_type == CYAML_TYPE_OBJECT) {
3094                         /* go deep to sub blocks */
3095                         if (string && !strncmp(string, "component", 9) &&
3096                             strncmp(string, "component0", 10) &&
3097                             strncmp(string, "components", 10)) {
3098                                 rc = build_prev_component(layout, prevp, lsa,
3099                                                           true);
3100                                 if (rc)
3101                                         return rc;
3102
3103                                 /* initialize lsa. */
3104                                 setstripe_args_init(lsa);
3105                                 lsa->lsa_first_comp = false;
3106                                 lsa->lsa_tgts = osts;
3107                         }
3108
3109                         rc = build_layout_from_yaml_node(node->cy_child, layout,
3110                                                          lsa, prevp);
3111                         if (rc)
3112                                 return rc;
3113                 } else {
3114                         if (!node->cy_string)
3115                                 return -EINVAL;
3116
3117                         /* skip leading lmm_ if present, to simplify parsing */
3118                         if (strncmp(string, "lmm_", 4) == 0)
3119                                 string += 4;
3120
3121                         if (node->cy_type == CYAML_TYPE_STRING) {
3122                                 if (!strcmp(string, "lcme_extent.e_end")) {
3123                                         if (!strcmp(node->cy_valuestring, "EOF") ||
3124                                             !strcmp(node->cy_valuestring, "eof"))
3125                                                 lsa->lsa_comp_end = LUSTRE_EOF;
3126                                 } else if (!strcmp(string, "pool")) {
3127                                         lsa->lsa_pool_name = node->cy_valuestring;
3128                                 } else if (!strcmp(string, "pattern")) {
3129                                         if (!strcmp(node->cy_valuestring, "mdt"))
3130                                                 lsa->lsa_pattern = LLAPI_LAYOUT_MDT;
3131                                         if (!strcmp(node->cy_valuestring,
3132                                                     "raid0,overstriped"))
3133                                                 lsa->lsa_pattern =
3134                                                         LLAPI_LAYOUT_OVERSTRIPING;
3135                                 } else if (!strcmp(string, "lcme_flags")) {
3136                                         rc = comp_str2flags(node->cy_valuestring,
3137                                                             &lsa->lsa_comp_flags,
3138                                                             &lsa->lsa_comp_neg_flags);
3139                                         if (rc)
3140                                                 return rc;
3141                                         /*
3142                                          * Only template flags have meaning in
3143                                          * the layout for a new file
3144                                          */
3145                                         lsa->lsa_comp_flags &= LCME_TEMPLATE_FLAGS;
3146                                 }
3147                         } else if (node->cy_type == CYAML_TYPE_NUMBER) {
3148                                 if (!strcmp(string, "lcm_mirror_count")) {
3149                                         lsa->lsa_mirror_count = node->cy_valueint;
3150                                 } else if (!strcmp(string, "lcme_extent.e_start")) {
3151                                         if (node->cy_valueint == 0)
3152                                                 lsa->lsa_first_comp = true;
3153                                 } else if (!strcmp(string, "lcme_extent.e_end")) {
3154                                         if (node->cy_valueint == -1)
3155                                                 lsa->lsa_comp_end = LUSTRE_EOF;
3156                                         else
3157                                                 lsa->lsa_comp_end = node->cy_valueint;
3158                                 } else if (!strcmp(string, "stripe_count")) {
3159                                         lsa->lsa_stripe_count = node->cy_valueint;
3160                                 } else if (!strcmp(string, "stripe_size")) {
3161                                         lsa->lsa_stripe_size = node->cy_valueint;
3162                                 } else if (!strcmp(string, "extension_size")) {
3163                                         lsa->lsa_extension_size = node->cy_valueint;
3164                                         lsa->lsa_extension_comp = true;
3165                                 } else if (!strcmp(string, "stripe_offset")) {
3166                                         lsa->lsa_stripe_off = node->cy_valueint;
3167                                 } else if (!strcmp(string, "l_ost_idx")) {
3168                                         osts[lsa->lsa_nr_tgts] = node->cy_valueint;
3169                                         lsa->lsa_nr_tgts++;
3170                                 }
3171                         }
3172                 }
3173                 node = node->cy_next;
3174         }
3175
3176         if (prevp == &prev) {
3177                 rc = build_prev_component(layout, prevp, lsa, true);
3178                 if (rc)
3179                         return rc;
3180
3181                 if (!(lsa->lsa_comp_flags & LCME_FL_EXTENSION))
3182                         rc = build_component(layout, lsa, *layout != NULL);
3183         }
3184
3185         return rc;
3186 }
3187
3188 static int lfs_comp_create_from_yaml(char *template,
3189                                      struct llapi_layout **layout,
3190                                      struct lfs_setstripe_args *lsa,
3191                                      __u32 *osts)
3192 {
3193         struct cYAML *tree = NULL, *err_rc = NULL;
3194         int rc = 0;
3195
3196         tree = cYAML_build_tree(template, NULL, 0, &err_rc, false);
3197         if (!tree) {
3198                 fprintf(stderr, "%s: cannot parse YAML file %s\n",
3199                         progname, template);
3200                 cYAML_build_error(-EINVAL, -1, "yaml", "from comp yaml",
3201                                   "can't parse", &err_rc);
3202                 cYAML_print_tree2file(stderr, err_rc);
3203                 cYAML_free_tree(err_rc);
3204                 rc = -EINVAL;
3205                 goto err;
3206         }
3207
3208         /* initialize lsa for plain file */
3209         setstripe_args_init(lsa);
3210         lsa->lsa_tgts = osts;
3211
3212         rc = build_layout_from_yaml_node(tree, layout, lsa, NULL);
3213         if (rc) {
3214                 fprintf(stderr, "%s: cannot build layout from YAML file %s.\n",
3215                         progname, template);
3216                 goto err;
3217         }
3218         /* clean clean lsa */
3219         setstripe_args_init(lsa);
3220
3221 err:
3222         if (tree)
3223                 cYAML_free_tree(tree);
3224         return rc;
3225 }
3226
3227 /**
3228  * Get the extension size from the next (SEL) component and extend the
3229  * current component on it. The start of the next component is to be
3230  * adjusted as well.
3231  *
3232  * \param[in] layout    the current layout
3233  * \param[in] start     the start of the current component
3234  * \param[in,out] end   the end of the current component
3235  * \param[in] offset    the offset to adjust the end position to instead of
3236  *                      extension size
3237  *
3238  * \retval 0            - extended successfully
3239  * \retval < 0          - error
3240  */
3241 static int layout_extend_comp(struct llapi_layout *layout,
3242                               uint64_t start, uint64_t *end,
3243                               uint64_t offset)
3244 {
3245         uint64_t size, next_start, next_end;
3246         int rc;
3247
3248         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_NEXT);
3249         if (rc < 0) {
3250                 fprintf(stderr,
3251                         "%s setstripe: cannot move component cursor: %s\n",
3252                         progname, strerror(errno));
3253                 return rc;
3254         }
3255
3256         /*
3257          * Even if the @size will not be used below, this will fail if
3258          * this is not a SEL component - a good confirmation we are
3259          * working on right components.
3260          */
3261         rc = llapi_layout_extension_size_get(layout, &size);
3262         if (rc < 0) {
3263                 fprintf(stderr,
3264                         "%s setstripe: cannot get component ext size: %s\n",
3265                         progname, strerror(errno));
3266                 return rc;
3267         }
3268
3269         rc = llapi_layout_comp_extent_get(layout, &next_start, &next_end);
3270         if (rc) {
3271                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
3272                         progname, strerror(errno));
3273                 return rc;
3274         }
3275
3276         next_start += offset ?: size;
3277         rc = llapi_layout_comp_extent_set(layout, next_start, next_end);
3278         if (rc) {
3279                 fprintf(stderr, "%s setstripe: cannot set extent: %s\n",
3280                         progname, strerror(errno));
3281                 return rc;
3282         }
3283
3284         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_PREV);
3285         if (rc < 0) {
3286                 fprintf(stderr,
3287                         "%s setstripe: cannot move component cursor: %s\n",
3288                         progname, strerror(errno));
3289                 return rc;
3290         }
3291
3292         *end += offset ?: size;
3293         rc = llapi_layout_comp_extent_set(layout, start, *end);
3294         if (rc) {
3295                 fprintf(stderr, "%s setstripe: cannot set extent: %s\n",
3296                         progname, strerror(errno));
3297                 return rc;
3298         }
3299
3300         return 0;
3301 }
3302
3303 /**
3304  * In 'lfs setstripe --component-add' mode, we need to fetch the extent
3305  * end of the last component in the existing file, and adjust the
3306  * first extent start of the components to be added accordingly.
3307  *
3308  * In the create mode, we need to check if the first component is an extendable
3309  * SEL component and extend its length to the extension size (first component
3310  * of the PFL file is initialised at the create time, cannot be 0-lenght.
3311  */
3312 static int layout_adjust_first_extent(char *fname, struct llapi_layout *layout,
3313                                       bool comp_add)
3314 {
3315         struct llapi_layout *head;
3316         uint64_t start = 0, prev_end = 0;
3317         uint64_t end;
3318         int rc, ret = 0;
3319
3320         if (!layout || !(comp_add || llapi_layout_is_composite(layout)))
3321                 return 0;
3322
3323         errno = 0;
3324         while (comp_add) {
3325                 head = llapi_layout_get_by_path(fname, 0);
3326                 if (!head) {
3327                         fprintf(stderr,
3328                                 "%s setstripe: cannot read layout from '%s': %s\n",
3329                                 progname, fname, strerror(errno));
3330                         return -EINVAL;
3331                 } else if (errno == ENODATA) {
3332                         /*
3333                          * file without LOVEA, this component-add will be turned
3334                          * into a component-create.
3335                          */
3336                         llapi_layout_free(head);
3337                         ret = -ENODATA;
3338
3339                         /*
3340                          * the new layout will be added to an empty one, it
3341                          * still needs to be adjusted below
3342                          */
3343                         comp_add = 0;
3344                         break;
3345                 } else if (!llapi_layout_is_composite(head)) {
3346                         fprintf(stderr,
3347                                 "%s setstripe: '%s' not a composite file\n",
3348                                 progname, fname);
3349                         llapi_layout_free(head);
3350                         return -EINVAL;
3351                 }
3352
3353                 rc = llapi_layout_comp_extent_get(head, &start, &prev_end);
3354                 if (rc) {
3355                         fprintf(stderr,
3356                                 "%s setstripe: cannot get prev extent: %s\n",
3357                                 progname, strerror(errno));
3358                         llapi_layout_free(head);
3359                         return rc;
3360                 }
3361
3362                 llapi_layout_free(head);
3363                 break;
3364         }
3365
3366         /* Make sure we use the first component of the layout to be added. */
3367         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
3368         if (rc < 0) {
3369                 fprintf(stderr,
3370                         "%s setstripe: cannot move component cursor: %s\n",
3371                         progname, strerror(errno));
3372                 return rc;
3373         }
3374
3375         rc = llapi_layout_comp_extent_get(layout, &start, &end);
3376         if (rc) {
3377                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
3378                         progname, strerror(errno));
3379                 return rc;
3380         }
3381
3382         if (start == 0 && end == 0) {
3383                 rc = layout_extend_comp(layout, start, &end,
3384                                         comp_add ? prev_end : 0);
3385                 if (rc)
3386                         return rc;
3387         }
3388
3389         if (start > prev_end || end < prev_end) {
3390                 fprintf(stderr,
3391                         "%s setstripe: first extent [%lu, %lu) not adjacent with extent end %lu\n",
3392                         progname, start, end, prev_end);
3393                 return -EINVAL;
3394         }
3395
3396         rc = llapi_layout_comp_extent_set(layout, prev_end, end);
3397         if (rc) {
3398                 fprintf(stderr,
3399                         "%s setstripe: cannot set component extent [%lu, %lu): %s\n",
3400                         progname, prev_end, end, strerror(errno));
3401                 return rc;
3402         }
3403
3404         return ret;
3405 }
3406
3407 static int mirror_adjust_first_extents(struct mirror_args *list)
3408 {
3409         int rc = 0;
3410
3411         if (!list)
3412                 return 0;
3413
3414         while (list) {
3415                 rc = layout_adjust_first_extent(NULL, list->m_layout, false);
3416                 if (rc)
3417                         break;
3418                 list = list->m_next;
3419         }
3420
3421         return rc;
3422 }
3423
3424 static inline bool arg_is_eof(char *arg)
3425 {
3426         return !strncmp(arg, "-1", strlen("-1")) ||
3427                !strncmp(arg, "EOF", strlen("EOF")) ||
3428                !strncmp(arg, "eof", strlen("eof"));
3429 }
3430
3431 /**
3432  * lfs_mirror_alloc() - Allocate a mirror argument structure.
3433  *
3434  * Return: Valid mirror_args pointer on success and
3435  *         NULL if memory allocation fails.
3436  */
3437 static struct mirror_args *lfs_mirror_alloc(void)
3438 {
3439         struct mirror_args *mirror = NULL;
3440
3441         while (1) {
3442                 mirror = calloc(1, sizeof(*mirror));
3443                 if (mirror) {
3444                         mirror->m_inherit = false;
3445                         break;
3446                 }
3447
3448                 sleep(1);
3449         }
3450
3451         return mirror;
3452 }
3453
3454 /**
3455  * lfs_mirror_free() - Free memory allocated for a mirror argument
3456  *                     structure.
3457  * @mirror: Previously allocated mirror argument structure by
3458  *          lfs_mirror_alloc().
3459  *
3460  * Free memory allocated for @mirror.
3461  *
3462  * Return: void.
3463  */
3464 static void lfs_mirror_free(struct mirror_args *mirror)
3465 {
3466         if (mirror->m_layout)
3467                 llapi_layout_free(mirror->m_layout);
3468         free(mirror);
3469 }
3470
3471 /**
3472  * lfs_mirror_list_free() - Free memory allocated for a mirror list.
3473  * @mirror_list: Previously allocated mirror list.
3474  *
3475  * Free memory allocated for @mirror_list.
3476  *
3477  * Return: void.
3478  */
3479 static void lfs_mirror_list_free(struct mirror_args *mirror_list)
3480 {
3481         struct mirror_args *next_mirror = NULL;
3482
3483         while (mirror_list) {
3484                 next_mirror = mirror_list->m_next;
3485                 lfs_mirror_free(mirror_list);
3486                 mirror_list = next_mirror;
3487         }
3488 }
3489
3490 enum {
3491         LFS_SETQUOTA_DELETE = (CHAR_MAX + 1),
3492         LFS_POOL_OPT,
3493         LFS_COMP_COUNT_OPT,
3494         LFS_COMP_START_OPT,
3495         LFS_COMP_FLAGS_OPT,
3496         LFS_COMP_DEL_OPT,
3497         LFS_COMP_SET_OPT,
3498         LFS_COMP_ADD_OPT,
3499         LFS_COMP_NO_VERIFY_OPT,
3500         LFS_PROJID_OPT,
3501         LFS_LAYOUT_FLAGS_OPT, /* used for mirror and foreign flags */
3502         LFS_MIRROR_ID_OPT,
3503         LFS_MIRROR_STATE_OPT,
3504         LFS_LAYOUT_COPY,
3505         LFS_MIRROR_INDEX_OPT,
3506         LFS_LAYOUT_FOREIGN_OPT,
3507         LFS_MODE_OPT,
3508         LFS_NEWERXY_OPT,
3509         LFS_INHERIT_RR_OPT,
3510         LFS_FIND_PERM,
3511         LFS_PRINTF_OPT,
3512         LFS_NO_FOLLOW_OPT,
3513         LFS_HEX_IDX_OPT,
3514         LFS_STATS_OPT,
3515         LFS_STATS_INTERVAL_OPT,
3516         LFS_LINKS_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         enum stats_flag stats_flag = STATS_OFF;
3573         long stats_interval_sec = 5;
3574
3575         struct option long_opts[] = {
3576 /* find { .val = '0',   .name = "null",         .has_arg = no_argument }, */
3577 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
3578         /* --block is only valid in migrate mode */
3579         { .val = 'b',   .name = "block",        .has_arg = no_argument },
3580 /* find { .val = 'B',   .name = "btime",        .has_arg = required_argument }*/
3581         { .val = LFS_COMP_ADD_OPT,
3582                         .name = "comp-add",     .has_arg = no_argument },
3583         { .val = LFS_COMP_ADD_OPT,
3584                         .name = "component-add", .has_arg = no_argument },
3585         { .val = LFS_COMP_DEL_OPT,
3586                         .name = "comp-del",     .has_arg = no_argument },
3587         { .val = LFS_COMP_DEL_OPT,
3588                         .name = "component-del", .has_arg = no_argument },
3589         { .val = LFS_COMP_FLAGS_OPT,
3590                         .name = "comp-flags",   .has_arg = required_argument },
3591         { .val = LFS_COMP_FLAGS_OPT,
3592                         .name = "component-flags",
3593                                                 .has_arg = required_argument },
3594         { .val = LFS_COMP_SET_OPT,
3595                         .name = "comp-set",     .has_arg = no_argument },
3596         { .val = LFS_COMP_SET_OPT,
3597                         .name = "component-set",
3598                                                 .has_arg = no_argument},
3599         { .val = LFS_COMP_NO_VERIFY_OPT,
3600                         .name = "no-verify",    .has_arg = no_argument},
3601         { .val = LFS_LAYOUT_FLAGS_OPT,
3602                         .name = "flags",        .has_arg = required_argument},
3603         { .val = LFS_LAYOUT_FOREIGN_OPT,
3604                         .name = "foreign",      .has_arg = optional_argument},
3605         { .val = LFS_MIRROR_ID_OPT,
3606                         .name = "mirror-id",    .has_arg = required_argument},
3607         { .val = LFS_MODE_OPT,
3608                         .name = "mode",         .has_arg = required_argument},
3609         { .val = LFS_LAYOUT_COPY,
3610                         .name = "copy",         .has_arg = required_argument},
3611         { .val = LFS_STATS_OPT,
3612                         .name = "stats",        .has_arg = no_argument},
3613         { .val = LFS_STATS_INTERVAL_OPT,
3614                         .name = "stats-interval",
3615                                                 .has_arg = required_argument},
3616         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument},
3617         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument},
3618         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument},
3619         { .val = 'C',   .name = "overstripe-count",
3620                                                 .has_arg = required_argument},
3621         { .val = 'd',   .name = "delete",       .has_arg = no_argument},
3622         { .val = 'd',   .name = "destroy",      .has_arg = no_argument},
3623         /* used with "lfs migrate -m" */
3624         { .val = 'd',   .name = "directory",    .has_arg = no_argument},
3625         /* --non-direct is only valid in migrate mode */
3626         { .val = 'D',   .name = "non-direct",   .has_arg = no_argument },
3627         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument},
3628         { .val = 'E',   .name = "component-end",
3629                                                 .has_arg = required_argument},
3630         { .val = 'f',   .name = "file",         .has_arg = required_argument },
3631 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
3632 /* find { .val = 'g',   .name = "gid",          .has_arg = no_argument }, */
3633 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
3634         { .val = 'h',   .name = "help",         .has_arg = no_argument },
3635         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument},
3636         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument},
3637         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument},
3638         { .val = 'I',   .name = "comp-id",      .has_arg = required_argument},
3639         { .val = 'I',   .name = "component-id", .has_arg = required_argument},
3640 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
3641         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
3642         { .val = 'm',   .name = "mdt",          .has_arg = required_argument},
3643         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument},
3644         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument},
3645         /* --non-block is only valid in migrate mode */
3646         { .val = 'n',   .name = "non-block",    .has_arg = no_argument },
3647         { .val = 'N',   .name = "mirror-count", .has_arg = optional_argument},
3648         { .val = 'o',   .name = "ost",          .has_arg = required_argument },
3649 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
3650         { .val = 'o',   .name = "ost-list",     .has_arg = required_argument },
3651         { .val = 'o',   .name = "ost_list",     .has_arg = required_argument },
3652 #endif
3653         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
3654 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
3655 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
3656 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
3657         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
3658         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
3659 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
3660 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
3661 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
3662 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
3663         /* --verbose is only valid in migrate mode */
3664         { .val = 'v',   .name = "verbose",      .has_arg = no_argument},
3665         { .val = 'W',   .name = "bandwidth",    .has_arg = required_argument },
3666         { .val = 'x',   .name = "xattr",        .has_arg = required_argument },
3667 /* dirstripe { .val = 'X',.name = "max-inherit",.has_arg = required_argument }*/
3668         { .val = 'y',   .name = "yaml",         .has_arg = required_argument },
3669         { .val = 'z',   .name = "ext-size",     .has_arg = required_argument},
3670         { .val = 'z',   .name = "extension-size", .has_arg = required_argument},
3671         { .name = NULL } };
3672
3673         setstripe_args_init(&lsa);
3674
3675         migrate_mode = (opc == SO_MIGRATE);
3676         mirror_mode = (opc == SO_MIRROR_CREATE || opc == SO_MIRROR_EXTEND);
3677         setstripe_mode = (opc == SO_SETSTRIPE);
3678         if (opc == SO_MIRROR_DELETE) {
3679                 delete = 1;
3680                 mirror_flags = MF_DESTROY;
3681         }
3682
3683         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
3684         progname = cmd;
3685         while ((c = getopt_long(argc, argv,
3686                                 "bc:C:dDE:f:hH:i:I:m:N::no:p:L:s:S:vx:W:y:z:",
3687                                 long_opts, NULL)) >= 0) {
3688                 size_units = 1;
3689                 switch (c) {
3690                 case 0:
3691                         /* Long options. */
3692                         break;
3693                 case LFS_COMP_ADD_OPT:
3694                         comp_add = 1;
3695                         break;
3696                 case LFS_COMP_DEL_OPT:
3697                         comp_del = 1;
3698                         break;
3699                 case LFS_COMP_FLAGS_OPT:
3700                         result = comp_str2flags(optarg, &lsa.lsa_comp_flags,
3701                                                 &lsa.lsa_comp_neg_flags);
3702                         if (result != 0)
3703                                 goto usage_error;
3704                         if (mirror_mode && lsa.lsa_comp_neg_flags) {
3705                                 fprintf(stderr,
3706                                         "%s: inverted flags are not supported\n",
3707                                         progname);
3708                                 goto usage_error;
3709                         }
3710                         break;
3711                 case LFS_COMP_SET_OPT:
3712                         comp_set = 1;
3713                         break;
3714                 case LFS_COMP_NO_VERIFY_OPT:
3715                         mirror_flags |= MF_NO_VERIFY;
3716                         break;
3717                 case LFS_MIRROR_ID_OPT: {
3718                         unsigned long int id;
3719
3720                         errno = 0;
3721                         id = strtoul(optarg, &end, 0);
3722                         if (errno != 0 || *end != '\0' || id == 0 ||
3723                             id > UINT16_MAX) {
3724                                 fprintf(stderr,
3725                                         "%s %s: invalid mirror ID '%s'\n",
3726                                         progname, argv[0], optarg);
3727                                 goto usage_error;
3728                         }
3729
3730                         mirror_id = (__u16)id;
3731                         break;
3732                 }
3733                 case LFS_LAYOUT_FLAGS_OPT: {
3734                         uint32_t neg_flags;
3735
3736                         /* check for numeric flags (foreign and mirror cases) */
3737                         if (setstripe_mode && !mirror_mode && !last_mirror) {
3738                                 errno = 0;
3739                                 flags = strtoul(optarg, &end, 16);
3740                                 if (errno != 0 || *end != '\0' ||
3741                                     flags >= UINT32_MAX) {
3742                                         fprintf(stderr,
3743                                                 "%s %s: invalid hex flags '%s'\n",
3744                                                 progname, argv[0], optarg);
3745                                         return CMD_HELP;
3746                                 }
3747                                 if (!foreign_mode) {
3748                                         fprintf(stderr,
3749                                                 "%s %s: hex flags must be specified with --foreign option\n",
3750                                                 progname, argv[0]);
3751                                         return CMD_HELP;
3752                                 }
3753                                 break;
3754                         }
3755
3756                         if (!mirror_mode || !last_mirror) {
3757                                 fprintf(stderr,
3758                                         "error: %s: --flags must be specified with --mirror-count|-N option\n",
3759                                         progname);
3760                                 goto usage_error;
3761                         }
3762
3763                         result = comp_str2flags(optarg, &last_mirror->m_flags,
3764                                                 &neg_flags);
3765                         if (result != 0)
3766                                 goto usage_error;
3767
3768                         if (neg_flags) {
3769                                 fprintf(stderr,
3770                                         "%s: inverted flags are not supported\n",
3771                                         progname);
3772                                 result = -EINVAL;
3773                                 goto usage_error;
3774                         }
3775                         if (last_mirror->m_flags & ~LCME_USER_MIRROR_FLAGS) {
3776                                 fprintf(stderr,
3777                                         "%s: unsupported mirror flags: %s\n",
3778                                         progname, optarg);
3779                                 result = -EINVAL;
3780                                 goto error;
3781                         }
3782                         break;
3783                 }
3784                 case LFS_LAYOUT_FOREIGN_OPT:
3785                         if (optarg) {
3786                                 /* check pure numeric */
3787                                 type = strtoul(optarg, &end, 0);
3788                                 if (*end) {
3789                                         /* check name */
3790                                         type = check_foreign_type_name(optarg);
3791                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
3792                                                 fprintf(stderr,
3793                                                         "%s %s: unrecognized foreign type '%s'\n",
3794                                                         progname, argv[0],
3795                                                         optarg);
3796                                                 return CMD_HELP;
3797                                         }
3798                                 } else if (type >= UINT32_MAX) {
3799                                         fprintf(stderr,
3800                                                 "%s %s: invalid foreign type '%s'\n",
3801                                                 progname, argv[0], optarg);
3802                                         return CMD_HELP;
3803                                 }
3804                         }
3805                         foreign_mode = true;
3806                         break;
3807                 case LFS_MODE_OPT:
3808                         mode_opt = optarg;
3809                         if (mode_opt) {
3810                                 mode = strtoul(mode_opt, &end, 8);
3811                                 if (*end != '\0') {
3812                                         fprintf(stderr,
3813                                                 "%s %s: bad mode '%s'\n",
3814                                                 progname, argv[0], mode_opt);
3815                                         return CMD_HELP;
3816                                 }
3817                                 previous_umask = umask(0);
3818                         }
3819                         break;
3820                 case LFS_LAYOUT_COPY:
3821                         from_copy = true;
3822                         template = optarg;
3823                         break;
3824                 case LFS_STATS_OPT:
3825                         stats_flag = STATS_ON;
3826                         break;
3827                 case LFS_STATS_INTERVAL_OPT:
3828                         stats_flag = STATS_ON;
3829                         stats_interval_sec = strtol(optarg, &end, 0);
3830                         if (stats_interval_sec == 0)
3831                                 stats_interval_sec = 5;
3832                         break;
3833                 case 'b':
3834                         if (!migrate_mode) {
3835                                 fprintf(stderr,
3836                                         "%s %s: -b|--block valid only for migrate command\n",
3837                                         progname, argv[0]);
3838                                 goto usage_error;
3839                         }
3840                         migration_block = true;
3841                         break;
3842                 case 'C':
3843                         if (lsa.lsa_pattern == LLAPI_LAYOUT_MDT) {
3844                                 fprintf(stderr,
3845                                         "%s %s: -C|--overstripe-count incompatible with DoM layout\n",
3846                                         progname, argv[0]);
3847                                 goto usage_error;
3848                         }
3849                         lsa.lsa_pattern = LLAPI_LAYOUT_OVERSTRIPING;
3850                         fallthrough;
3851                 case 'c':
3852                         errno = 0;
3853                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
3854                         if (errno != 0 || *end != '\0'|| optarg == end ||
3855                             lsa.lsa_stripe_count < -1 ||
3856                             lsa.lsa_stripe_count > LOV_MAX_STRIPE_COUNT) {
3857                                 fprintf(stderr,
3858                                         "%s %s: invalid stripe count '%s'\n",
3859                                         progname, argv[0], optarg);
3860                                 goto usage_error;
3861                         }
3862
3863                         if (lsa.lsa_stripe_count == -1)
3864                                 lsa.lsa_stripe_count = LLAPI_LAYOUT_WIDE;
3865                         break;
3866                 case 'd':
3867                         if (migrate_mode) {
3868                                 migrate_mdt_param.fp_max_depth = 1;
3869                         } else {
3870                                 /* delete the default striping pattern */
3871                                 delete = 1;
3872                                 if (opc == SO_MIRROR_SPLIT) {
3873                                         if (has_m_file) {
3874                                                 fprintf(stderr,
3875                                                       "%s %s: -d cannot used with -f\n",
3876                                                         progname, argv[0]);
3877                                                 goto usage_error;
3878                                         }
3879                                         mirror_flags |= MF_DESTROY;
3880                                 }
3881                         }
3882                         break;
3883                 case 'D':
3884                         if (!migrate_mode) {
3885                                 fprintf(stderr,
3886                                         "%s %s: -D|--non-direct is valid only for migrate command\n",
3887                                         progname, argv[0]);
3888                                 goto usage_error;
3889                         }
3890                         migration_flags |= LLAPI_MIGRATION_NONDIRECT;
3891                         break;
3892                 case 'E':
3893                         if (lsa.lsa_comp_end != 0) {
3894                                 result = comp_args_to_layout(lpp, &lsa, true);
3895                                 if (result) {
3896                                         fprintf(stderr, "%s: invalid layout\n",
3897                                                 progname);
3898                                         goto usage_error;
3899                                 }
3900
3901                                 setstripe_args_init_inherit(&lsa);
3902                         }
3903
3904                         if (arg_is_eof(optarg)) {
3905                                 lsa.lsa_comp_end = LUSTRE_EOF;
3906                         } else {
3907                                 result = llapi_parse_size(optarg,
3908                                                           &lsa.lsa_comp_end,
3909                                                           &size_units, 0);
3910                                 /* assume units of KB if too small */
3911                                 if (lsa.lsa_comp_end < 4096)
3912                                         lsa.lsa_comp_end *= 1024;
3913                                 if (result ||
3914                                     lsa.lsa_comp_end & (LOV_MIN_STRIPE_SIZE - 1)) {
3915                                         fprintf(stderr,
3916                                                 "%s %s: invalid component end '%s'\n",
3917                                                 progname, argv[0], optarg);
3918                                         goto usage_error;
3919                                 }
3920                         }
3921                         break;
3922                 case 'H':
3923                         if (!migrate_mode) {
3924                                 fprintf(stderr,
3925                                         "--mdt-hash is valid only for migrate command\n");
3926                                 return CMD_HELP;
3927                         }
3928
3929                         lsa.lsa_pattern = check_hashtype(optarg);
3930                         if (lsa.lsa_pattern == 0) {
3931                                 fprintf(stderr,
3932                                         "%s %s: bad stripe hash type '%s'\n",
3933                                         progname, argv[0], optarg);
3934                                 return CMD_HELP;
3935                         }
3936                         break;
3937                 case 'i':
3938                         errno = 0;
3939                         lsa.lsa_stripe_off = strtol(optarg, &end, 0);
3940                         if (errno != 0 || *end != '\0' || optarg == end ||
3941                             lsa.lsa_stripe_off < -1 ||
3942                             lsa.lsa_stripe_off > LOV_V1_INSANE_STRIPE_COUNT) {
3943                                 fprintf(stderr,
3944                                         "%s %s: invalid stripe offset '%s'\n",
3945                                         progname, argv[0], optarg);
3946                                 goto usage_error;
3947                         }
3948                         if (lsa.lsa_stripe_off == -1)
3949                                 lsa.lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
3950                         break;
3951                 case 'I':
3952                         comp_id = strtoul(optarg, &end, 0);
3953                         if (*end != '\0' || comp_id == 0 ||
3954                             comp_id > LCME_ID_MAX) {
3955                                 fprintf(stderr,
3956                                         "%s %s: invalid component ID '%s'\n",
3957                                         progname, argv[0], optarg);
3958                                 goto usage_error;
3959                         }
3960                         break;
3961                 case 'f':
3962                         if (opc != SO_MIRROR_EXTEND && opc != SO_MIRROR_SPLIT) {
3963                                 fprintf(stderr,
3964                                         "error: %s: invalid option: %s\n",
3965                                         progname, argv[optopt + 1]);
3966                                 goto usage_error;
3967                         }
3968                         if (opc == SO_MIRROR_EXTEND) {
3969                                 if (!last_mirror) {
3970                                         fprintf(stderr,
3971                                 "error: %s: '-N' must exist in front of '%s'\n",
3972                                                 progname, argv[optopt + 1]);
3973                                         goto usage_error;
3974                                 }
3975                                 last_mirror->m_file = optarg;
3976                                 last_mirror->m_count = 1;
3977                         } else {
3978                                 /* mirror split */
3979                                 if (!mirror_list)
3980                                         mirror_list = lfs_mirror_alloc();
3981                                 mirror_list->m_file = optarg;
3982                         }
3983                         has_m_file = true;
3984                         break;
3985                 case 'L':
3986                         if (strcmp(argv[optind - 1], "mdt") == 0) {
3987                                 /* Can be only the first component */
3988                                 if (layout) {
3989                                         result = -EINVAL;
3990                                         fprintf(stderr,
3991                                                 "error: 'mdt' layout can be only the first one\n");
3992                                         goto error;
3993                                 }
3994                                 if (lsa.lsa_comp_end > (1ULL << 30)) { /* 1Gb */
3995                                         result = -EFBIG;
3996                                         fprintf(stderr,
3997                                                 "error: 'mdt' layout size is too big\n");
3998                                         goto error;
3999                                 }
4000                                 lsa.lsa_pattern = LLAPI_LAYOUT_MDT;
4001                                 lsa.lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
4002                         } else if (strcmp(argv[optind - 1], "raid0") != 0) {
4003                                 result = -EINVAL;
4004                                 fprintf(stderr,
4005                                         "error: layout '%s' is unknown, supported layouts are: 'mdt', 'raid0'\n",
4006                                         argv[optind]);
4007                                 goto error;
4008                         }
4009                         break;
4010                 case 'm':
4011                         if (!migrate_mode) {
4012                                 fprintf(stderr,
4013                                         "%s %s: -m|--mdt-index is valid only for migrate command\n",
4014                                         progname, argv[0]);
4015                                 goto usage_error;
4016                         }
4017                         migrate_mdt_mode = true;
4018                         lsa.lsa_nr_tgts = parse_targets(tgts,
4019                                                 sizeof(tgts) / sizeof(__u32),
4020                                                 lsa.lsa_nr_tgts, optarg, NULL);
4021                         if (lsa.lsa_nr_tgts < 0) {
4022                                 fprintf(stderr,
4023                                         "%s: invalid MDT target(s) '%s'\n",
4024                                         progname, optarg);
4025                                 goto usage_error;
4026                         }
4027
4028                         lsa.lsa_tgts = tgts;
4029                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
4030                                 lsa.lsa_stripe_off = tgts[0];
4031                         break;
4032                 case 'n':
4033                         if (!migrate_mode) {
4034                                 fprintf(stderr,
4035                                         "%s %s: -n|--non-block valid only for migrate command\n",
4036                                         progname, argv[0]);
4037                                 goto usage_error;
4038                         }
4039                         migration_flags |= LLAPI_MIGRATION_NONBLOCK;
4040                         break;
4041                 case 'N':
4042                         if (opc == SO_SETSTRIPE) {
4043                                 opc = SO_MIRROR_CREATE;
4044                                 mirror_mode = true;
4045                         }
4046                         mirror_count = 1;
4047                         if (optarg) {
4048                                 errno = 0;
4049                                 mirror_count = strtoul(optarg, &end, 0);
4050                                 if (errno != 0 || *end != '\0' ||
4051                                     mirror_count == 0 ||
4052                                     mirror_count > LUSTRE_MIRROR_COUNT_MAX) {
4053                                         fprintf(stderr,
4054                                                 "error: %s: bad mirror count: %s\n",
4055                                                 progname, optarg);
4056                                         result = -EINVAL;
4057                                         goto error;
4058                                 }
4059                         }
4060
4061                         new_mirror = lfs_mirror_alloc();
4062                         new_mirror->m_count = mirror_count;
4063
4064                         if (!mirror_list)
4065                                 mirror_list = new_mirror;
4066
4067                         if (last_mirror) {
4068                                 /* wrap up last mirror */
4069                                 if (!setstripe_args_specified(&lsa))
4070                                         last_mirror->m_inherit = true;
4071                                 if (lsa.lsa_comp_end == 0)
4072                                         lsa.lsa_comp_end = LUSTRE_EOF;
4073
4074                                 result = comp_args_to_layout(lpp, &lsa, true);
4075                                 if (result) {
4076                                         lfs_mirror_free(new_mirror);
4077                                         goto error;
4078                                 }
4079
4080                                 setstripe_args_init_inherit(&lsa);
4081
4082                                 last_mirror->m_next = new_mirror;
4083                         }
4084
4085                         last_mirror = new_mirror;
4086                         lpp = &last_mirror->m_layout;
4087                         break;
4088                 case 'o':
4089 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4090                         if (strcmp(argv[optind - 1], "--ost-list") == 0)
4091                                 fprintf(stderr,
4092                                         "warning: '--ost-list' is deprecated, use '--ost' instead\n");
4093 #endif
4094                         if (lsa.lsa_pattern == LLAPI_LAYOUT_MDT) {
4095                                 fprintf(stderr,
4096                                         "%s %s: -o|--ost incompatible with DoM layout\n",
4097                                         progname, argv[0]);
4098                                 goto usage_error;
4099                         }
4100                         /*
4101                          * -o allows overstriping, and must note it because
4102                          * parse_targets is shared with MDT striping, which
4103                          * does not allow duplicates
4104                          */
4105                         lsa.lsa_pattern = LLAPI_LAYOUT_OVERSTRIPING;
4106                         lsa.lsa_nr_tgts = parse_targets(tgts,
4107                                                 sizeof(tgts) / sizeof(__u32),
4108                                                 lsa.lsa_nr_tgts, optarg,
4109                                                 &lsa.lsa_pattern);
4110                         if (lsa.lsa_nr_tgts < 0) {
4111                                 fprintf(stderr,
4112                                         "%s %s: invalid OST target(s) '%s'\n",
4113                                         progname, argv[0], optarg);
4114                                 goto usage_error;
4115                         }
4116
4117                         lsa.lsa_tgts = tgts;
4118                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
4119                                 lsa.lsa_stripe_off = tgts[0];
4120                         break;
4121                 case 'p':
4122                         if (!optarg)
4123                                 goto usage_error;
4124
4125                         if (optarg[0] == '\0' || lov_pool_is_inherited(optarg))
4126                                 lsa.lsa_pool_name = NULL;
4127                         else
4128                                 lsa.lsa_pool_name = optarg;
4129                         break;
4130                 case 'S':
4131                         result = llapi_parse_size(optarg, &lsa.lsa_stripe_size,
4132                                                   &size_units, 0);
4133                         /* assume units of KB if too small to be valid */
4134                         if (lsa.lsa_stripe_size < 4096)
4135                                 lsa.lsa_stripe_size *= 1024;
4136                         if (result ||
4137                             lsa.lsa_stripe_size & (LOV_MIN_STRIPE_SIZE - 1)) {
4138                                 fprintf(stderr,
4139                                         "%s %s: invalid stripe size '%s'\n",
4140                                         progname, argv[0], optarg);
4141                                 goto usage_error;
4142                         }
4143                         break;
4144                 case 'v':
4145                         if (!migrate_mode) {
4146                                 fprintf(stderr,
4147                                         "%s %s: -v|--verbose valid only for migrate command\n",
4148                                         progname, argv[0]);
4149                                 goto usage_error;
4150                         }
4151                         migrate_mdt_param.fp_verbose = VERBOSE_DETAIL;
4152                         migration_flags = LLAPI_MIGRATION_VERBOSE;
4153                         break;
4154                 case 'x':
4155                         xattr = optarg;
4156                         break;
4157                 case 'W':
4158                         if (!migrate_mode && !mirror_mode) {
4159                                 fprintf(stderr,
4160                                         "--bandwidth is valid only for migrate and mirror mode\n");
4161                                 goto error;
4162                         }
4163                         if (llapi_parse_size(optarg, &bandwidth_bytes_sec,
4164                                              &bandwidth_unit, 0) < 0) {
4165                                 fprintf(stderr,
4166                                         "error: %s: bad value for bandwidth '%s'\n",
4167                                         argv[0], optarg);
4168                                 goto error;
4169                         }
4170                         break;
4171                 case 'y':
4172                         from_yaml = true;
4173                         template = optarg;
4174                         break;
4175                 case 'z':
4176                         result = llapi_parse_size(optarg,
4177                                                   &lsa.lsa_extension_size,
4178                                                   &size_units, 0);
4179                         if (result) {
4180                                 fprintf(stderr,
4181                                         "%s %s: invalid extension size '%s'\n",
4182                                         progname, argv[0], optarg);
4183                                 goto usage_error;
4184                         }
4185
4186                         lsa.lsa_extension_comp = true;
4187                         break;
4188                 default:
4189                         fprintf(stderr, "%s: unrecognized option '%s'\n",
4190                                 progname, argv[optind - 1]);
4191                 case 'h':
4192                         goto usage_error;
4193                 }
4194         }
4195
4196         fname = argv[optind];
4197
4198         if (optind == argc) {
4199                 fprintf(stderr, "%s %s: FILE must be specified\n",
4200                         progname, argv[0]);
4201                 goto usage_error;
4202         }
4203
4204         /* lfs migrate $filename should keep the file's layout by default */
4205         if (migrate_mode && !layout && !from_yaml &&
4206             !setstripe_args_specified(&lsa) && !lsa.lsa_pool_name)
4207                 from_copy = true;
4208
4209         if (xattr && !foreign_mode) {
4210                 /*
4211                  * only print a warning as this is harmless and will be ignored
4212                  */
4213                 fprintf(stderr,
4214                         "%s %s: xattr has been specified for non-foreign layout\n",
4215                         progname, argv[0]);
4216         } else if (foreign_mode && !xattr) {
4217                 fprintf(stderr,
4218                         "%s %s: xattr must be provided in foreign mode\n",
4219                         progname, argv[0]);
4220                 goto usage_error;
4221         }
4222
4223         if (foreign_mode && (!setstripe_mode || comp_add | comp_del ||
4224             comp_set || comp_id || delete || from_copy ||
4225             setstripe_args_specified(&lsa) || lsa.lsa_nr_tgts ||
4226             lsa.lsa_tgts)) {
4227                 fprintf(stderr,
4228                         "%s %s: only --xattr/--flags/--mode options are valid with --foreign\n",
4229                         progname, argv[0]);
4230                 return CMD_HELP;
4231         }
4232
4233         if (mirror_mode && mirror_count == 0) {
4234                 fprintf(stderr,
4235                         "error: %s: --mirror-count|-N option is required\n",
4236                         progname);
4237                 result = -EINVAL;
4238                 goto error;
4239         }
4240
4241         if (mirror_mode) {
4242                 if (!setstripe_args_specified(&lsa))
4243                         last_mirror->m_inherit = true;
4244                 if (lsa.lsa_comp_end == 0)
4245                         lsa.lsa_comp_end = LUSTRE_EOF;
4246         }
4247
4248         if (lsa.lsa_comp_end != 0) {
4249                 result = comp_args_to_layout(lpp, &lsa, true);
4250                 if (result) {
4251                         fprintf(stderr, "error: %s: invalid layout\n",
4252                                 progname);
4253                         result = -EINVAL;
4254                         goto error;
4255                 }
4256         }
4257
4258         if (mirror_flags & MF_NO_VERIFY) {
4259                 if (opc != SO_MIRROR_EXTEND) {
4260                         fprintf(stderr,
4261                                 "error: %s: --no-verify is valid only for lfs mirror extend command\n",
4262                                 progname);
4263                         result = -EINVAL;
4264                         goto error;
4265                 } else if (!has_m_file) {
4266                         fprintf(stderr,
4267                                 "error: %s: --no-verify must be specified with -f <victim_file> option\n",
4268                                 progname);
4269                         result = -EINVAL;
4270                         goto error;
4271                 }
4272         }
4273
4274         if (comp_set && !comp_id && !lsa.lsa_pool_name) {
4275                 fprintf(stderr,
4276                         "%s %s: --component-set doesn't have component-id set\n",
4277                         progname, argv[0]);
4278                 goto usage_error;
4279         }
4280
4281         if ((delete + comp_set + comp_del + comp_add) > 1) {
4282                 fprintf(stderr,
4283                         "%s %s: options --component-set, --component-del, --component-add and -d are mutually exclusive\n",
4284                         progname, argv[0]);
4285                 goto usage_error;
4286         }
4287
4288         if (delete && (setstripe_args_specified(&lsa) || comp_id != 0 ||
4289                        lsa.lsa_comp_flags != 0 || layout != NULL)) {
4290                 fprintf(stderr,
4291                         "%s %s: option -d is mutually exclusive with -s, -c, -o, -p, -I, -F and -E options\n",
4292                         progname, argv[0]);
4293                 goto usage_error;
4294         }
4295
4296         if ((comp_set || comp_del) &&
4297             (setstripe_args_specified(&lsa) || layout != NULL)) {
4298                 fprintf(stderr,
4299                         "%s %s: options --component-del and --component-set are mutually exclusive when used with -c, -E, -o, -p, or -s\n",
4300                         progname, argv[0]);
4301                 goto usage_error;
4302         }
4303
4304         if (comp_del && comp_id != 0 && lsa.lsa_comp_flags != 0) {
4305                 fprintf(stderr,
4306                         "%s %s: options -I and -F are mutually exclusive when used with --component-del\n",
4307                         progname, argv[0]);
4308                 goto usage_error;
4309         }
4310
4311         if (comp_add || comp_del) {
4312                 struct stat st;
4313
4314                 result = lstat(fname, &st);
4315                 if (result == 0 && S_ISDIR(st.st_mode)) {
4316                         fprintf(stderr,
4317                                 "%s setstripe: cannot use --component-add or --component-del for directory\n",
4318                                 progname);
4319                         goto usage_error;
4320                 }
4321
4322                 if (mirror_mode) {
4323                         fprintf(stderr,
4324                                 "error: %s: can't use --component-add or --component-del for mirror operation\n",
4325                                 progname);
4326                         goto usage_error;
4327                 }
4328         }
4329
4330         if (comp_add) {
4331                 if (!layout) {
4332                         fprintf(stderr,
4333                                 "%s %s: option -E must be specified with --component-add\n",
4334                                 progname, argv[0]);
4335                         goto usage_error;
4336                 }
4337         }
4338
4339         if (from_yaml && from_copy) {
4340                 fprintf(stderr,
4341                         "%s: can't specify --yaml and --copy together\n",
4342                         progname);
4343                 goto error;
4344         }
4345
4346         if ((from_yaml || from_copy) &&
4347             (setstripe_args_specified(&lsa) || layout != NULL)) {
4348                 fprintf(stderr,
4349                         "error: %s: can't specify --yaml or --copy with -c, -S, -i, -o, -p or -E options.\n",
4350                         argv[0]);
4351                 goto error;
4352         }
4353
4354         if ((migration_flags & LLAPI_MIGRATION_NONBLOCK) && migration_block) {
4355                 fprintf(stderr,
4356                         "%s %s: options --non-block and --block are mutually exclusive\n",
4357                         progname, argv[0]);
4358                 goto usage_error;
4359         }
4360
4361         if (!comp_del && !comp_set && opc != SO_MIRROR_SPLIT &&
4362             opc != SO_MIRROR_DELETE && comp_id != 0) {
4363                 fprintf(stderr,
4364                         "%s: option -I can only be used with --component-del or --component-set or lfs mirror split\n",
4365                         progname);
4366                 goto usage_error;
4367         }
4368
4369         if (migrate_mdt_mode) {
4370                 struct lmv_user_md *lmu;
4371
4372                 /* initialize migrate mdt parameters */
4373                 lmu = calloc(1, lmv_user_md_size(lsa.lsa_nr_tgts,
4374                                                  LMV_USER_MAGIC_SPECIFIC));
4375                 if (!lmu) {
4376                         fprintf(stderr,
4377                                 "%s %s: cannot allocate memory for lmv_user_md: %s\n",
4378                                 progname, argv[0], strerror(ENOMEM));
4379                         result = -ENOMEM;
4380                         goto error;
4381                 }
4382                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
4383                         lmu->lum_stripe_count = lsa.lsa_stripe_count;
4384                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT) {
4385                         fprintf(stderr,
4386                                 "%s %s: migrate should specify MDT index\n",
4387                                 progname, argv[0]);
4388                         free(lmu);
4389                         goto usage_error;
4390                 }
4391                 lmu->lum_stripe_offset = lsa.lsa_stripe_off;
4392                 if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
4393                         lmu->lum_hash_type = lsa.lsa_pattern;
4394                 else
4395                         lmu->lum_hash_type = LMV_HASH_TYPE_UNKNOWN;
4396                 if (lsa.lsa_pool_name) {
4397                         strncpy(lmu->lum_pool_name, lsa.lsa_pool_name,
4398                                 sizeof(lmu->lum_pool_name) - 1);
4399                         lmu->lum_pool_name[sizeof(lmu->lum_pool_name) - 1] = 0;
4400                 }
4401                 if (lsa.lsa_nr_tgts > 1) {
4402                         int i;
4403
4404                         if (lsa.lsa_stripe_count > 0 &&
4405                             lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
4406                             lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
4407                                 fprintf(stderr,
4408                                         "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
4409                                         progname, lsa.lsa_stripe_count,
4410                                         lsa.lsa_nr_tgts);
4411                                 free(lmu);
4412                                 goto usage_error;
4413                         }
4414
4415                         lmu->lum_magic = LMV_USER_MAGIC_SPECIFIC;
4416                         lmu->lum_stripe_count = lsa.lsa_nr_tgts;
4417                         for (i = 0; i < lsa.lsa_nr_tgts; i++)
4418                                 lmu->lum_objects[i].lum_mds = lsa.lsa_tgts[i];
4419                 } else {
4420                         lmu->lum_magic = LMV_USER_MAGIC;
4421                 }
4422
4423                 migrate_mdt_param.fp_lmv_md = lmu;
4424                 migrate_mdt_param.fp_migrate = 1;
4425         } else if (!layout) {
4426                 if (lsa_args_stripe_count_check(&lsa))
4427                         goto usage_error;
4428
4429                 /* initialize stripe parameters */
4430                 param = calloc(1, offsetof(typeof(*param),
4431                                lsp_osts[lsa.lsa_nr_tgts]));
4432                 if (!param) {
4433                         fprintf(stderr,
4434                                 "%s %s: cannot allocate memory for parameters: %s\n",
4435                                 progname, argv[0], strerror(ENOMEM));
4436                         result = -ENOMEM;
4437                         goto error;
4438                 }
4439
4440                 if (lsa.lsa_stripe_size != LLAPI_LAYOUT_DEFAULT)
4441                         param->lsp_stripe_size = lsa.lsa_stripe_size;
4442                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
4443                         if (lsa.lsa_stripe_count == LLAPI_LAYOUT_WIDE)
4444                                 param->lsp_stripe_count = -1;
4445                         else
4446                                 param->lsp_stripe_count = lsa.lsa_stripe_count;
4447                 }
4448                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
4449                         param->lsp_stripe_offset = -1;
4450                 else
4451                         param->lsp_stripe_offset = lsa.lsa_stripe_off;
4452                 param->lsp_stripe_pattern =
4453                                 llapi_pattern_to_lov(lsa.lsa_pattern);
4454                 if (param->lsp_stripe_pattern == EINVAL) {
4455                         fprintf(stderr, "error: %s: invalid stripe pattern\n",
4456                                 argv[0]);
4457                         free(param);
4458                         goto usage_error;
4459                 }
4460                 param->lsp_pool = lsa.lsa_pool_name;
4461                 param->lsp_is_specific = false;
4462
4463                 if (lsa.lsa_nr_tgts > 0) {
4464                         param->lsp_is_specific = true;
4465                         param->lsp_stripe_count = lsa.lsa_nr_tgts;
4466                         memcpy(param->lsp_osts, tgts,
4467                                sizeof(*tgts) * lsa.lsa_nr_tgts);
4468                 }
4469         }
4470
4471         if (from_yaml) {
4472                 /* generate a layout from a YAML template */
4473                 result = lfs_comp_create_from_yaml(template, &layout,
4474                                                    &lsa, tgts);
4475                 if (result) {
4476                         fprintf(stderr,
4477                                 "error: %s: can't create composite layout from template file %s\n",
4478                                 argv[0], template);
4479                         goto error;
4480                 }
4481         }
4482
4483         if (layout != NULL || mirror_list != NULL) {
4484                 if (mirror_list)
4485                         result = mirror_adjust_first_extents(mirror_list);
4486                 else
4487                         result = layout_adjust_first_extent(fname, layout,
4488                                                             comp_add);
4489                 if (result == -ENODATA)
4490                         comp_add = 0;
4491                 else if (result != 0) {
4492                         fprintf(stderr, "error: %s: invalid layout\n",
4493                                 progname);
4494                         goto error;
4495                 }
4496         }
4497
4498         for (fname = argv[optind]; fname != NULL; fname = argv[++optind]) {
4499                 if (from_copy) {
4500                         layout = llapi_layout_get_by_path(template ?: fname, 0);
4501                         if (!layout) {
4502                                 fprintf(stderr,
4503                                         "%s: can't create composite layout from file %s: %s\n",
4504                                         progname, template ?: fname,
4505                                         strerror(errno));
4506                                 result = -errno;
4507                                 goto error;
4508                         }
4509                 }
4510
4511                 if (migrate_mdt_mode) {
4512                         result = llapi_migrate_mdt(fname, &migrate_mdt_param);
4513                 } else if (migrate_mode) {
4514                         if (from_copy) {
4515                                 /*
4516                                  * Strip the source layout of specific
4517                                  * OST object/index values.
4518                                  */
4519                                 result = llapi_layout_ost_index_set(layout, 0,
4520                                                 LLAPI_LAYOUT_DEFAULT);
4521                                 if (result) {
4522                                         fprintf(stderr,
4523                                                 "%s: set default ost index failed: %s\n",
4524                                                 progname, strerror(errno));
4525                                         result = -errno;
4526                                         goto error;
4527                                 }
4528                         }
4529
4530                         result = lfs_migrate(fname, migration_flags, param,
4531                                              layout, bandwidth_bytes_sec,
4532                                              stats_flag, stats_interval_sec);
4533                 } else if (comp_set != 0) {
4534                         result = lfs_component_set(fname, comp_id,
4535                                                    lsa.lsa_pool_name,
4536                                                    lsa.lsa_comp_flags,
4537                                                    lsa.lsa_comp_neg_flags);
4538                 } else if (comp_del != 0) {
4539                         result = lfs_component_del(fname, comp_id,
4540                                                    lsa.lsa_comp_flags,
4541                                                    lsa.lsa_comp_neg_flags);
4542                 } else if (comp_add != 0) {
4543                         result = lfs_component_add(fname, layout);
4544                 } else if (opc == SO_MIRROR_CREATE) {
4545                         result = mirror_create(fname, mirror_list);
4546                 } else if (opc == SO_MIRROR_EXTEND) {
4547                         result = mirror_extend(fname, mirror_list,
4548                                                mirror_flags,
4549                                                bandwidth_bytes_sec,
4550                                                stats_flag, stats_interval_sec);
4551                 } else if (opc == SO_MIRROR_SPLIT || opc == SO_MIRROR_DELETE) {
4552                         if (!mirror_id && !comp_id && !lsa.lsa_pool_name) {
4553                                 fprintf(stderr,
4554                                         "%s: no mirror id, component id, or pool name specified to delete from '%s'\n",
4555                                         progname, fname);
4556                                 goto usage_error;
4557                         }
4558                         if (lsa.lsa_pool_name)
4559                                 mirror_flags |= MF_COMP_POOL;
4560                         else if (mirror_id != 0)
4561                                 comp_id = mirror_id;
4562                         else
4563                                 mirror_flags |= MF_COMP_ID;
4564                         if (has_m_file && !strcmp(fname, mirror_list->m_file)) {
4565                                 fprintf(stderr,
4566                                         "%s: the file specified by -f cannot be same as the source file '%s'\n",
4567                                         progname, fname);
4568                                 goto usage_error;
4569                         }
4570                         result = mirror_split(fname, comp_id, lsa.lsa_pool_name,
4571                                               mirror_flags,
4572                                               has_m_file ? mirror_list->m_file :
4573                                               NULL);
4574                 } else if (layout) {
4575                         result = lfs_component_create(fname, O_CREAT | O_WRONLY,
4576                                                       mode, layout);
4577                         if (result >= 0) {
4578                                 close(result);
4579                                 result = 0;
4580                         }
4581                 } else if (foreign_mode) {
4582                         result = llapi_file_create_foreign(fname, mode, type,
4583                                                            flags, xattr);
4584                         if (result >= 0) {
4585                                 close(result);
4586                                 result = 0;
4587                         }
4588                 } else {
4589                         result = llapi_file_open_param(fname,
4590                                                        O_CREAT | O_WRONLY,
4591                                                        mode, param);
4592                         if (result >= 0) {
4593                                 close(result);
4594                                 result = 0;
4595                         }
4596                 }
4597                 if (result) {
4598                         /* Save the first error encountered. */
4599                         if (result2 == 0)
4600                                 result2 = result;
4601                         continue;
4602                 }
4603         }
4604
4605         if (mode_opt)
4606                 umask(previous_umask);
4607
4608         free(param);
4609         free(migrate_mdt_param.fp_lmv_md);
4610         llapi_layout_free(layout);
4611         lfs_mirror_list_free(mirror_list);
4612         return result2;
4613 usage_error:
4614         result = CMD_HELP;
4615 error:
4616         llapi_layout_free(layout);
4617         lfs_mirror_list_free(mirror_list);
4618         return result;
4619 }
4620
4621 static int lfs_poollist(int argc, char **argv)
4622 {
4623         if (argc != 2)
4624                 return CMD_HELP;
4625
4626         return llapi_poollist(argv[1]);
4627 }
4628
4629 #define FP_DEFAULT_TIME_MARGIN (24 * 60 * 60)
4630 static int set_time(struct find_param *param, time_t *time, time_t *set,
4631                     char *str)
4632 {
4633         long long t = 0;
4634         int sign = 0;
4635         char *endptr = "AD";
4636         char *timebuf;
4637
4638         if (str[0] == '+')
4639                 sign = 1;
4640         else if (str[0] == '-')
4641                 sign = -1;
4642
4643         if (sign)
4644                 str++;
4645
4646         for (timebuf = str; *endptr && *(endptr + 1); timebuf = endptr + 1) {
4647                 long long val = strtoll(timebuf, &endptr, 0);
4648                 int unit = 1;
4649
4650                 switch (*endptr) {
4651                 case  'y':
4652                         unit *= 52; /* 52 weeks + 1 day below */
4653                         fallthrough;
4654                 case  'w':
4655                         unit *= 7;
4656                         if (param->fp_time_margin == FP_DEFAULT_TIME_MARGIN)
4657                                 param->fp_time_margin *= (1 + unit / 52);
4658                         unit += (*endptr == 'y'); /* +1 day for 365 days/year */
4659                         fallthrough;
4660                 case '\0': /* days are default unit if none used */
4661                         fallthrough;
4662                 case  'd':
4663                         unit *= 24;
4664                         fallthrough;
4665                 case  'h':
4666                         unit *= 60;
4667                         fallthrough;
4668                 case  'm':
4669                         unit *= 60;
4670                         fallthrough;
4671                 case  's':
4672                         break;
4673                         /* don't need to multiply by 1 for seconds */
4674                 default:
4675                         fprintf(stderr,
4676                                 "%s find: bad time string '%s': %s\n",
4677                                 progname, timebuf, strerror(EINVAL));
4678                         return INT_MAX;
4679                 }
4680
4681                 if (param->fp_time_margin == 0 ||
4682                     (*endptr && unit < param->fp_time_margin))
4683                         param->fp_time_margin = unit;
4684
4685                 t += val * unit;
4686         }
4687         if (*time < t) {
4688                 if (sign != 0)
4689                         str--;
4690                 fprintf(stderr, "%s find: bad time '%s': too large\n",
4691                         progname, str);
4692                 return INT_MAX;
4693         }
4694
4695         *set = *time - t;
4696
4697         return sign;
4698 }
4699
4700 static int str2quotaid(__u32 *id, const char *arg)
4701 {
4702         unsigned long int projid_tmp = 0;
4703         char *endptr = NULL;
4704
4705         projid_tmp = strtoul(arg, &endptr, 10);
4706         if (*endptr != '\0')
4707                 return -EINVAL;
4708         /* UINT32_MAX is not allowed - see projid_valid()/INVALID_PROJID */
4709         if (projid_tmp >= UINT32_MAX)
4710                 return -ERANGE;
4711
4712         *id = projid_tmp;
4713         return 0;
4714 }
4715
4716 static int name2uid(unsigned int *id, const char *name)
4717 {
4718         struct passwd *passwd;
4719
4720         passwd = getpwnam(name);
4721         if (!passwd)
4722                 return -ENOENT;
4723         *id = passwd->pw_uid;
4724
4725         return 0;
4726 }
4727
4728 static int name2gid(unsigned int *id, const char *name)
4729 {
4730         struct group *group;
4731
4732         group = getgrnam(name);
4733         if (!group)
4734                 return -ENOENT;
4735         *id = group->gr_gid;
4736
4737         return 0;
4738 }
4739
4740 static inline int name2projid(unsigned int *id, const char *name)
4741 {
4742         return -ENOTSUP;
4743 }
4744
4745 static int uid2name(char **name, unsigned int id)
4746 {
4747         struct passwd *passwd;
4748
4749         passwd = getpwuid(id);
4750         if (!passwd)
4751                 return -ENOENT;
4752         *name = passwd->pw_name;
4753
4754         return 0;
4755 }
4756
4757 static inline int gid2name(char **name, unsigned int id)
4758 {
4759         struct group *group;
4760
4761         group = getgrgid(id);
4762         if (!group)
4763                 return -ENOENT;
4764         *name = group->gr_name;
4765
4766         return 0;
4767 }
4768
4769 static int name2layout(__u32 *layout, char *name)
4770 {
4771         char *ptr, *layout_name;
4772
4773         *layout = 0;
4774         for (ptr = name; ; ptr = NULL) {
4775                 layout_name = strtok(ptr, ",");
4776                 if (!layout_name)
4777                         break;
4778                 if (strcmp(layout_name, "released") == 0)
4779                         *layout |= LOV_PATTERN_F_RELEASED;
4780                 else if (strcmp(layout_name, "raid0") == 0)
4781                         *layout |= LOV_PATTERN_RAID0;
4782                 else if (strcmp(layout_name, "mdt") == 0)
4783                         *layout |= LOV_PATTERN_MDT;
4784                 else if (strcmp(layout_name, "overstriping") == 0)
4785                         *layout |= LOV_PATTERN_OVERSTRIPING;
4786                 else
4787                         return -1;
4788         }
4789         return 0;
4790 }
4791
4792 static int parse_symbolic(const char *input, mode_t *outmode, const char **end)
4793 {
4794         int loop;
4795         int user, group, other;
4796         int who, all;
4797         char c, op;
4798         mode_t perm;
4799         mode_t usermask;
4800         mode_t previous_flags;
4801
4802         user = group = other = 0;
4803         all = 0;
4804         loop = 1;
4805         perm = 0;
4806         previous_flags = 0;
4807         *end = input;
4808         usermask = 0;
4809
4810         while (loop) {
4811                 switch (*input) {
4812                 case 'u':
4813                         user = 1;
4814                         break;
4815                 case 'g':
4816                         group = 1;
4817                         break;
4818                 case 'o':
4819                         other = 1;
4820                         break;
4821                 case 'a':
4822                         user = group = other = 1;
4823                         all = 1;
4824                         break;
4825                 default:
4826                         loop = 0;
4827                 }
4828
4829                 if (loop)
4830                         input++;
4831         }
4832
4833         who = user || group || other;
4834         if (!who) {
4835                 /* get the umask */
4836                 usermask = umask(0022);
4837                 umask(usermask);
4838                 usermask &= 07777;
4839         }
4840
4841         if (*input == '-' || *input == '+' || *input == '=')
4842                 op = *input++;
4843         else
4844                 /* operation is required */
4845                 return -1;
4846
4847         /* get the flags in *outmode */
4848         switch (*input) {
4849         case 'u':
4850                 previous_flags = (*outmode & 0700);
4851                 perm |= user  ? previous_flags : 0;
4852                 perm |= group ? (previous_flags >> 3) : 0;
4853                 perm |= other ? (previous_flags >> 6) : 0;
4854                 input++;
4855                 goto write_perm;
4856         case 'g':
4857                 previous_flags = (*outmode & 0070);
4858                 perm |= user  ? (previous_flags << 3) : 0;
4859                 perm |= group ? previous_flags : 0;
4860                 perm |= other ? (previous_flags >> 3) : 0;
4861                 input++;
4862                 goto write_perm;
4863         case 'o':
4864                 previous_flags = (*outmode & 0007);
4865                 perm |= user  ? (previous_flags << 6) : 0;
4866                 perm |= group ? (previous_flags << 3) : 0;
4867                 perm |= other ? previous_flags : 0;
4868                 input++;
4869                 goto write_perm;
4870         default:
4871                 break;
4872         }
4873
4874         /* this part is optional,
4875          * if empty perm = 0 and *outmode is not modified
4876          */
4877         loop = 1;
4878         while (loop) {
4879                 c = *input;
4880                 switch (c) {
4881                 case 'r':
4882                         perm |= user  ? 0400 : 0;
4883                         perm |= group ? 0040 : 0;
4884                         perm |= other ? 0004 : 0;
4885                         /* set read permission for uog except for umask's
4886                          * permissions
4887                          */
4888                         perm |= who   ? 0 : (0444 & ~usermask);
4889                         break;
4890                 case 'w':
4891                         perm |= user  ? 0200 : 0;
4892                         perm |= group ? 0020 : 0;
4893                         perm |= other ? 0002 : 0;
4894                         /* set write permission for uog except for umask'
4895                          * permissions
4896                          */
4897                         perm |= who   ? 0 : (0222 & ~usermask);
4898                         break;
4899                 case 'x':
4900                         perm |= user  ? 0100 : 0;
4901                         perm |= group ? 0010 : 0;
4902                         perm |= other ? 0001 : 0;
4903                         /* set execute permission for uog except for umask'
4904                          * permissions
4905                          */
4906                         perm |= who   ? 0 : (0111 & ~usermask);
4907                         break;
4908                 case 'X':
4909                         /*
4910                          * Adds execute permission to 'u', 'g' and/or 'g' if
4911                          * specified and either 'u', 'g' or 'o' already has
4912                          * execute permissions.
4913                          */
4914                         if ((*outmode & 0111) != 0) {
4915                                 perm |= user  ? 0100 : 0;
4916                                 perm |= group ? 0010 : 0;
4917                                 perm |= other ? 0001 : 0;
4918                                 perm |= !who  ? 0111 : 0;
4919                         }
4920                         break;
4921                 case 's':
4922                         /* s is ignored if o is given, but it's not an error */
4923                         if (other && !group && !user)
4924                                 break;
4925                         perm |= user  ? S_ISUID : 0;
4926                         perm |= group ? S_ISGID : 0;
4927                         break;
4928                 case 't':
4929                         /* 't' should be used when 'a' is given
4930                          * or who is empty
4931                          */
4932                         perm |= (!who || all) ? S_ISVTX : 0;
4933                         /* using ugo with t is not an error */
4934                         break;
4935                 default:
4936                         loop = 0;
4937                         break;
4938                 }
4939                 if (loop)
4940                         input++;
4941         }
4942
4943 write_perm:
4944         /* uog flags should be only one character long */
4945         if (previous_flags && (*input != '\0' && *input != ','))
4946                 return -1;
4947
4948         switch (op) {
4949         case '-':
4950                 /* remove the flags from outmode */
4951                 *outmode &= ~perm;
4952                 break;
4953         case '+':
4954                 /* add the flags to outmode */
4955                 *outmode |= perm;
4956                 break;
4957         case '=':
4958                 /* set the flags of outmode to perm */
4959                 if (perm != 0)
4960                         *outmode = perm;
4961                 break;
4962         }
4963
4964         *end = input;
4965         return 0;
4966 }
4967
4968 static int str2mode_t(const char *input, mode_t *outmode)
4969 {
4970         int ret;
4971         const char *iter;
4972
4973         ret = 0;
4974
4975         if (*input >= '0' && *input <= '7') {
4976                 /* parse octal representation */
4977                 char *end;
4978
4979                 iter = input;
4980
4981                 /* look for invalid digits in octal representation */
4982                 while (isdigit(*iter))
4983                         if (*iter++ > '7')
4984                                 return -1;
4985
4986                 errno = 0;
4987                 *outmode = strtoul(input, &end, 8);
4988
4989                 if (errno != 0 || *outmode > 07777) {
4990                         *outmode = 0;
4991                         ret = -1;
4992                 }
4993
4994         } else if (*input == '8' || *input == '9') {
4995                 /* error: invalid octal number */
4996                 ret = -1;
4997         } else {
4998                 /* parse coma seperated list of symbolic representation */
4999                 int rc;
5000                 const char *end;
5001
5002                 *outmode = 0;
5003                 rc = 0;
5004                 end = NULL;
5005
5006                 do {
5007                         rc = parse_symbolic(input, outmode, &end);
5008                         if (rc)
5009                                 return -1;
5010
5011                         input = end+1;
5012                 } while (*end == ',');
5013
5014                 if (*end != '\0')
5015                         ret = -1;
5016         }
5017         return ret;
5018 }
5019
5020 static int lfs_find(int argc, char **argv)
5021 {
5022         int c, rc;
5023         int ret = 0;
5024         time_t t;
5025         struct find_param param = {
5026                 .fp_max_depth = -1,
5027                 .fp_quiet = 1,
5028                 .fp_time_margin = FP_DEFAULT_TIME_MARGIN,
5029         };
5030         struct option long_opts[] = {
5031         { .val = 'A',   .name = "atime",        .has_arg = required_argument },
5032         { .val = 'b',   .name = "blocks",       .has_arg = required_argument },
5033         { .val = 'B',   .name = "btime",        .has_arg = required_argument },
5034         { .val = 'B',   .name = "Btime",        .has_arg = required_argument },
5035         { .val = LFS_COMP_COUNT_OPT,
5036                         .name = "comp-count",   .has_arg = required_argument },
5037         { .val = LFS_COMP_COUNT_OPT,
5038                         .name = "component-count",
5039                                                 .has_arg = required_argument },
5040         { .val = LFS_COMP_FLAGS_OPT,
5041                         .name = "comp-flags",   .has_arg = required_argument },
5042         { .val = LFS_COMP_FLAGS_OPT,
5043                         .name = "component-flags",
5044                                                 .has_arg = required_argument },
5045         { .val = LFS_COMP_START_OPT,
5046                         .name = "comp-start",   .has_arg = required_argument },
5047         { .val = LFS_COMP_START_OPT,
5048                         .name = "component-start",
5049                                                 .has_arg = required_argument },
5050         { .val = LFS_MIRROR_STATE_OPT,
5051                         .name = "mirror-state", .has_arg = required_argument },
5052         { .val = LFS_NEWERXY_OPT,
5053                         .name = "newer",        .has_arg = required_argument},
5054         { .val = LFS_NEWERXY_OPT,
5055                         .name = "neweraa",      .has_arg = required_argument},
5056         { .val = LFS_NEWERXY_OPT,
5057                         .name = "neweram",      .has_arg = required_argument},
5058         { .val = LFS_NEWERXY_OPT,
5059                         .name = "newerac",      .has_arg = required_argument},
5060         { .val = LFS_NEWERXY_OPT,
5061                         .name = "newerab",      .has_arg = required_argument},
5062         { .val = LFS_NEWERXY_OPT,
5063                         .name = "newerma",      .has_arg = required_argument},
5064         { .val = LFS_NEWERXY_OPT,
5065                         .name = "newermm",      .has_arg = required_argument},
5066         { .val = LFS_NEWERXY_OPT,
5067                         .name = "newermc",      .has_arg = required_argument},
5068         { .val = LFS_NEWERXY_OPT,
5069                         .name = "newermb",      .has_arg = required_argument},
5070         { .val = LFS_NEWERXY_OPT,
5071                         .name = "newerca",      .has_arg = required_argument},
5072         { .val = LFS_NEWERXY_OPT,
5073                         .name = "newercm",      .has_arg = required_argument},
5074         { .val = LFS_NEWERXY_OPT,
5075                         .name = "newercc",      .has_arg = required_argument},
5076         { .val = LFS_NEWERXY_OPT,
5077                         .name = "newercb",      .has_arg = required_argument},
5078         { .val = LFS_NEWERXY_OPT,
5079                         .name = "newerba",      .has_arg = required_argument},
5080         { .val = LFS_NEWERXY_OPT,
5081                         .name = "newerbm",      .has_arg = required_argument},
5082         { .val = LFS_NEWERXY_OPT,
5083                         .name = "newerbc",      .has_arg = required_argument},
5084         { .val = LFS_NEWERXY_OPT,
5085                         .name = "newerbb",      .has_arg = required_argument},
5086         { .val = LFS_NEWERXY_OPT,
5087                         .name = "newerBa",      .has_arg = required_argument},
5088         { .val = LFS_NEWERXY_OPT,
5089                         .name = "newerBm",      .has_arg = required_argument},
5090         { .val = LFS_NEWERXY_OPT,
5091                         .name = "newerBc",      .has_arg = required_argument},
5092         { .val = LFS_NEWERXY_OPT,
5093                         .name = "newerBB",      .has_arg = required_argument},
5094         { .val = LFS_NEWERXY_OPT,
5095                         .name = "newerat",      .has_arg = required_argument},
5096         { .val = LFS_NEWERXY_OPT,
5097                         .name = "newermt",      .has_arg = required_argument},
5098         { .val = LFS_NEWERXY_OPT,
5099                         .name = "newerct",      .has_arg = required_argument},
5100         { .val = LFS_NEWERXY_OPT,
5101                         .name = "newerbt",      .has_arg = required_argument},
5102         { .val = LFS_NEWERXY_OPT,
5103                         .name = "newerBt",      .has_arg = required_argument},
5104         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument },
5105         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument },
5106         { .val = 'C',   .name = "ctime",        .has_arg = required_argument },
5107 /* getstripe { .val = 'd', .name = "directory", .has_arg = no_argument }, */
5108         { .val = 'D',   .name = "maxdepth",     .has_arg = required_argument },
5109         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument },
5110         { .val = 'E',   .name = "component-end",
5111                                                 .has_arg = required_argument },
5112 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
5113         { .val = LFS_LAYOUT_FOREIGN_OPT,
5114                         .name = "foreign",      .has_arg = optional_argument},
5115         { .val = 'g',   .name = "gid",          .has_arg = required_argument },
5116         { .val = 'G',   .name = "group",        .has_arg = required_argument },
5117         { .val = 'h',   .name = "help",         .has_arg = no_argument },
5118         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
5119         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument },
5120         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument },
5121 /* getstripe { .val = 'I', .name = "comp-id",   .has_arg = required_argument }*/
5122         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
5123         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
5124         { .val = LFS_LINKS_OPT,
5125                         .name = "links",        .has_arg = required_argument },
5126         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
5127         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
5128         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument },
5129         { .val = 'M',   .name = "mtime",        .has_arg = required_argument },
5130         { .val = 'n',   .name = "name",         .has_arg = required_argument },
5131         { .val = 'N',   .name = "mirror-count", .has_arg = required_argument },
5132 /* find { .val = 'o'    .name = "or", .has_arg = no_argument }, like find(1) */
5133         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
5134         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
5135         { .val = LFS_FIND_PERM,
5136                         .name = "perm",         .has_arg = required_argument },
5137         /* no short option for pool yet, can be 'p' after 2.18 */
5138         { .val = LFS_POOL_OPT,
5139                         .name = "pool",         .has_arg = required_argument },
5140         { .val = '0',   .name = "print0",       .has_arg = no_argument },
5141         { .val = 'P',   .name = "print",        .has_arg = no_argument },
5142         { .val = LFS_PRINTF_OPT,
5143                         .name = "printf",       .has_arg = required_argument },
5144         { .val = LFS_PROJID_OPT,
5145                         .name = "projid",       .has_arg = required_argument },
5146 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
5147 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
5148 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
5149         { .val = 's',   .name = "size",         .has_arg = required_argument },
5150         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
5151         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
5152         { .val = 't',   .name = "type",         .has_arg = required_argument },
5153         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
5154         { .val = 'u',   .name = "uid",          .has_arg = required_argument },
5155         { .val = 'U',   .name = "user",         .has_arg = required_argument },
5156 /* getstripe { .val = 'v', .name = "verbose",   .has_arg = no_argument }, */
5157 /* setstripe { .val = 'W', .name = "bandwidth", .has_arg = required_argument }, */
5158         { .val = 'z',   .name = "extension-size",
5159                                                 .has_arg = required_argument },
5160         { .val = 'z',   .name = "ext-size",     .has_arg = required_argument },
5161         { .name = NULL } };
5162         int prev_optind = optind;
5163         int optidx = 0;
5164         int pathstart = -1;
5165         int pathend = -1;
5166         int pathbad = -1;
5167         int neg_opt = 0;
5168         time_t *xtime;
5169         int *xsign;
5170         int isoption;
5171         char *endptr;
5172
5173         time(&t);
5174
5175         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
5176         while ((c = getopt_long_only(argc, argv,
5177                 "-0A:b:B:c:C:D:E:g:G:hH:i:lL:m:M:n:N:O:Ppqrs:S:t:T:u:U:z:",
5178                 long_opts, &optidx)) >= 0) {
5179                 xtime = NULL;
5180                 xsign = NULL;
5181                 if (neg_opt)
5182                         --neg_opt;
5183                 /* '!' is part of option */
5184                 /*
5185                  * when getopt_long_only() finds a string which is not
5186                  * an option nor a known option argument it returns 1
5187                  * in that case if we already have found pathstart and pathend
5188                  * (i.e. we have the list of pathnames),
5189                  * the only supported value is "!"
5190                  */
5191                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
5192                 if (!isoption && pathend != -1) {
5193                         fprintf(stderr,
5194                                 "err: %s: filename|dirname must either precede options or follow options\n",
5195                                 argv[0]);
5196                         ret = CMD_HELP;
5197                         goto err;
5198                 }
5199                 if (!isoption && pathstart == -1)
5200                         pathstart = prev_optind;
5201                 if (isoption && pathstart != -1 && pathend == -1)
5202                         pathend = prev_optind;
5203
5204                 prev_optind = optind;
5205
5206                 switch (c) {
5207                 case 0:
5208                         /* Long options. */
5209                         break;
5210                 case 1:
5211                         /*
5212                          * unknown; opt is "!" or path component,
5213                          * checking done above.
5214                          */
5215                         if (strcmp(optarg, "!") == 0)
5216                                 neg_opt = 2;
5217                         break;
5218                 case 'A':
5219                         xtime = &param.fp_atime;
5220                         xsign = &param.fp_asign;
5221                         param.fp_exclude_atime = !!neg_opt;
5222                         /* no break, this falls through to 'B' for btime */
5223                         fallthrough;
5224                 case 'B':
5225                         if (c == 'B') {
5226                                 xtime = &param.fp_btime;
5227                                 xsign = &param.fp_bsign;
5228                                 param.fp_exclude_btime = !!neg_opt;
5229                         }
5230                         /* no break, this falls through to 'C' for ctime */
5231                         fallthrough;
5232                 case 'C':
5233                         if (c == 'C') {
5234                                 xtime = &param.fp_ctime;
5235                                 xsign = &param.fp_csign;
5236                                 param.fp_exclude_ctime = !!neg_opt;
5237                         }
5238                         /* no break, this falls through to 'M' for mtime */
5239                         fallthrough;
5240                 case 'M':
5241                         if (c == 'M') {
5242                                 xtime = &param.fp_mtime;
5243                                 xsign = &param.fp_msign;
5244                                 param.fp_exclude_mtime = !!neg_opt;
5245                         }
5246                         rc = set_time(&param, &t, xtime, optarg);
5247                         if (rc == INT_MAX) {
5248                                 ret = -1;
5249                                 goto err;
5250                         }
5251                         if (rc)
5252                                 *xsign = rc;
5253                         break;
5254                 case 'b':
5255                         if (optarg[0] == '+') {
5256                                 param.fp_blocks_sign = -1;
5257                                 optarg++;
5258                         } else if (optarg[0] == '-') {
5259                                 param.fp_blocks_sign =  1;
5260                                 optarg++;
5261                         }
5262
5263                         param.fp_blocks_units = 1024;
5264                         ret = llapi_parse_size(optarg, &param.fp_blocks,
5265                                                &param.fp_blocks_units, 0);
5266                         if (ret) {
5267                                 fprintf(stderr, "error: bad blocks '%s'\n",
5268                                         optarg);
5269                                 goto err;
5270                         }
5271                         param.fp_check_blocks = 1;
5272                         param.fp_exclude_blocks = !!neg_opt;
5273                         break;
5274                 case LFS_COMP_COUNT_OPT:
5275                         if (optarg[0] == '+') {
5276                                 param.fp_comp_count_sign = -1;
5277                                 optarg++;
5278                         } else if (optarg[0] == '-') {
5279                                 param.fp_comp_count_sign =  1;
5280                                 optarg++;
5281                         }
5282
5283                         errno = 0;
5284                         param.fp_comp_count = strtoul(optarg, &endptr, 0);
5285                         if (errno != 0 || *endptr != '\0' ||
5286                             param.fp_comp_count > UINT32_MAX) {
5287                                 fprintf(stderr,
5288                                         "error: bad component count '%s'\n",
5289                                         optarg);
5290                                 goto err;
5291                         }
5292                         param.fp_check_comp_count = 1;
5293                         param.fp_exclude_comp_count = !!neg_opt;
5294                         break;
5295                 case LFS_COMP_FLAGS_OPT:
5296                         rc = comp_str2flags(optarg, &param.fp_comp_flags,
5297                                             &param.fp_comp_neg_flags);
5298                         if (rc) {
5299                                 fprintf(stderr,
5300                                         "error: bad component flags '%s'\n",
5301                                         optarg);
5302                                 goto err;
5303                         }
5304                         param.fp_check_comp_flags = 1;
5305                         if (neg_opt) {
5306                                 __u32 flags = param.fp_comp_neg_flags;
5307
5308                                 param.fp_comp_neg_flags = param.fp_comp_flags;
5309                                 param.fp_comp_flags = flags;
5310                         }
5311                         break;
5312                 case LFS_COMP_START_OPT:
5313                         if (optarg[0] == '+') {
5314                                 param.fp_comp_start_sign = -1;
5315                                 optarg++;
5316                         } else if (optarg[0] == '-') {
5317                                 param.fp_comp_start_sign =  1;
5318                                 optarg++;
5319                         }
5320
5321                         rc = llapi_parse_size(optarg, &param.fp_comp_start,
5322                                               &param.fp_comp_start_units, 0);
5323                         if (rc) {
5324                                 fprintf(stderr,
5325                                         "error: bad component start '%s'\n",
5326                                         optarg);
5327                                 goto err;
5328                         }
5329                         param.fp_check_comp_start = 1;
5330                         param.fp_exclude_comp_start = !!neg_opt;
5331                         break;
5332                 case LFS_MIRROR_STATE_OPT:
5333                         rc = mirror_str2state(optarg, &param.fp_mirror_state,
5334                                               &param.fp_mirror_neg_state);
5335                         if (rc) {
5336                                 fprintf(stderr,
5337                                         "error: bad mirrored file state '%s'\n",
5338                                         optarg);
5339                                 goto err;
5340                         }
5341                         param.fp_check_mirror_state = 1;
5342                         if (neg_opt) {
5343                                 __u16 state = param.fp_mirror_neg_state;
5344
5345                                 param.fp_mirror_neg_state =
5346                                         param.fp_mirror_state;
5347                                 param.fp_mirror_state = state;
5348                         }
5349                         break;
5350                 case 'c':
5351                         if (optarg[0] == '+') {
5352                                 param.fp_stripe_count_sign = -1;
5353                                 optarg++;
5354                         } else if (optarg[0] == '-') {
5355                                 param.fp_stripe_count_sign =  1;
5356                                 optarg++;
5357                         }
5358
5359                         errno = 0;
5360                         param.fp_stripe_count = strtoul(optarg, &endptr, 0);
5361                         if (errno != 0 || *endptr != '\0' ||
5362                             param.fp_stripe_count > LOV_MAX_STRIPE_COUNT) {
5363                                 fprintf(stderr,
5364                                         "error: bad stripe_count '%s'\n",
5365                                         optarg);
5366                                 ret = -1;
5367                                 goto err;
5368                         }
5369                         param.fp_check_stripe_count = 1;
5370                         param.fp_exclude_stripe_count = !!neg_opt;
5371                         break;
5372                 case 'D':
5373                         errno = 0;
5374                         param.fp_max_depth = strtol(optarg, 0, 0);
5375                         if (errno != 0 || param.fp_max_depth < 0) {
5376                                 fprintf(stderr,
5377                                         "error: bad maxdepth '%s'\n",
5378                                         optarg);
5379                                 ret = -1;
5380                                 goto err;
5381                         }
5382                         break;
5383                 case 'E':
5384                         if (optarg[0] == '+') {
5385                                 param.fp_comp_end_sign = -1;
5386                                 optarg++;
5387                         } else if (optarg[0] == '-') {
5388                                 param.fp_comp_end_sign =  1;
5389                                 optarg++;
5390                         }
5391
5392                         if (arg_is_eof(optarg)) {
5393                                 param.fp_comp_end = LUSTRE_EOF;
5394                                 param.fp_comp_end_units = 1;
5395                                 rc = 0;
5396                         } else {
5397                                 rc = llapi_parse_size(optarg,
5398                                                 &param.fp_comp_end,
5399                                                 &param.fp_comp_end_units, 0);
5400                                 /* assume units of KB if too small */
5401                                 if (param.fp_comp_end < 4096)
5402                                         param.fp_comp_end *= 1024;
5403                         }
5404                         if (rc) {
5405                                 fprintf(stderr,
5406                                         "error: bad component end '%s'\n",
5407                                         optarg);
5408                                 goto err;
5409                         }
5410                         param.fp_check_comp_end = 1;
5411                         param.fp_exclude_comp_end = !!neg_opt;
5412                         break;
5413                 case LFS_LAYOUT_FOREIGN_OPT: {
5414                         /* all types by default */
5415                         uint32_t type = LU_FOREIGN_TYPE_UNKNOWN;
5416
5417                         if (optarg) {
5418                                 /* check pure numeric */
5419                                 type = strtoul(optarg, &endptr, 0);
5420                                 if (*endptr) {
5421                                         /* check name */
5422                                         type = check_foreign_type_name(optarg);
5423                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
5424                                                 fprintf(stderr,
5425                                                         "%s %s: unknown foreign type '%s'\n",
5426                                                         progname, argv[0],
5427                                                         optarg);
5428                                                 return CMD_HELP;
5429                                         }
5430                                 } else if (type >= UINT32_MAX) {
5431                                         fprintf(stderr,
5432                                                 "%s %s: invalid foreign type '%s'\n",
5433                                                 progname, argv[0], optarg);
5434                                         return CMD_HELP;
5435                                 }
5436                         }
5437                         param.fp_foreign_type = type;
5438                         param.fp_check_foreign = 1;
5439                         param.fp_exclude_foreign = !!neg_opt;
5440                         break;
5441                 }
5442                 case LFS_NEWERXY_OPT: {
5443                         char x = 'm';
5444                         char y = 'm';
5445                         int xidx;
5446                         int negidx;
5447                         time_t *newery;
5448                         time_t ref = time(NULL);
5449
5450                         /* no need to check bad options, they won't get here */
5451                         if (strlen(long_opts[optidx].name) == 7) {
5452                                 x = long_opts[optidx].name[5];
5453                                 y = long_opts[optidx].name[6];
5454                         }
5455
5456                         if (y == 't') {
5457                                 static const char *const fmts[] = {
5458                                         "%Y-%m-%d %H:%M:%S",
5459                                         "%Y-%m-%d %H:%M",
5460                                         "%Y-%m-%d",
5461                                         "%H:%M:%S", /* sometime today */
5462                                         "%H:%M",
5463                                         "@%s",
5464                                         "%s",
5465                                         NULL };
5466                                 struct tm tm;
5467                                 bool found = false;
5468                                 int i;
5469
5470                                 for (i = 0; fmts[i] != NULL; i++) {
5471                                         char *ptr;
5472
5473                                         /* Init for times relative to today */
5474                                         if (strncmp(fmts[i], "%H", 2) == 0) {
5475                                                 localtime_r(&ref, &tm);
5476                                         } else {
5477                                                 memset(&tm, 0, sizeof(tm));
5478                                                 tm.tm_isdst = -1;
5479                                         }
5480                                         ptr = strptime(optarg, fmts[i], &tm);
5481                                         /* Skip spaces */
5482                                         while (ptr && isspace(*ptr))
5483                                                 ptr++;
5484                                         if (ptr == optarg + strlen(optarg)) {
5485                                                 found = true;
5486                                                 break;
5487                                         }
5488                                 }
5489
5490                                 if (!found) {
5491                                         fprintf(stderr,
5492                                                 "%s: invalid time '%s'\n",
5493                                                 progname, optarg);
5494                                         fprintf(stderr,
5495                                                 "supported formats are:\n  ");
5496                                         for (i = 0; fmts[i] != NULL; i++)
5497                                                 fprintf(stderr, "'%s', ",
5498                                                         fmts[i]);
5499                                         fprintf(stderr, "\n");
5500                                         ret = -EINVAL;
5501                                         goto err;
5502                                 }
5503
5504                                 ref = mktime(&tm);
5505                         } else if (y == 'b' || y == 'B') {
5506                                 lstatx_t stx;
5507
5508                                 rc = llapi_get_lum_file(optarg, NULL, &stx,
5509                                                         NULL, 0);
5510                                 if (rc || !(stx.stx_mask & STATX_BTIME)) {
5511                                         if (!(stx.stx_mask & STATX_BTIME))
5512                                                 ret = -EOPNOTSUPP;
5513                                         else
5514                                                 ret = -errno;
5515                                         fprintf(stderr,
5516                                                 "%s: get btime failed '%s': %s\n",
5517                                                 progname, optarg,
5518                                                 strerror(-ret));
5519                                         goto err;
5520                                 }
5521
5522                                 ref = stx.stx_btime.tv_sec;
5523                         } else {
5524                                 struct stat statbuf;
5525
5526                                 if (stat(optarg, &statbuf) < 0) {
5527                                         fprintf(stderr,
5528                                                 "%s: cannot stat file '%s': %s\n",
5529                                                 progname, optarg,
5530                                                 strerror(errno));
5531                                         ret = -errno;
5532                                         goto err;
5533                                 }
5534
5535                                 switch (y) {
5536                                 case 'a':
5537                                         ref = statbuf.st_atime;
5538                                         break;
5539                                 case 'm':
5540                                         ref = statbuf.st_mtime;
5541                                         break;
5542                                 case 'c':
5543                                         ref = statbuf.st_ctime;
5544                                         break;
5545                                 default:
5546                                         fprintf(stderr,
5547                                                 "%s: invalid Y argument: '%c'\n",
5548                                                 progname, x);
5549                                         ret = -EINVAL;
5550                                         goto err;
5551                                 }
5552                         }
5553
5554                         switch (x) {
5555                         case 'a':
5556                                 xidx = NEWERXY_ATIME;
5557                                 break;
5558                         case 'm':
5559                                 xidx = NEWERXY_MTIME;
5560                                 break;
5561                         case 'c':
5562                                 xidx = NEWERXY_CTIME;
5563                                 break;
5564                         case 'b':
5565                         case 'B':
5566                                 xidx = NEWERXY_BTIME;
5567                                 break;
5568                         default:
5569                                 fprintf(stderr,
5570                                         "%s: invalid X argument: '%c'\n",
5571                                         progname, x);
5572                                 ret = -EINVAL;
5573                                 goto err;
5574                         }
5575
5576                         negidx = !!neg_opt;
5577                         newery = &param.fp_newery[xidx][negidx];
5578
5579                         if (*newery == 0) {
5580                                 *newery = ref;
5581                         } else {
5582                                 if (negidx)
5583                                         *newery = *newery > ref ? ref : *newery;
5584                                 else
5585                                         *newery = *newery > ref ? *newery : ref;
5586                         }
5587                         param.fp_newerxy = 1;
5588                         break;
5589                 }
5590                 case 'g':
5591                 case 'G':
5592                         rc = name2gid(&param.fp_gid, optarg);
5593                         if (rc) {
5594                                 if (str2quotaid(&param.fp_gid, optarg)) {
5595                                         fprintf(stderr,
5596                                                 "Group/GID: %s cannot be found.\n",
5597                                                 optarg);
5598                                         ret = -1;
5599                                         goto err;
5600                                 }
5601                         }
5602                         param.fp_exclude_gid = !!neg_opt;
5603                         param.fp_check_gid = 1;
5604                         break;
5605                 case 'H':
5606                         rc = mdthash_input(optarg, &param.fp_hash_inflags,
5607                                            &param.fp_hash_exflags,
5608                                            &param.fp_hash_type);
5609                         if (rc) {
5610                                 ret = -1;
5611                                 goto err;
5612                         }
5613                         if (param.fp_hash_inflags || param.fp_hash_exflags)
5614                                 param.fp_check_hash_flag = 1;
5615                         param.fp_exclude_hash_type = !!neg_opt;
5616                         break;
5617                 case 'l':
5618                         param.fp_lazy = 1;
5619                         break;
5620                 case 'L':
5621                         ret = name2layout(&param.fp_layout, optarg);
5622                         if (ret)
5623                                 goto err;
5624                         param.fp_exclude_layout = !!neg_opt;
5625                         param.fp_check_layout = 1;
5626                         break;
5627                 case LFS_LINKS_OPT:
5628                         if (optarg[0] == '+') {
5629                                 param.fp_nlink_sign = -1;
5630                                 optarg++;
5631                         } else if (optarg[0] == '-') {
5632                                 param.fp_nlink_sign =  1;
5633                                 optarg++;
5634                         }
5635                         errno = 0;
5636                         param.fp_nlink = strtoul(optarg, &endptr, 0);
5637                         if (errno != 0 || *endptr != '\0' || !param.fp_nlink) {
5638                                 fprintf(stderr, "error: bad link count '%s'\n",
5639                                         optarg);
5640                                 ret = -1;
5641                                 goto err;
5642                         }
5643                         param.fp_exclude_nlink = !!neg_opt;
5644                         break;
5645                 case 'u':
5646                 case 'U':
5647                         rc = name2uid(&param.fp_uid, optarg);
5648                         if (rc) {
5649                                 if (str2quotaid(&param.fp_uid, optarg)) {
5650                                         fprintf(stderr,
5651                                                 "User/UID: %s cannot be found.\n",
5652                                                 optarg);
5653                                         ret = -1;
5654                                         goto err;
5655                                 }
5656                         }
5657                         param.fp_exclude_uid = !!neg_opt;
5658                         param.fp_check_uid = 1;
5659                         break;
5660                 case 'n':
5661                         param.fp_pattern = (char *)optarg;
5662                         param.fp_exclude_pattern = !!neg_opt;
5663                         break;
5664                 case 'N':
5665                         if (optarg[0] == '+') {
5666                                 param.fp_mirror_count_sign = -1;
5667                                 optarg++;
5668                         } else if (optarg[0] == '-') {
5669                                 param.fp_mirror_count_sign =  1;
5670                                 optarg++;
5671                         }
5672
5673                         errno = 0;
5674                         param.fp_mirror_count = strtoul(optarg, &endptr, 0);
5675                         if (errno != 0 || *endptr != '\0' ||
5676                             param.fp_mirror_count > LUSTRE_MIRROR_COUNT_MAX) {
5677                                 fprintf(stderr,
5678                                         "error: bad mirror count '%s'\n",
5679                                         optarg);
5680                                 goto err;
5681                         }
5682                         param.fp_check_mirror_count = 1;
5683                         param.fp_exclude_mirror_count = !!neg_opt;
5684                         break;
5685                 case 'm':
5686                 case 'i':
5687                 case 'O': {
5688                         char *buf, *token, *next, *p;
5689                         int len = 1;
5690                         void *tmp;
5691
5692                         buf = strdup(optarg);
5693                         if (!buf) {
5694                                 ret = -ENOMEM;
5695                                 goto err;
5696                         }
5697
5698                         param.fp_exclude_obd = !!neg_opt;
5699
5700                         token = buf;
5701                         while (token && *token) {
5702                                 token = strchr(token, ',');
5703                                 if (token) {
5704                                         len++;
5705                                         token++;
5706                                 }
5707                         }
5708                         if (c == 'm') {
5709                                 param.fp_exclude_mdt = !!neg_opt;
5710                                 param.fp_num_alloc_mdts += len;
5711                                 tmp = realloc(param.fp_mdt_uuid,
5712                                               param.fp_num_alloc_mdts *
5713                                               sizeof(*param.fp_mdt_uuid));
5714                                 if (!tmp) {
5715                                         ret = -ENOMEM;
5716                                         goto err_free;
5717                                 }
5718
5719                                 param.fp_mdt_uuid = tmp;
5720                         } else {
5721                                 param.fp_exclude_obd = !!neg_opt;
5722                                 param.fp_num_alloc_obds += len;
5723                                 tmp = realloc(param.fp_obd_uuid,
5724                                               param.fp_num_alloc_obds *
5725                                               sizeof(*param.fp_obd_uuid));
5726                                 if (!tmp) {
5727                                         ret = -ENOMEM;
5728                                         goto err_free;
5729                                 }
5730
5731                                 param.fp_obd_uuid = tmp;
5732                         }
5733                         for (token = buf; token && *token; token = next) {
5734                                 struct obd_uuid *puuid;
5735
5736                                 if (c == 'm') {
5737                                         puuid =
5738                                         &param.fp_mdt_uuid[param.fp_num_mdts++];
5739                                 } else {
5740                                         puuid =
5741                                         &param.fp_obd_uuid[param.fp_num_obds++];
5742                                 }
5743                                 p = strchr(token, ',');
5744                                 next = 0;
5745                                 if (p) {
5746                                         *p = 0;
5747                                         next = p+1;
5748                                 }
5749
5750                                 if (strlen(token) > sizeof(puuid->uuid) - 1) {
5751                                         ret = -E2BIG;
5752                                         goto err_free;
5753                                 }
5754
5755                                 strncpy(puuid->uuid, token,
5756                                         sizeof(puuid->uuid));
5757                         }
5758 err_free:
5759                         if (buf)
5760                                 free(buf);
5761                         break;
5762                 }
5763 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 18, 53, 0)
5764                 case 'p':
5765 #endif
5766                 case LFS_POOL_OPT:
5767                         if (strlen(optarg) > LOV_MAXPOOLNAME) {
5768                                 fprintf(stderr,
5769                                         "Pool name %s is too long (max %d)\n",
5770                                         optarg, LOV_MAXPOOLNAME);
5771                                 ret = -1;
5772                                 goto err;
5773                         }
5774                         /*
5775                          * We do check for empty pool because empty pool
5776                          * is used to find V1 LOV attributes
5777                          */
5778                         strncpy(param.fp_poolname, optarg, LOV_MAXPOOLNAME);
5779                         param.fp_poolname[LOV_MAXPOOLNAME] = '\0';
5780                         param.fp_exclude_pool = !!neg_opt;
5781                         param.fp_check_pool = 1;
5782                         break;
5783                 case '0':
5784                         param.fp_zero_end = 1;
5785                         break;
5786                 case 'P': /* we always print, this option is a no-op */
5787                         break;
5788                 case LFS_PRINTF_OPT:
5789                         param.fp_format_printf_str = strdup(optarg);
5790                         break;
5791                 case LFS_PROJID_OPT:
5792                         rc = name2projid(&param.fp_projid, optarg);
5793                         if (rc) {
5794                                 if (str2quotaid(&param.fp_projid, optarg)) {
5795                                         fprintf(stderr,
5796                                                 "Invalid project ID: %s\n",
5797                                                 optarg);
5798                                         ret = -1;
5799                                         goto err;
5800                                 }
5801                         }
5802                         param.fp_exclude_projid = !!neg_opt;
5803                         param.fp_check_projid = 1;
5804                         break;
5805                 case 's':
5806                         if (optarg[0] == '+') {
5807                                 param.fp_size_sign = -1;
5808                                 optarg++;
5809                         } else if (optarg[0] == '-') {
5810                                 param.fp_size_sign =  1;
5811                                 optarg++;
5812                         }
5813
5814                         ret = llapi_parse_size(optarg, &param.fp_size,
5815                                                &param.fp_size_units, 0);
5816                         if (ret) {
5817                                 fprintf(stderr, "error: bad file size '%s'\n",
5818                                         optarg);
5819                                 goto err;
5820                         }
5821                         param.fp_check_size = 1;
5822                         param.fp_exclude_size = !!neg_opt;
5823                         break;
5824                 case 'S':
5825                         if (optarg[0] == '+') {
5826                                 param.fp_stripe_size_sign = -1;
5827                                 optarg++;
5828                         } else if (optarg[0] == '-') {
5829                                 param.fp_stripe_size_sign =  1;
5830                                 optarg++;
5831                         }
5832
5833                         ret = llapi_parse_size(optarg, &param.fp_stripe_size,
5834                                                &param.fp_stripe_size_units, 0);
5835                         /* assume units of KB if too small to be valid */
5836                         if (param.fp_stripe_size < 4096)
5837                                 param.fp_stripe_size *= 1024;
5838                         if (ret) {
5839                                 fprintf(stderr, "error: bad stripe_size '%s'\n",
5840                                         optarg);
5841                                 goto err;
5842                         }
5843                         param.fp_check_stripe_size = 1;
5844                         param.fp_exclude_stripe_size = !!neg_opt;
5845                         break;
5846                 case 't':
5847                         param.fp_exclude_type = !!neg_opt;
5848                         switch (optarg[0]) {
5849                         case 'b':
5850                                 param.fp_type = S_IFBLK;
5851                                 break;
5852                         case 'c':
5853                                 param.fp_type = S_IFCHR;
5854                                 break;
5855                         case 'd':
5856                                 param.fp_type = S_IFDIR;
5857                                 break;
5858                         case 'f':
5859                                 param.fp_type = S_IFREG;
5860                                 break;
5861                         case 'l':
5862                                 param.fp_type = S_IFLNK;
5863                                 break;
5864                         case 'p':
5865                                 param.fp_type = S_IFIFO;
5866                                 break;
5867                         case 's':
5868                                 param.fp_type = S_IFSOCK;
5869                                 break;
5870                         default:
5871                                 fprintf(stderr, "%s: bad type '%s'\n",
5872                                         progname, optarg);
5873                                 ret = CMD_HELP;
5874                                 goto err;
5875                         }
5876                         break;
5877                 case LFS_FIND_PERM:
5878                         param.fp_exclude_perm = !!neg_opt;
5879                         param.fp_perm_sign = LFS_FIND_PERM_EXACT;
5880                         if (*optarg == '/') {
5881                                 param.fp_perm_sign = LFS_FIND_PERM_ANY;
5882                                 optarg++;
5883                         } else if (*optarg == '-') {
5884                                 param.fp_perm_sign = LFS_FIND_PERM_ALL;
5885                                 optarg++;
5886                         }
5887
5888                         if (str2mode_t(optarg, &param.fp_perm)) {
5889                                 fprintf(stderr, "error: invalid mode '%s'\n",
5890                                         optarg);
5891                                 ret = -1;
5892                                 goto err;
5893                         }
5894                         break;
5895                 case 'T':
5896                         if (optarg[0] == '+') {
5897                                 param.fp_mdt_count_sign = -1;
5898                                 optarg++;
5899                         } else if (optarg[0] == '-') {
5900                                 param.fp_mdt_count_sign =  1;
5901                                 optarg++;
5902                         }
5903
5904                         errno = 0;
5905                         param.fp_mdt_count = strtoul(optarg, &endptr, 0);
5906                         if (errno != 0 || *endptr != '\0' ||
5907                             param.fp_mdt_count >= UINT32_MAX) {
5908                                 fprintf(stderr, "error: bad mdt_count '%s'\n",
5909                                         optarg);
5910                                 ret = -1;
5911                                 goto err;
5912                         }
5913                         param.fp_check_mdt_count = 1;
5914                         param.fp_exclude_mdt_count = !!neg_opt;
5915                         break;
5916                 case 'z':
5917                         if (optarg[0] == '+') {
5918                                 param.fp_ext_size_sign = -1;
5919                                 optarg++;
5920                         } else if (optarg[0] == '-') {
5921                                 param.fp_ext_size_sign =  1;
5922                                 optarg++;
5923                         }
5924
5925                         ret = llapi_parse_size(optarg, &param.fp_ext_size,
5926                                                &param.fp_ext_size_units, 0);
5927                         if (ret) {
5928                                 fprintf(stderr, "error: bad ext-size '%s'\n",
5929                                         optarg);
5930                                 goto err;
5931                         }
5932                         param.fp_ext_size /= SEL_UNIT_SIZE;
5933                         param.fp_ext_size_units /= SEL_UNIT_SIZE;
5934                         param.fp_check_ext_size = 1;
5935                         param.fp_exclude_ext_size = !!neg_opt;
5936                         break;
5937                 default:
5938                         fprintf(stderr, "%s: unrecognized option '%s'\n",
5939                                 progname, argv[optind - 1]);
5940                 case 'h':
5941                         ret = CMD_HELP;
5942                         goto err;
5943                 }
5944         }
5945         if (!param.fp_verbose)
5946                 param.fp_verbose = VERBOSE_DEFAULT;
5947
5948         if (pathstart == -1) {
5949                 fprintf(stderr, "error: %s: no filename|pathname\n",
5950                         argv[0]);
5951                 ret = CMD_HELP;
5952                 goto err;
5953         } else if (pathend == -1) {
5954                 /* no options */
5955                 pathend = argc;
5956         }
5957
5958         do {
5959                 rc = llapi_find(argv[pathstart], &param);
5960                 if (rc && !ret) {
5961                         ret = rc;
5962                         pathbad = pathstart;
5963                 }
5964         } while (++pathstart < pathend);
5965
5966         if (ret)
5967                 fprintf(stderr, "%s: failed for '%s': %s\n",
5968                         progname, argv[pathbad], strerror(-rc));
5969
5970 err:
5971         if (param.fp_obd_uuid && param.fp_num_alloc_obds)
5972                 free(param.fp_obd_uuid);
5973
5974         if (param.fp_mdt_uuid && param.fp_num_alloc_mdts)
5975                 free(param.fp_mdt_uuid);
5976
5977         if (param.fp_format_printf_str)
5978                 free(param.fp_format_printf_str);
5979
5980         return ret;
5981 }
5982
5983 static int lfs_getstripe_internal(int argc, char **argv,
5984                                   struct find_param *param)
5985 {
5986         struct option long_opts[] = {
5987 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
5988 /* find { .val = 'b',   .name = "blocks",       .has_arg = required_argument }*/
5989 /* find { .val = 'B',   .name = "btime",        .has_arg = required_argument }*/
5990 /* find { .val = 'B',   .name = "Btime",        .has_arg = required_argument }*/
5991         { .val = LFS_COMP_COUNT_OPT,
5992                         .name = "comp-count",   .has_arg = no_argument },
5993         { .val = LFS_COMP_COUNT_OPT,
5994                 .name = "component-count",      .has_arg = no_argument },
5995         { .val = LFS_COMP_FLAGS_OPT,
5996                         .name = "comp-flags",   .has_arg = optional_argument },
5997         { .val = LFS_COMP_FLAGS_OPT,
5998                 .name = "component-flags",      .has_arg = optional_argument },
5999         { .val = LFS_COMP_START_OPT,
6000                         .name = "comp-start",   .has_arg = optional_argument },
6001         { .val = LFS_COMP_START_OPT,
6002                 .name = "component-start",      .has_arg = optional_argument },
6003         { .val = 'c',   .name = "stripe-count", .has_arg = no_argument },
6004         { .val = 'c',   .name = "stripe_count", .has_arg = no_argument },
6005 /* find { .val = 'C',   .name = "ctime",        .has_arg = required_argument }*/
6006         { .val = 'd',   .name = "directory",    .has_arg = no_argument },
6007         { .val = 'D',   .name = "default",      .has_arg = no_argument },
6008         { .val = 'E',   .name = "comp-end",     .has_arg = optional_argument },
6009         { .val = 'E',   .name = "component-end", .has_arg = optional_argument },
6010         { .val = 'F',   .name = "fid",          .has_arg = no_argument },
6011         { .val = 'g',   .name = "generation",   .has_arg = no_argument },
6012 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
6013         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6014         { .val = LFS_HEX_IDX_OPT,
6015                         .name = "hex-idx",      .has_arg = no_argument },
6016 /* dirstripe { .val = 'H', .name = "mdt-hash",  .has_arg = required_argument }*/
6017         { .val = 'i',   .name = "stripe-index", .has_arg = no_argument },
6018         { .val = 'i',   .name = "stripe_index", .has_arg = no_argument },
6019         { .val = 'I',   .name = "comp-id",      .has_arg = optional_argument },
6020         { .val = 'I',   .name = "component-id", .has_arg = optional_argument },
6021 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
6022         { .val = 'L',   .name = "layout",       .has_arg = no_argument },
6023         { .val = 'm',   .name = "mdt",          .has_arg = no_argument },
6024         { .val = 'm',   .name = "mdt-index",    .has_arg = no_argument },
6025         { .val = 'm',   .name = "mdt_index",    .has_arg = no_argument },
6026 /* find { .val = 'M',   .name = "mtime",        .has_arg = required_argument }*/
6027 /* find { .val = 'n',   .name = "name",         .has_arg = required_argument }*/
6028         { .val = 'N',   .name = "mirror-count", .has_arg = no_argument },
6029         { .val = LFS_MIRROR_INDEX_OPT,
6030                         .name = "mirror-index", .has_arg = required_argument },
6031         { .val = LFS_MIRROR_ID_OPT,
6032                         .name = "mirror-id",    .has_arg = required_argument },
6033         { .val = LFS_NO_FOLLOW_OPT,
6034                         .name = "no-follow",    .has_arg = no_argument },
6035         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
6036         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
6037         { .val = 'p',   .name = "pool",         .has_arg = no_argument },
6038 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
6039         { .val = 'q',   .name = "quiet",        .has_arg = no_argument },
6040         { .val = 'r',   .name = "recursive",    .has_arg = no_argument },
6041         { .val = 'R',   .name = "raw",          .has_arg = no_argument },
6042         { .val = 'S',   .name = "stripe-size",  .has_arg = no_argument },
6043         { .val = 'S',   .name = "stripe_size",  .has_arg = no_argument },
6044 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
6045 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
6046 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
6047 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
6048         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
6049 /* dirstripe { .val = 'X',.name = "max-inherit",.has_arg = required_argument }*/
6050 /* setstripe { .val = 'W', .name = "bandwidth", .has_arg = required_argument }*/
6051         { .val = 'y',   .name = "yaml",         .has_arg = no_argument },
6052         { .val = 'z',   .name = "extension-size", .has_arg = no_argument },
6053         { .val = 'z',   .name = "ext-size",     .has_arg = no_argument },
6054         { .name = NULL } };
6055         int c, rc = 0;
6056         int neg_opt = 0;
6057         int pathstart = -1, pathend = -1;
6058         int isoption;
6059         char *end, *tmp;
6060
6061         while ((c = getopt_long(argc, argv,
6062                         "-cdDE::FghiI::LmMNoO:pqrRsSvyz",
6063                         long_opts, NULL)) != -1) {
6064                 if (neg_opt)
6065                         --neg_opt;
6066
6067                 /* '!' is part of option */
6068                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
6069                 if (!isoption && pathend != -1) {
6070                         fprintf(stderr,
6071                                 "error: %s: filename|dirname must either precede options or follow options\n",
6072                                 argv[0]);
6073                         return CMD_HELP;
6074                 }
6075                 if (!isoption && pathstart == -1)
6076                         pathstart = optind - 1;
6077                 if (isoption && pathstart != -1 && pathend == -1)
6078                         pathend = optind - 2;
6079
6080                 switch (c) {
6081                 case 1:
6082                         /* unknown: opt is "!" */
6083                         if (strcmp(optarg, "!") == 0)
6084                                 neg_opt = 2;
6085                         break;
6086                 case 'c':
6087                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6088                                 param->fp_verbose |= VERBOSE_COUNT;
6089                                 param->fp_max_depth = 0;
6090                         }
6091                         break;
6092                 case LFS_COMP_COUNT_OPT:
6093                         param->fp_verbose |= VERBOSE_COMP_COUNT;
6094                         param->fp_max_depth = 0;
6095                         break;
6096                 case LFS_COMP_FLAGS_OPT:
6097                         if (optarg) {
6098                                 rc = comp_str2flags(optarg,
6099                                                     &param->fp_comp_flags,
6100                                                     &param->fp_comp_neg_flags);
6101                                 if (rc != 0) {
6102                                         fprintf(stderr,
6103                                                 "error: %s bad component flags '%s'.\n",
6104                                                 argv[0], optarg);
6105                                         return CMD_HELP;
6106                                 }
6107                                 param->fp_check_comp_flags = 1;
6108                         } else {
6109                                 param->fp_verbose |= VERBOSE_COMP_FLAGS;
6110                                 param->fp_max_depth = 0;
6111                         }
6112                         break;
6113                 case LFS_COMP_START_OPT:
6114                         if (optarg) {
6115                                 tmp = optarg;
6116                                 if (tmp[0] == '+') {
6117                                         param->fp_comp_start_sign = -1;
6118                                         tmp++;
6119                                 } else if (tmp[0] == '-') {
6120                                         param->fp_comp_start_sign = 1;
6121                                         tmp++;
6122                                 }
6123                                 rc = llapi_parse_size(tmp,
6124                                                 &param->fp_comp_start,
6125                                                 &param->fp_comp_start_units, 0);
6126                                 if (rc != 0) {
6127                                         fprintf(stderr,
6128                                                 "error: %s bad component start '%s'.\n",
6129                                                 argv[0], tmp);
6130                                         return CMD_HELP;
6131                                 }
6132                                 param->fp_check_comp_start = 1;
6133                         } else {
6134                                 param->fp_verbose |= VERBOSE_COMP_START;
6135                                 param->fp_max_depth = 0;
6136                         }
6137                         break;
6138                 case LFS_MIRROR_INDEX_OPT: {
6139                         unsigned long int mirror_index;
6140
6141                         if (optarg[0] == '+') {
6142                                 param->fp_mirror_index_sign = -1;
6143                                 optarg++;
6144                         } else if (optarg[0] == '-') {
6145                                 param->fp_mirror_index_sign = 1;
6146                                 optarg++;
6147                         }
6148
6149                         errno = 0;
6150                         mirror_index = strtoul(optarg, &end, 0);
6151                         if (errno != 0 || *end != '\0' ||
6152                             mirror_index > UINT16_MAX || (mirror_index == 0 &&
6153                             param->fp_mirror_index_sign == 0 && neg_opt == 0)) {
6154                                 fprintf(stderr,
6155                                         "%s %s: invalid mirror index '%s'\n",
6156                                         progname, argv[0], optarg);
6157                                 return CMD_HELP;
6158                         }
6159
6160                         param->fp_mirror_index = (__u16)mirror_index;
6161
6162                         if (param->fp_mirror_id != 0) {
6163                                 fprintf(stderr,
6164                                         "%s %s: can't specify both mirror index and mirror ID\n",
6165                                         progname, argv[0]);
6166                                 return CMD_HELP;
6167                         }
6168                         param->fp_check_mirror_index = 1;
6169                         param->fp_exclude_mirror_index = !!neg_opt;
6170                         break;
6171                 }
6172                 case LFS_MIRROR_ID_OPT: {
6173                         unsigned long int mirror_id;
6174
6175                         if (optarg[0] == '+') {
6176                                 param->fp_mirror_id_sign = -1;
6177                                 optarg++;
6178                         } else if (optarg[0] == '-') {
6179                                 param->fp_mirror_id_sign = 1;
6180                                 optarg++;
6181                         }
6182
6183                         errno = 0;
6184                         mirror_id = strtoul(optarg, &end, 0);
6185                         if (errno != 0 || *end != '\0' ||
6186                             mirror_id > UINT16_MAX || (mirror_id == 0 &&
6187                             param->fp_mirror_id_sign == 0 && neg_opt == 0)) {
6188                                 fprintf(stderr,
6189                                         "%s %s: invalid mirror ID '%s'\n",
6190                                         progname, argv[0], optarg);
6191                                 return CMD_HELP;
6192                         }
6193
6194                         param->fp_mirror_id = (__u16)mirror_id;
6195
6196                         if (param->fp_mirror_index != 0) {
6197                                 fprintf(stderr,
6198                                         "%s %s: can't specify both mirror index and mirror ID\n",
6199                                         progname, argv[0]);
6200                                 return CMD_HELP;
6201                         }
6202                         param->fp_check_mirror_id = 1;
6203                         param->fp_exclude_mirror_id = !!neg_opt;
6204                         break;
6205                 }
6206                 case LFS_NO_FOLLOW_OPT:
6207                         param->fp_no_follow = true;
6208                         break;
6209                 case LFS_HEX_IDX_OPT:
6210                         param->fp_hex_idx = true;
6211                         break;
6212                 case 'd':
6213                         param->fp_max_depth = 0;
6214                         break;
6215                 case 'D':
6216                         param->fp_get_default_lmv = 1;
6217                         break;
6218                 case 'E':
6219                         if (optarg) {
6220                                 tmp = optarg;
6221                                 if (tmp[0] == '+') {
6222                                         param->fp_comp_end_sign = -1;
6223                                         tmp++;
6224                                 } else if (tmp[0] == '-') {
6225                                         param->fp_comp_end_sign = 1;
6226                                         tmp++;
6227                                 }
6228
6229                                 if (arg_is_eof(tmp)) {
6230                                         param->fp_comp_end = LUSTRE_EOF;
6231                                         param->fp_comp_end_units = 1;
6232                                         rc = 0;
6233                                 } else {
6234                                         rc = llapi_parse_size(tmp,
6235                                                 &param->fp_comp_end,
6236                                                 &param->fp_comp_end_units, 0);
6237                                         /* assume units of KB if too small */
6238                                         if (param->fp_comp_end < 4096)
6239                                                 param->fp_comp_end *= 1024;
6240                                 }
6241                                 if (rc != 0) {
6242                                         fprintf(stderr,
6243                                                 "error: %s bad component end '%s'.\n",
6244                                                 argv[0], tmp);
6245                                         return CMD_HELP;
6246                                 }
6247                                 param->fp_check_comp_end = 1;
6248                         } else {
6249                                 param->fp_verbose |= VERBOSE_COMP_END;
6250                                 param->fp_max_depth = 0;
6251                         }
6252                         break;
6253                 case 'F':
6254                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6255                                 param->fp_verbose |= VERBOSE_DFID;
6256                                 param->fp_max_depth = 0;
6257                         }
6258                         break;
6259                 case 'g':
6260                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6261                                 param->fp_verbose |= VERBOSE_GENERATION;
6262                                 param->fp_max_depth = 0;
6263                         }
6264                         break;
6265                 case 'i':
6266                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6267                                 param->fp_verbose |= VERBOSE_STRIPE_OFFSET;
6268                                 param->fp_max_depth = 0;
6269                         }
6270                         break;
6271                 case 'I':
6272                         if (optarg) {
6273                                 param->fp_comp_id = strtoul(optarg, &end, 0);
6274                                 if (*end != '\0' || param->fp_comp_id == 0 ||
6275                                     param->fp_comp_id > LCME_ID_MAX) {
6276                                         fprintf(stderr,
6277                                                 "error: %s bad component id '%s'\n",
6278                                                 argv[0], optarg);
6279                                         return CMD_HELP;
6280                                 }
6281                                 param->fp_check_comp_id = 1;
6282                         } else {
6283                                 param->fp_max_depth = 0;
6284                                 param->fp_verbose |= VERBOSE_COMP_ID;
6285                         }
6286                         break;
6287                 case 'L':
6288                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6289                                 param->fp_verbose |= VERBOSE_PATTERN;
6290                                 param->fp_max_depth = 0;
6291                         }
6292                         break;
6293 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6294                 case 'M':
6295                         fprintf(stderr,
6296                                 "warning: '-M' deprecated, use '--mdt-index' or '-m' instead\n");
6297 #endif
6298                 case 'm':
6299                         if (!(param->fp_verbose & VERBOSE_DETAIL))
6300                                 param->fp_max_depth = 0;
6301                         param->fp_verbose |= VERBOSE_MDTINDEX;
6302                         break;
6303                 case 'N':
6304                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6305                                 param->fp_verbose |= VERBOSE_MIRROR_COUNT;
6306                                 param->fp_max_depth = 0;
6307                         }
6308                         break;
6309                 case 'O':
6310                         if (param->fp_obd_uuid) {
6311                                 fprintf(stderr,
6312                                         "error: %s: only one obduuid allowed",
6313                                         argv[0]);
6314                                 return CMD_HELP;
6315                         }
6316                         param->fp_obd_uuid = (struct obd_uuid *)optarg;
6317                         break;
6318                 case 'p':
6319                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6320                                 param->fp_verbose |= VERBOSE_POOL;
6321                                 param->fp_max_depth = 0;
6322                         }
6323                         break;
6324                 case 'q':
6325                         param->fp_quiet++;
6326                         break;
6327                 case 'r':
6328                         param->fp_recursive = 1;
6329                         break;
6330                 case 'R':
6331                         param->fp_raw = 1;
6332                         break;
6333                 case 'S':
6334                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6335                                 param->fp_verbose |= VERBOSE_STRIPE_SIZE;
6336                                 param->fp_max_depth = 0;
6337                         }
6338                         break;
6339                 case 'v':
6340                         param->fp_verbose = VERBOSE_DEFAULT | VERBOSE_DETAIL;
6341                         break;
6342                 case 'y':
6343                         param->fp_yaml = 1;
6344                         break;
6345                 case 'z':
6346                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6347                                 param->fp_verbose |= VERBOSE_EXT_SIZE;
6348                                 param->fp_max_depth = 0;
6349                         }
6350                         break;
6351                 default:
6352                         fprintf(stderr, "%s: unrecognized option '%s'\n",
6353                                 progname, argv[optind - 1]);
6354                 case 'h':
6355                         return CMD_HELP;
6356                 }
6357         }
6358
6359         if (pathstart == -1) {
6360                 fprintf(stderr, "error: %s: no filename|pathname\n",
6361                                 argv[0]);
6362                 return CMD_HELP;
6363         } else if (pathend == -1) {
6364                 /* no options */
6365                 pathend = argc;
6366         }
6367
6368         if (pathend > argc)
6369                 return CMD_HELP;
6370
6371         if (param->fp_recursive)
6372                 param->fp_max_depth = -1;
6373         else if (param->fp_verbose & VERBOSE_DETAIL)
6374                 param->fp_max_depth = 1;
6375
6376         if (!param->fp_verbose)
6377                 param->fp_verbose = VERBOSE_DEFAULT;
6378         if (param->fp_quiet)
6379                 param->fp_verbose = VERBOSE_OBJID;
6380
6381         do {
6382                 int rc2;
6383
6384                 rc2 = llapi_getstripe(argv[pathstart], param);
6385                 if (rc2) {
6386                         fprintf(stderr, "%s: %s for '%s' failed: %s\n",
6387                                 progname, argv[0], argv[optind - 1],
6388                                 strerror(-rc2));
6389                         if (!rc)
6390                                 rc = rc2;
6391                 }
6392         } while (++pathstart < pathend);
6393
6394         return rc;
6395 }
6396
6397 static int lfs_tgts(int argc, char **argv)
6398 {
6399         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
6400         struct find_param param;
6401         int index = 0, rc = 0;
6402
6403         if (argc > 2)
6404                 return CMD_HELP;
6405
6406         if (argc == 2 && !realpath(argv[1], path)) {
6407                 rc = -errno;
6408                 fprintf(stderr, "error: invalid path '%s': %s\n",
6409                         argv[1], strerror(-rc));
6410                 return rc;
6411         }
6412
6413         while (!llapi_search_mounts(path, index++, mntdir, NULL)) {
6414                 /* Check if we have a mount point */
6415                 if (mntdir[0] == '\0')
6416                         continue;
6417
6418                 memset(&param, 0, sizeof(param));
6419                 if (!strcmp(argv[0], "mdts"))
6420                         param.fp_get_lmv = 1;
6421
6422                 rc = llapi_ostlist(mntdir, &param);
6423                 if (rc) {
6424                         fprintf(stderr, "error: %s: failed on %s\n",
6425                                 argv[0], mntdir);
6426                 }
6427                 if (path[0] != '\0')
6428                         break;
6429                 memset(mntdir, 0, PATH_MAX);
6430         }
6431
6432         return rc;
6433 }
6434
6435 static int lfs_getstripe(int argc, char **argv)
6436 {
6437         struct find_param param = { 0 };
6438
6439         param.fp_max_depth = 1;
6440         return lfs_getstripe_internal(argc, argv, &param);
6441 }
6442
6443 /* functions */
6444 static int lfs_getdirstripe(int argc, char **argv)
6445 {
6446         struct find_param param = { 0 };
6447         struct option long_opts[] = {
6448         { .val = 'c',   .name = "mdt-count",     .has_arg = no_argument },
6449         { .val = 'D',   .name = "default",       .has_arg = no_argument },
6450         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6451         { .val = 'H',   .name = "mdt-hash",      .has_arg = no_argument },
6452         { .val = LFS_HEX_IDX_OPT,
6453                         .name = "hex-idx",       .has_arg = no_argument },
6454         { .val = 'i',   .name = "mdt-index",     .has_arg = no_argument },
6455         { .val = 'm',   .name = "mdt-index",     .has_arg = no_argument },
6456         { .val = 'O',   .name = "obd",           .has_arg = required_argument },
6457         { .val = 'r',   .name = "recursive",     .has_arg = no_argument },
6458         { .val = 'R',   .name = "raw",          .has_arg = no_argument },
6459         { .val = 'T',   .name = "mdt-count",     .has_arg = no_argument },
6460         { .val = 'v',   .name = "verbose",       .has_arg = no_argument },
6461         { .val = 'X',   .name = "max-inherit",   .has_arg = no_argument },
6462         { .val = LFS_INHERIT_RR_OPT,
6463                         .name = "max-inherit-rr", .has_arg = no_argument },
6464         { .val = 'y',   .name = "yaml",          .has_arg = no_argument },
6465         { .name = NULL } };
6466         int c, rc = 0;
6467
6468         param.fp_get_lmv = 1;
6469
6470         while ((c = getopt_long(argc, argv,
6471                                 "cDhHimO:rRtTvXy", long_opts, NULL)) != -1) {
6472                 switch (c) {
6473                 case 'c':
6474                 case 'T':
6475                         param.fp_verbose |= VERBOSE_COUNT;
6476                         break;
6477                 case 'D':
6478                         param.fp_get_default_lmv = 1;
6479                         break;
6480 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6481                 case 't':
6482                         fprintf(stderr,
6483                                 "warning: '-t' deprecated, use '--mdt-hash' or '-H' instead\n");
6484                         fallthrough;
6485 #endif
6486                 case 'H':
6487                         param.fp_verbose |= VERBOSE_HASH_TYPE;
6488                         break;
6489                 case LFS_HEX_IDX_OPT:
6490                         param.fp_hex_idx = 1;
6491                         break;
6492                 case 'i':
6493                         fallthrough;
6494                 case 'm':
6495                         param.fp_verbose |= VERBOSE_STRIPE_OFFSET;
6496                         break;
6497                 case 'O':
6498                         if (param.fp_obd_uuid) {
6499                                 fprintf(stderr,
6500                                         "%s: only one obduuid allowed",
6501                                         progname);
6502                                 return CMD_HELP;
6503                         }
6504                         param.fp_obd_uuid = (struct obd_uuid *)optarg;
6505                         break;
6506                 case 'r':
6507                         param.fp_recursive = 1;
6508                         break;
6509                 case 'R':
6510                         param.fp_raw = 1;
6511                         break;
6512                 case 'v':
6513                         param.fp_verbose |= VERBOSE_DEFAULT;
6514                         param.fp_verbose |= VERBOSE_DETAIL;
6515                         break;
6516                 case 'X':
6517                         param.fp_verbose |= VERBOSE_INHERIT;
6518                         break;
6519                 case LFS_INHERIT_RR_OPT:
6520                         param.fp_verbose |= VERBOSE_INHERIT_RR;
6521                         break;
6522                 case 'y':
6523                         param.fp_yaml = 1;
6524                         break;
6525                 default:
6526                         fprintf(stderr, "%s: unrecognized option '%s'\n",
6527                                 progname, argv[optind - 1]);
6528                         fallthrough;
6529                 case 'h':
6530                         return CMD_HELP;
6531                 }
6532         }
6533
6534         if (optind >= argc)
6535                 return CMD_HELP;
6536
6537         if (param.fp_recursive)
6538                 param.fp_max_depth = -1;
6539
6540         if (!param.fp_verbose)
6541                 param.fp_verbose = VERBOSE_DEFAULT;
6542
6543         do {
6544                 int rc2;
6545
6546                 rc2 = llapi_getstripe(argv[optind], &param);
6547                 if (rc2) {
6548                         fprintf(stderr, "%s: %s for '%s' failed: %s\n",
6549                                 progname, argv[0], argv[optind],
6550                                 strerror(-rc2));
6551                         if (!rc)
6552                                 rc = rc2;
6553                 }
6554         } while (++optind < argc);
6555
6556         return rc;
6557 }
6558
6559 enum mntdf_flags {
6560         MNTDF_INODES    = 0x0001,
6561         MNTDF_COOKED    = 0x0002,
6562         MNTDF_LAZY      = 0x0004,
6563         MNTDF_VERBOSE   = 0x0008,
6564         MNTDF_SHOW      = 0x0010,
6565         MNTDF_DECIMAL   = 0x0020,
6566 };
6567
6568 #define COOK(value, base)                                       \
6569 ({                                                              \
6570         int radix = 0;                                          \
6571         while (value > base) {                                  \
6572                 value /= base;                                  \
6573                 radix++;                                        \
6574         }                                                       \
6575         radix;                                                  \
6576 })
6577 #define UUF     "%-20s"
6578 #define CSF     "%11s"
6579 #define CDF     "%11llu"
6580 #define HDF     "%8.1f%c"
6581 #define RSF     "%4s"
6582 #define RDF     "%3d%%"
6583
6584 static inline int obd_statfs_ratio(const struct obd_statfs *st, bool inodes)
6585 {
6586         double avail, used, ratio = 0;
6587
6588         if (inodes) {
6589                 avail = st->os_ffree;
6590                 used = st->os_files - st->os_ffree;
6591         } else {
6592                 avail = st->os_bavail;
6593                 used = st->os_blocks - st->os_bfree;
6594         }
6595         if (avail + used > 0)
6596                 ratio = used / (used + avail) * 100;
6597
6598         /* Round up to match df(1) usage percentage */
6599         return (ratio - (int)ratio) > 0 ? (int)(ratio + 1) : (int)ratio;
6600 }
6601
6602 /*
6603  * This is to identify various problem states for "lfs df" if .osn_err = true,
6604  * so only show flags reflecting those states by default. Informational states
6605  * are only shown with "-v" and use lower-case names to distinguish them.
6606  * UNUSED[12] were for "EROFS = 30" until 1.6 but are now available for use.
6607  */
6608 static struct obd_statfs_state_names {
6609         enum obd_statfs_state   osn_state;
6610         const char              osn_name;
6611         bool                    osn_err;
6612 } oss_names[] = {
6613         { .osn_state = OS_STATFS_DEGRADED,   .osn_name = 'D', .osn_err = true },
6614         { .osn_state = OS_STATFS_READONLY,   .osn_name = 'R', .osn_err = true },
6615         { .osn_state = OS_STATFS_NOPRECREATE,.osn_name = 'N', .osn_err = true },
6616         { .osn_state = OS_STATFS_UNUSED1,    .osn_name = '?', .osn_err = true },
6617         { .osn_state = OS_STATFS_UNUSED2,    .osn_name = '?', .osn_err = true },
6618         { .osn_state = OS_STATFS_ENOSPC,     .osn_name = 'S', .osn_err = true },
6619         { .osn_state = OS_STATFS_ENOINO,     .osn_name = 'I', .osn_err = true },
6620         { .osn_state = OS_STATFS_SUM,        .osn_name = 'a', /* aggregate */ },
6621         { .osn_state = OS_STATFS_NONROT,     .osn_name = 'f', /* flash */     },
6622 };
6623
6624 static int showdf(char *mntdir, struct obd_statfs *stat,
6625                   char *uuid, enum mntdf_flags flags,
6626                   char *type, int index, int rc)
6627 {
6628         long long avail, used, total;
6629         int ratio = 0;
6630         char *suffix = flags & MNTDF_DECIMAL ? "kMGTPEZY" : "KMGTPEZY";
6631         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
6632         char tbuf[3 * sizeof(__u64)];
6633         char ubuf[3 * sizeof(__u64)];
6634         char abuf[3 * sizeof(__u64)];
6635         char rbuf[3 * sizeof(__u64)];
6636
6637         if (!uuid || !stat)
6638                 return -EINVAL;
6639
6640         switch (rc) {
6641         case 0:
6642                 if (flags & MNTDF_INODES) {
6643                         avail = stat->os_ffree;
6644                         used = stat->os_files - stat->os_ffree;
6645                         total = stat->os_files;
6646                 } else {
6647                         int shift = flags & MNTDF_COOKED ? 0 : 10;
6648
6649                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
6650                         used  = ((stat->os_blocks - stat->os_bfree) *
6651                                  stat->os_bsize) >> shift;
6652                         total = (stat->os_blocks * stat->os_bsize) >> shift;
6653                 }
6654
6655                 ratio = obd_statfs_ratio(stat, flags & MNTDF_INODES);
6656
6657                 if (flags & MNTDF_COOKED) {
6658                         int base = flags & MNTDF_DECIMAL ? 1000 : 1024;
6659                         double cook_val;
6660                         int i;
6661
6662                         cook_val = (double)total;
6663                         i = COOK(cook_val, base);
6664                         if (i > 0)
6665                                 snprintf(tbuf, sizeof(tbuf), HDF, cook_val,
6666                                          suffix[i - 1]);
6667                         else
6668                                 snprintf(tbuf, sizeof(tbuf), CDF, total);
6669
6670                         cook_val = (double)used;
6671                         i = COOK(cook_val, base);
6672                         if (i > 0)
6673                                 snprintf(ubuf, sizeof(ubuf), HDF, cook_val,
6674                                          suffix[i - 1]);
6675                         else
6676                                 snprintf(ubuf, sizeof(ubuf), CDF, used);
6677
6678                         cook_val = (double)avail;
6679                         i = COOK(cook_val, base);
6680                         if (i > 0)
6681                                 snprintf(abuf, sizeof(abuf), HDF, cook_val,
6682                                          suffix[i - 1]);
6683                         else
6684                                 snprintf(abuf, sizeof(abuf), CDF, avail);
6685                 } else {
6686                         snprintf(tbuf, sizeof(tbuf), CDF, total);
6687                         snprintf(ubuf, sizeof(tbuf), CDF, used);
6688                         snprintf(abuf, sizeof(tbuf), CDF, avail);
6689                 }
6690
6691                 sprintf(rbuf, RDF, ratio);
6692                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
6693                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
6694                 if (type)
6695                         printf("[%s:%d]", type, index);
6696
6697                 if (stat->os_state) {
6698                         uint32_t i;
6699
6700                         printf(" ");
6701                         for (i = 0; i < ARRAY_SIZE(oss_names); i++) {
6702                                 if (oss_names[i].osn_state & stat->os_state &&
6703                                     (oss_names[i].osn_err ||
6704                                      flags & MNTDF_VERBOSE))
6705                                         printf("%c", oss_names[i].osn_name);
6706                         }
6707                 }
6708
6709                 printf("\n");
6710                 break;
6711         case -ENODATA:
6712                 printf(UUF": inactive device\n", uuid);
6713                 break;
6714         default:
6715                 printf(UUF": %s\n", uuid, strerror(-rc));
6716                 break;
6717         }
6718
6719         return 0;
6720 }
6721
6722 struct ll_stat_type {
6723         int   st_op;
6724         char *st_name;
6725 };
6726
6727 #define LL_STATFS_MAX   LOV_MAX_STRIPE_COUNT
6728
6729 struct ll_statfs_data {
6730         int                     sd_index;
6731         struct obd_statfs       sd_st;
6732 };
6733
6734 struct ll_statfs_buf {
6735         int                     sb_count;
6736         struct ll_statfs_data   sb_buf[LL_STATFS_MAX];
6737 };
6738
6739 static int mntdf(char *mntdir, char *fsname, char *pool, enum mntdf_flags flags,
6740                  int ops, struct ll_statfs_buf *lsb)
6741 {
6742         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
6743         struct obd_uuid uuid_buf;
6744         char *poolname = NULL;
6745         struct ll_stat_type types[] = {
6746                 { .st_op = LL_STATFS_LMV,       .st_name = "MDT" },
6747                 { .st_op = LL_STATFS_LOV,       .st_name = "OST" },
6748                 { .st_name = NULL } };
6749         struct ll_stat_type *tp;
6750         __u64 ost_files = 0;
6751         __u64 ost_ffree = 0;
6752         __u32 index;
6753         __u32 type;
6754         int fd;
6755         int rc = 0;
6756         int rc2;
6757
6758         if (pool) {
6759                 poolname = strchr(pool, '.');
6760                 if (poolname) {
6761                         if (strncmp(fsname, pool, strlen(fsname))) {
6762                                 fprintf(stderr, "filesystem name incorrect\n");
6763                                 return -ENODEV;
6764                         }
6765                         poolname++;
6766                 } else
6767                         poolname = pool;
6768         }
6769
6770         fd = open(mntdir, O_RDONLY);
6771         if (fd < 0) {
6772                 rc = -errno;
6773                 fprintf(stderr, "%s: cannot open '%s': %s\n", progname, mntdir,
6774                         strerror(errno));
6775                 return rc;
6776         }
6777
6778         if (flags & MNTDF_SHOW) {
6779                 if (flags & MNTDF_INODES)
6780                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
6781                                "UUID", "Inodes", "IUsed", "IFree",
6782                                "IUse%", "Mounted on");
6783                 else
6784                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
6785                                "UUID",
6786                                flags & MNTDF_COOKED ? "bytes" : "1K-blocks",
6787                                "Used", "Available", "Use%", "Mounted on");
6788         }
6789
6790         for (tp = types; tp->st_name != NULL; tp++) {
6791                 bool have_ost = false;
6792
6793                 if (!(tp->st_op & ops))
6794                         continue;
6795
6796                 for (index = 0; index < LOV_ALL_STRIPES &&
6797                      (!lsb || lsb->sb_count < LL_STATFS_MAX); index++) {
6798                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
6799                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
6800                         type = flags & MNTDF_LAZY ?
6801                                 tp->st_op | LL_STATFS_NODELAY : tp->st_op;
6802                         rc2 = llapi_obd_fstatfs(fd, type, index,
6803                                                 &stat_buf, &uuid_buf);
6804                         if (rc2 == -ENODEV)
6805                                 break;
6806                         if (rc2 == -EAGAIN)
6807                                 continue;
6808                         if (rc2 == -ENODATA) { /* Inactive device, OK. */
6809                                 if (!(flags & MNTDF_VERBOSE))
6810                                         continue;
6811                         } else if (rc2 < 0 && rc == 0) {
6812                                 rc = rc2;
6813                         }
6814
6815                         /*
6816                          * If we have OSTs then don't report MDT block counts.
6817                          * For MDT-only filesystems the expectation is that all
6818                          * layouts have a DoM component.  For filesystems with
6819                          * OSTs, files are not necessarily going to store data
6820                          * on MDTs, and MDT space is limited to a fraction of
6821                          * OST space, so don't include it in the summary.
6822                          */
6823                         if (tp->st_op == LL_STATFS_LOV && !have_ost) {
6824                                 have_ost = true;
6825                                 sum.os_blocks = 0;
6826                                 sum.os_bfree = 0;
6827                                 sum.os_bavail = 0;
6828                         }
6829
6830                         if (poolname && tp->st_op == LL_STATFS_LOV &&
6831                             llapi_search_ost(fsname, poolname,
6832                                              obd_uuid2str(&uuid_buf)) != 1)
6833                                 continue;
6834
6835                         /*
6836                          * the llapi_obd_fstatfs() call may have returned with
6837                          * an error, but if it filled in uuid_buf we will at
6838                          * lease use that to print out a message for that OBD.
6839                          * If we didn't get anything in the uuid_buf, then fill
6840                          * it in so that we can print an error message.
6841                          */
6842                         if (uuid_buf.uuid[0] == '\0')
6843                                 snprintf(uuid_buf.uuid, sizeof(uuid_buf.uuid),
6844                                          "%s%04x", tp->st_name, index);
6845                         if (!rc && lsb) {
6846                                 lsb->sb_buf[lsb->sb_count].sd_index = index;
6847                                 lsb->sb_buf[lsb->sb_count].sd_st = stat_buf;
6848                                 lsb->sb_count++;
6849                         }
6850                         if (flags & MNTDF_SHOW)
6851                                 showdf(mntdir, &stat_buf,
6852                                        obd_uuid2str(&uuid_buf), flags,
6853                                        tp->st_name, index, rc2);
6854
6855                         if (rc2)
6856                                 continue;
6857
6858                         if (tp->st_op == LL_STATFS_LMV) {
6859                                 sum.os_ffree += stat_buf.os_ffree;
6860                                 sum.os_files += stat_buf.os_files;
6861                         } else /* if (tp->st_op == LL_STATFS_LOV) */ {
6862                                 ost_files += stat_buf.os_files;
6863                                 ost_ffree += stat_buf.os_ffree;
6864                         }
6865                         sum.os_blocks += stat_buf.os_blocks *
6866                                          stat_buf.os_bsize;
6867                         sum.os_bfree  += stat_buf.os_bfree *
6868                                          stat_buf.os_bsize;
6869                         sum.os_bavail += stat_buf.os_bavail *
6870                                          stat_buf.os_bsize;
6871                 }
6872         }
6873
6874         close(fd);
6875
6876         /*
6877          * If we have _some_ OSTs, but don't have as many free objects on the
6878          * OST as inodes on the MDTs, reduce the reported number of inodes
6879          * to compensate, so that the "inodes in use" number is correct.
6880          * This should be kept in sync with ll_statfs_internal().
6881          */
6882         if (ost_files && ost_ffree < sum.os_ffree) {
6883                 sum.os_files = (sum.os_files - sum.os_ffree) + ost_ffree;
6884                 sum.os_ffree = ost_ffree;
6885         }
6886         if (flags & MNTDF_SHOW) {
6887                 printf("\n");
6888                 showdf(mntdir, &sum, "filesystem_summary:", flags, NULL, 0, 0);
6889                 printf("\n");
6890         }
6891
6892         return rc;
6893 }
6894
6895 enum {
6896         LAYOUT_INHERIT_UNSET    = -2,
6897 };
6898
6899 /* functions */
6900 static int lfs_setdirstripe(int argc, char **argv)
6901 {
6902         char *dname;
6903         struct lfs_setstripe_args lsa = { 0 };
6904         struct llapi_stripe_param *param = NULL;
6905         __u32 mdts[LMV_MAX_STRIPE_COUNT] = { 0 };
6906         char *end;
6907         int c;
6908         char *mode_opt = NULL;
6909         bool default_stripe = false;
6910         bool delete = false;
6911         bool foreign_mode = false;
6912         bool mdt_count_set = false;
6913         mode_t mode = S_IRWXU | S_IRWXG | S_IRWXO;
6914         mode_t previous_mode = 0;
6915         char *xattr = NULL;
6916         __u32 type = LU_FOREIGN_TYPE_SYMLINK, flags = 0;
6917         int max_inherit = LAYOUT_INHERIT_UNSET;
6918         int max_inherit_rr = LAYOUT_INHERIT_UNSET;
6919         struct option long_opts[] = {
6920         { .val = 'c',   .name = "count",        .has_arg = required_argument },
6921         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument },
6922         { .val = 'd',   .name = "delete",       .has_arg = no_argument },
6923         { .val = 'D',   .name = "default",      .has_arg = no_argument },
6924         { .val = 'D',   .name = "default_stripe", .has_arg = no_argument },
6925         { .val = LFS_LAYOUT_FLAGS_OPT,
6926                         .name = "flags",        .has_arg = required_argument },
6927         { .val = LFS_LAYOUT_FOREIGN_OPT,
6928                         .name = "foreign",      .has_arg = optional_argument},
6929         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6930         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
6931 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 17, 53, 0)
6932         { .val = 'i',   .name = "mdt-index",    .has_arg = required_argument },
6933         { .val = 'i',   .name = "mdt",          .has_arg = required_argument },
6934 #else
6935 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
6936         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
6937         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
6938 #endif
6939 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6940         { .val = 'i',   .name = "index",        .has_arg = required_argument },
6941 #endif
6942         { .val = 'o',   .name = "mode",         .has_arg = required_argument },
6943 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6944         { .val = 't',   .name = "hash-type",    .has_arg = required_argument },
6945 #endif
6946         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
6947         { .val = 'x',   .name = "xattr",        .has_arg = required_argument },
6948         { .val = 'X',   .name = "max-inherit",  .has_arg = required_argument },
6949         { .val = LFS_INHERIT_RR_OPT,
6950                         .name = "max-inherit-rr", .has_arg = required_argument},
6951 /* setstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
6952 /* setstripe { .val = 'W', .name = "bandwidth", .has_arg = required_argument }, */
6953         { .name = NULL } };
6954         int result = 0;
6955
6956         setstripe_args_init(&lsa);
6957
6958         while ((c = getopt_long(argc, argv, "c:dDi:hH:m:o:t:T:x:X:",
6959                                 long_opts, NULL)) >= 0) {
6960                 switch (c) {
6961                 case 0:
6962                         /* Long options. */
6963                         break;
6964                 case 'c':
6965                 case 'T':
6966                         errno = 0;
6967                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
6968                         if (errno != 0 || *end != '\0' ||
6969                             lsa.lsa_stripe_count < -1 ||
6970                             lsa.lsa_stripe_count > LOV_MAX_STRIPE_COUNT) {
6971                                 fprintf(stderr,
6972                                         "%s: invalid stripe count '%s'\n",
6973                                         progname, optarg);
6974                                 return CMD_HELP;
6975                         }
6976                         mdt_count_set = true;
6977                         break;
6978                 case 'd':
6979                         delete = true;
6980                         default_stripe = true;
6981                         break;
6982                 case 'D':
6983                         default_stripe = true;
6984                         break;
6985                 case LFS_LAYOUT_FOREIGN_OPT:
6986                         if (optarg) {
6987                                 /* check pure numeric */
6988                                 type = strtoul(optarg, &end, 0);
6989                                 if (*end) {
6990                                         /* check name */
6991                                         type = check_foreign_type_name(optarg);
6992                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
6993                                                 fprintf(stderr,
6994                                                         "%s %s: unknown foreign type '%s'\n",
6995                                                         progname, argv[0],
6996                                                         optarg);
6997                                                 return CMD_HELP;
6998                                         }
6999                                 } else if (type >= UINT32_MAX) {
7000                                         fprintf(stderr,
7001                                                 "%s %s: invalid foreign type '%s'\n",
7002                                                 progname, argv[0], optarg);
7003                                         return CMD_HELP;
7004                                 }
7005                         }
7006                         foreign_mode = true;
7007                         break;
7008                 case LFS_LAYOUT_FLAGS_OPT:
7009                         errno = 0;
7010                         flags = strtoul(optarg, &end, 16);
7011                         if (errno != 0 || *end != '\0' ||
7012                             flags >= UINT32_MAX) {
7013                                 fprintf(stderr,
7014                                         "%s %s: invalid hex flags '%s'\n",
7015                                         progname, argv[0], optarg);
7016                                 return CMD_HELP;
7017                         }
7018                         if (!foreign_mode) {
7019                                 fprintf(stderr,
7020                                         "%s %s: hex flags must be specified with --foreign option\n",
7021                                         progname, argv[0]);
7022                                 return CMD_HELP;
7023                         }
7024                         break;
7025 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
7026                 case 't':
7027                         fprintf(stderr,
7028                                 "warning: '--hash-type' and '-t' deprecated, use '--mdt-hash' or '-H' instead\n");
7029                         fallthrough;
7030 #endif
7031                 case 'H':
7032                         lsa.lsa_pattern = check_hashtype(optarg);
7033                         if (lsa.lsa_pattern == 0) {
7034                                 fprintf(stderr,
7035                                         "%s %s: bad directory hash type '%s'\n",
7036                                         progname, argv[0], optarg);
7037                                 return CMD_HELP;
7038                         }
7039                         break;
7040                 case 'i':
7041 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 17, 53, 0)
7042                 case 'm':
7043 #endif
7044 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
7045                         if (strcmp(argv[optind - 1], "--index") == 0)
7046                                 fprintf(stderr,
7047                                         "%s %s: warning: '--index' deprecated, use '--mdt-index' instead\n",
7048                                         progname, argv[0]);
7049 #endif
7050                         lsa.lsa_nr_tgts = parse_targets(mdts,
7051                                                 sizeof(mdts) / sizeof(__u32),
7052                                                 lsa.lsa_nr_tgts, optarg, NULL);
7053                         if (lsa.lsa_nr_tgts < 0) {
7054                                 fprintf(stderr,
7055                                         "%s %s: invalid MDT target(s) '%s'\n",
7056                                         progname, argv[0], optarg);
7057                                 return CMD_HELP;
7058                         }
7059
7060                         lsa.lsa_tgts = mdts;
7061                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
7062                                 lsa.lsa_stripe_off = mdts[0];
7063                         break;
7064                 case 'o':
7065                         mode_opt = optarg;
7066                         break;
7067                 case 'x':
7068                         xattr = optarg;
7069                         break;
7070                 case 'X':
7071                         errno = 0;
7072                         max_inherit = strtol(optarg, &end, 10);
7073                         if (errno != 0 || *end != '\0' || max_inherit < -2) {
7074                                 fprintf(stderr,
7075                                         "%s %s: invalid max-inherit '%s'\n",
7076                                         progname, argv[0], optarg);
7077                                 return CMD_HELP;
7078                         }
7079                         if (max_inherit == 0) {
7080                                 max_inherit = LMV_INHERIT_NONE;
7081                         } else if (max_inherit == -1) {
7082                                 max_inherit = LMV_INHERIT_UNLIMITED;
7083                         } else if (max_inherit > LMV_INHERIT_MAX) {
7084                                 fprintf(stderr,
7085                                         "%s %s: max-inherit %d exceeds maximum %u\n",
7086                                         progname, argv[0], max_inherit,
7087                                         LMV_INHERIT_MAX);
7088                                 return CMD_HELP;
7089                         }
7090                         break;
7091                 case LFS_INHERIT_RR_OPT:
7092                         if (!default_stripe) {
7093                                 fprintf(stderr,
7094                                         "%s %s: '--max-inherit-rr' must be specified with '-D'\n",
7095                                         progname, argv[0]);
7096                                 return CMD_HELP;
7097                         }
7098                         errno = 0;
7099                         max_inherit_rr = strtol(optarg, &end, 10);
7100                         if (errno != 0 || *end != '\0' || max_inherit_rr < -2) {
7101                                 fprintf(stderr,
7102                                         "%s %s: invalid max-inherit-rr '%s'\n",
7103                                         progname, argv[0], optarg);
7104                                 return CMD_HELP;
7105                         }
7106                         if (max_inherit_rr == 0) {
7107                                 max_inherit_rr = LMV_INHERIT_RR_NONE;
7108                         } else if (max_inherit_rr == -1) {
7109                                 max_inherit_rr = LMV_INHERIT_RR_UNLIMITED;
7110                         } else if (max_inherit_rr > LMV_INHERIT_RR_MAX) {
7111                                 fprintf(stderr,
7112                                         "%s %s: max-inherit-rr %d exceeds maximum %u\n",
7113                                         progname, argv[0], max_inherit_rr,
7114                                         LMV_INHERIT_RR_MAX);
7115                                 return CMD_HELP;
7116                         }
7117                         break;
7118                 default:
7119                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7120                                 progname, argv[optind - 1]);
7121                         fallthrough;
7122                 case 'h':
7123                         return CMD_HELP;
7124                 }
7125         }
7126
7127         if (optind == argc) {
7128                 fprintf(stderr, "%s %s: DIR must be specified\n",
7129                         progname, argv[0]);
7130                 return CMD_HELP;
7131         }
7132
7133         if (xattr && !foreign_mode) {
7134                 /*
7135                  * only print a warning as this is armless and will be
7136                  * ignored
7137                  */
7138                 fprintf(stderr,
7139                         "%s %s: xattr has been specified for non-foreign layout\n",
7140                         progname, argv[0]);
7141         } else if (foreign_mode && !xattr) {
7142                 fprintf(stderr,
7143                         "%s %s: xattr must be provided in foreign mode\n",
7144                         progname, argv[0]);
7145                 return CMD_HELP;
7146         }
7147
7148         if (foreign_mode && (delete || default_stripe || lsa.lsa_nr_tgts ||
7149             lsa.lsa_tgts || setstripe_args_specified(&lsa))) {
7150                 fprintf(stderr,
7151                         "%s %s: only --xattr/--flags/--mode options are valid with --foreign\n",
7152                         progname, argv[0]);
7153                 return CMD_HELP;
7154         }
7155
7156         if (!delete && lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT &&
7157             lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT && !foreign_mode) {
7158                 /* if no parameters set, create directory on least-used MDTs */
7159                 lsa.lsa_stripe_off = LMV_OFFSET_DEFAULT;
7160                 lsa.lsa_stripe_count = 1;
7161         }
7162
7163         if (delete &&
7164             (lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
7165              lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)) {
7166                 fprintf(stderr,
7167                         "%s %s: cannot specify -d with -c or -i options\n",
7168                         progname, argv[0]);
7169                 return CMD_HELP;
7170         }
7171
7172         if (mode_opt) {
7173                 mode = strtoul(mode_opt, &end, 8);
7174                 if (*end != '\0') {
7175                         fprintf(stderr,
7176                                 "%s %s: bad MODE '%s'\n",
7177                                 progname, argv[0], mode_opt);
7178                         return CMD_HELP;
7179                 }
7180                 previous_mode = umask(0);
7181         }
7182
7183         /* check max-inherit and warn user in some cases */
7184         if (default_stripe &&
7185             (lsa.lsa_stripe_count < 0 || lsa.lsa_stripe_count > 1)) {
7186                 if (max_inherit == LMV_INHERIT_UNLIMITED)
7187                         fprintf(stderr,
7188                         "%s %s: unrecommended max-inherit=-1 when default stripe-count=%lld\n",
7189                         progname, argv[0], lsa.lsa_stripe_count);
7190                 else if (max_inherit > LMV_INHERIT_DEFAULT_STRIPED + 2 &&
7191                          max_inherit != LMV_INHERIT_NONE)
7192                         fprintf(stderr,
7193                                 "%s %s: unrecommended max-inherit=%d when default stripe-count=%lld\n",
7194                                 progname, argv[0], max_inherit,
7195                                 lsa.lsa_stripe_count);
7196         }
7197
7198         if (default_stripe && lsa.lsa_nr_tgts > 1 && !mdt_count_set) {
7199                 fprintf(stderr,
7200                         "%s %s: trying to create unrecommended default striped directory layout,\n"
7201                         "       '-D -i x,y,z' will stripe every new directory across all MDTs,\n"
7202                         "       add -c with the number of MDTs to do this anyway\n",
7203                         progname, argv[0]);
7204                 return CMD_HELP;
7205         }
7206
7207         if (max_inherit_rr != LAYOUT_INHERIT_UNSET &&
7208             lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT &&
7209             lsa.lsa_stripe_off != LMV_OFFSET_DEFAULT) {
7210                 fprintf(stderr,
7211                         "%s %s: max-inherit-rr needs mdt-index=-1, not %lld\n",
7212                         progname, argv[0], lsa.lsa_stripe_off);
7213                 return CMD_HELP;
7214         }
7215
7216         /* foreign LMV/dir case */
7217         if (foreign_mode) {
7218                 if (argc > optind + 1) {
7219                         fprintf(stderr,
7220                                 "%s %s: cannot specify multiple foreign dirs\n",
7221                                 progname, argv[0]);
7222                         return CMD_HELP;
7223                 }
7224
7225                 dname = argv[optind];
7226                 result = llapi_dir_create_foreign(dname, mode, type, flags,
7227                                                   xattr);
7228                 if (result != 0)
7229                         fprintf(stderr,
7230                                 "%s mkdir: can't create foreign dir '%s': %s\n",
7231                                 progname, dname, strerror(-result));
7232                 return result;
7233         }
7234
7235         /*
7236          * initialize stripe parameters, in case param is converted to specific,
7237          * i.e, 'lfs mkdir -i -1 -c N', always allocate space for lsp_tgts.
7238          */
7239         param = calloc(1, offsetof(typeof(*param),
7240                        lsp_tgts[lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ?
7241                                 lsa.lsa_stripe_count : lsa.lsa_nr_tgts]));
7242         if (!param) {
7243                 fprintf(stderr,
7244                         "%s %s: cannot allocate memory for parameters: %s\n",
7245                         progname, argv[0], strerror(ENOMEM));
7246                 return CMD_HELP;
7247         }
7248
7249         /* if "lfs setdirstripe -D -i -1" is used, assume 1-stripe directory */
7250         if (default_stripe && lsa.lsa_stripe_off == LMV_OFFSET_DEFAULT &&
7251             (lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT ||
7252              lsa.lsa_stripe_count == 0))
7253                 lsa.lsa_stripe_count = 1;
7254         if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
7255                 param->lsp_stripe_count = lsa.lsa_stripe_count;
7256         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
7257                 param->lsp_stripe_offset = LMV_OFFSET_DEFAULT;
7258         else
7259                 param->lsp_stripe_offset = lsa.lsa_stripe_off;
7260         if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
7261                 param->lsp_stripe_pattern = lsa.lsa_pattern;
7262         else
7263                 param->lsp_stripe_pattern = LMV_HASH_TYPE_UNKNOWN;
7264         param->lsp_pool = lsa.lsa_pool_name;
7265         param->lsp_is_specific = false;
7266
7267         if (max_inherit == LAYOUT_INHERIT_UNSET) {
7268                 if (lsa.lsa_stripe_count == 0 || lsa.lsa_stripe_count == 1 ||
7269                     lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT)
7270                         max_inherit = LMV_INHERIT_DEFAULT_PLAIN;
7271                 else
7272                         max_inherit = LMV_INHERIT_DEFAULT_STRIPED;
7273         }
7274         param->lsp_max_inherit = max_inherit;
7275         if (default_stripe) {
7276
7277                 if (max_inherit_rr == LAYOUT_INHERIT_UNSET)
7278                         max_inherit_rr = LMV_INHERIT_RR_DEFAULT;
7279                 param->lsp_max_inherit_rr = max_inherit_rr;
7280         }
7281         if (strcmp(argv[0], "mkdir") == 0)
7282                 param->lsp_is_create = true;
7283         if (lsa.lsa_nr_tgts > 1) {
7284                 if (lsa.lsa_stripe_count > 0 &&
7285                     lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
7286                     lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
7287                         fprintf(stderr,
7288                                 "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
7289                                 argv[0], lsa.lsa_stripe_count,
7290                                 lsa.lsa_nr_tgts);
7291                         free(param);
7292                         return CMD_HELP;
7293                 }
7294
7295                 param->lsp_is_specific = true;
7296                 param->lsp_stripe_count = lsa.lsa_nr_tgts;
7297                 memcpy(param->lsp_tgts, mdts, sizeof(*mdts) * lsa.lsa_nr_tgts);
7298         }
7299
7300         dname = argv[optind];
7301         do {
7302                 if (default_stripe) {
7303                         result = llapi_dir_set_default_lmv(dname, param);
7304                         if (result)
7305                                 fprintf(stderr,
7306                                         "%s setdirstripe: cannot set default stripe on dir '%s': %s\n",
7307                                         progname, dname, strerror(-result));
7308                         continue;
7309                 }
7310
7311                 result = llapi_dir_create(dname, mode, param);
7312                 if (result)
7313                         fprintf(stderr,
7314                                 "%s setdirstripe: cannot create dir '%s': %s\n",
7315                                 progname, dname, strerror(-result));
7316         } while (!result && (dname = argv[++optind]));
7317
7318         if (mode_opt)
7319                 umask(previous_mode);
7320
7321         free(param);
7322         return result;
7323 }
7324
7325 static int lfs_rmentry(int argc, char **argv)
7326 {
7327         char *dname;
7328         int index;
7329         int result = 0;
7330
7331         if (argc <= 1) {
7332                 fprintf(stderr, "error: %s: missing dirname\n",
7333                         argv[0]);
7334                 return CMD_HELP;
7335         }
7336
7337         index = 1;
7338         dname = argv[index];
7339         while (dname) {
7340                 int rc2;
7341
7342                 rc2 = llapi_direntry_remove(dname);
7343                 if (rc2) {
7344                         fprintf(stderr,
7345                                 "%s %s: remove dir entry '%s' failed: %s\n",
7346                                 progname, argv[0], dname, strerror(-rc2));
7347                         if (!result)
7348                                 result = rc2;
7349                 }
7350                 dname = argv[++index];
7351         }
7352         return result;
7353 }
7354
7355 static int lfs_unlink_foreign(int argc, char **argv)
7356 {
7357         char *name;
7358         int   index;
7359         int   result = 0;
7360
7361         if (argc <= 1) {
7362                 fprintf(stderr, "error: %s: missing pathname\n",
7363                         argv[0]);
7364                 return CMD_HELP;
7365         }
7366
7367         index = 1;
7368         name = argv[index];
7369         while (name != NULL) {
7370                 result = llapi_unlink_foreign(name);
7371                 if (result) {
7372                         fprintf(stderr,
7373                                 "error: %s: unlink foreign entry '%s' failed\n",
7374                                 argv[0], name);
7375                         break;
7376                 }
7377                 name = argv[++index];
7378         }
7379         return result;
7380 }
7381
7382 static int lfs_mv(int argc, char **argv)
7383 {
7384         struct lmv_user_md lmu = { LMV_USER_MAGIC };
7385         struct find_param param = {
7386                 .fp_max_depth = -1,
7387                 .fp_mdt_index = -1,
7388         };
7389         char *end;
7390         int c;
7391         int rc = 0;
7392         struct option long_opts[] = {
7393         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
7394         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
7395         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
7396         { .name = NULL } };
7397
7398         while ((c = getopt_long(argc, argv, "m:M:v", long_opts, NULL)) != -1) {
7399                 switch (c) {
7400 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
7401                 case 'M':
7402                         fprintf(stderr,
7403                                 "warning: '-M' deprecated, use '--mdt-index' or '-m' instead\n");
7404 #endif
7405                 case 'm':
7406                         errno = 0;
7407                         lmu.lum_stripe_offset = strtoul(optarg, &end, 0);
7408                         if (errno != 0 || *end != '\0' ||
7409                             lmu.lum_stripe_offset >= UINT32_MAX) {
7410                                 fprintf(stderr, "%s mv: bad MDT index '%s'\n",
7411                                         progname, optarg);
7412                                 return CMD_HELP;
7413                         }
7414                         break;
7415                 case 'v':
7416                         param.fp_verbose = VERBOSE_DETAIL;
7417                         break;
7418                 default:
7419                         fprintf(stderr, "%s mv: unrecognized option '%s'\n",
7420                                 progname, argv[optind - 1]);
7421                         return CMD_HELP;
7422                 }
7423         }
7424
7425         if (lmu.lum_stripe_offset == LMV_OFFSET_DEFAULT) {
7426                 fprintf(stderr, "%s mv: MDT index must be specified\n",
7427                         progname);
7428                 return CMD_HELP;
7429         }
7430
7431         if (optind >= argc) {
7432                 fprintf(stderr, "%s mv: DIR must be specified\n", progname);
7433                 return CMD_HELP;
7434         }
7435
7436         lmu.lum_hash_type = LMV_HASH_TYPE_UNKNOWN;
7437
7438         /* initialize migrate mdt parameters */
7439         param.fp_lmv_md = &lmu;
7440         param.fp_migrate = 1;
7441         rc = llapi_migrate_mdt(argv[optind], &param);
7442         if (rc != 0)
7443                 fprintf(stderr, "%s mv: cannot migrate '%s' to MDT%04x: %s\n",
7444                         progname, argv[optind], lmu.lum_stripe_offset,
7445                         strerror(-rc));
7446         return rc;
7447 }
7448
7449 static int lfs_osts(int argc, char **argv)
7450 {
7451         return lfs_tgts(argc, argv);
7452 }
7453
7454 static int lfs_mdts(int argc, char **argv)
7455 {
7456         return lfs_tgts(argc, argv);
7457 }
7458
7459 static int lfs_df(int argc, char **argv)
7460 {
7461         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
7462         enum mntdf_flags flags = MNTDF_SHOW;
7463         int ops = LL_STATFS_LMV | LL_STATFS_LOV;
7464         int c, rc = 0, rc1 = 0, index = 0, arg_idx = 0;
7465         char fsname[PATH_MAX] = "", *pool_name = NULL;
7466         struct option long_opts[] = {
7467         { .val = 'h',   .name = "human-readable", .has_arg = no_argument },
7468         { .val = 'H',   .name = "si",           .has_arg = no_argument },
7469         { .val = 'i',   .name = "inodes",       .has_arg = no_argument },
7470         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
7471         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
7472         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
7473         { .name = NULL} };
7474
7475         while ((c = getopt_long(argc, argv, "hHilp:v", long_opts, NULL)) != -1) {
7476                 switch (c) {
7477                 case 'h':
7478                         flags = (flags & ~MNTDF_DECIMAL) | MNTDF_COOKED;
7479                         break;
7480                 case 'H':
7481                         flags |= MNTDF_COOKED | MNTDF_DECIMAL;
7482                         break;
7483                 case 'i':
7484                         flags |= MNTDF_INODES;
7485                         break;
7486                 case 'l':
7487                         flags |= MNTDF_LAZY;
7488                         break;
7489                 case 'p':
7490                         pool_name = optarg;
7491                         break;
7492                 case 'v':
7493                         flags |= MNTDF_VERBOSE;
7494                         break;
7495                 default:
7496                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7497                                 progname, argv[optind - 1]);
7498                         return CMD_HELP;
7499                 }
7500         }
7501
7502         /* Handle case where path is not specified */
7503         if (optind == argc) {
7504                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7505                         /* Check if we have a mount point */
7506                         if (mntdir[0] == '\0')
7507                                 continue;
7508
7509                         rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
7510                         if (rc || path[0] != '\0')
7511                                 break;
7512
7513                         fsname[0] = '\0'; /* avoid matching in next loop */
7514                         mntdir[0] = '\0'; /* avoid matching in next loop */
7515                         path[0] = '\0'; /* clean for next loop */
7516                 }
7517                 return rc;
7518         }
7519
7520         /* Loop through all the remaining arguments. These are Lustre FS
7521          * paths.
7522          */
7523         for (arg_idx = optind; arg_idx <= argc - 1; arg_idx++) {
7524                 bool valid = false;
7525
7526                 fsname[0] = '\0'; /* start clean */
7527                 mntdir[0] = '\0'; /* start clean */
7528                 path[0] = '\0';   /* start clean */
7529
7530                 /* path does not exists at all */
7531                 if (!realpath(argv[arg_idx], path)) {
7532                         rc = -errno;
7533                         fprintf(stderr, "error: invalid path '%s': %s\n",
7534                                 argv[arg_idx], strerror(-rc));
7535                         /* save first seen error */
7536                         if (!rc1)
7537                                 rc1 = rc;
7538
7539                         continue;
7540                 }
7541
7542                 /* path exists but may not be a Lustre filesystem */
7543                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7544                         /* Check if we have a mount point */
7545                         if (mntdir[0] == '\0')
7546                                 continue;
7547
7548                         rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
7549                         if (rc || path[0] != '\0') {
7550                                 valid = true;
7551
7552                                 /* save first seen error */
7553                                 if (!rc1)
7554                                         rc1 = rc;
7555                                 break;
7556                         }
7557                 }
7558
7559                 if (!valid) {
7560                         llapi_printf(LLAPI_MSG_ERROR,
7561                                      "%s:%s Not a Lustre filesystem\n",
7562                                      argv[0], argv[arg_idx]);
7563                         /* save first seen error */
7564                         if (!rc1)
7565                                 rc1 = -EOPNOTSUPP;
7566                 }
7567         }
7568
7569         return rc1;
7570 }
7571
7572 static int print_instance(const char *mntdir, char *buf, size_t buflen,
7573                           bool opt_instance, bool opt_fsname, bool opt_mntdir)
7574 {
7575         int rc = 0;
7576
7577         if (opt_fsname == opt_instance) { /* both true or both false */
7578                 rc = llapi_getname(mntdir, buf, buflen);
7579         } else if (opt_fsname) {
7580                 /*
7581                  * llapi_search_mounts() fills @buf with fsname, but that is not
7582                  * called if explicit paths are specified on the command-line
7583                  */
7584                 if (buf[0] == '\0')
7585                         rc = llapi_get_fsname(mntdir, buf, buflen);
7586         } else /* if (opt_instance) */ {
7587                 rc = llapi_get_instance(mntdir, buf, buflen);
7588         }
7589
7590         if (rc < 0) {
7591                 fprintf(stderr, "cannot get instance for '%s': %s\n",
7592                         mntdir, strerror(-rc));
7593                 return rc;
7594         }
7595
7596         if (opt_mntdir)
7597                 printf("%s %s\n", buf, mntdir);
7598         else
7599                 printf("%s\n", buf);
7600
7601         return 0;
7602 }
7603
7604 static int lfs_getname(int argc, char **argv)
7605 {
7606         struct option long_opts[] = {
7607         { .val = 'h',   .name = "help",         .has_arg = no_argument },
7608         { .val = 'i',   .name = "instance",     .has_arg = no_argument },
7609         { .val = 'n',   .name = "fsname",       .has_arg = no_argument },
7610         { .name = NULL} };
7611         bool opt_instance = false, opt_fsname = false;
7612         char fsname[PATH_MAX] = "";
7613         int rc = 0, rc2, c;
7614
7615         while ((c = getopt_long(argc, argv, "hin", long_opts, NULL)) != -1) {
7616                 switch (c) {
7617                 case 'i':
7618                         opt_instance = true;
7619                         break;
7620                 case 'n':
7621                         opt_fsname = true;
7622                         break;
7623                 default:
7624                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7625                                 progname, argv[optind - 1]);
7626                         fallthrough;
7627                 case 'h':
7628                         return CMD_HELP;
7629                 }
7630         }
7631
7632         if (optind == argc) { /* no paths specified, get all paths. */
7633                 char mntdir[PATH_MAX] = "", path[PATH_MAX] = "";
7634                 int index = 0;
7635
7636                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7637                         rc2 = print_instance(mntdir, fsname, sizeof(fsname),
7638                                              opt_instance, opt_fsname, true);
7639                         if (!rc)
7640                                 rc = rc2;
7641                         path[0] = fsname[0] = mntdir[0] = '\0';
7642                 }
7643         } else { /* paths specified, only attempt to search these. */
7644                 bool opt_mntdir;
7645
7646                 /* if only one path is given, print only requested info */
7647                 opt_mntdir = argc - optind > 1 || (opt_instance == opt_fsname);
7648
7649                 for (; optind < argc; optind++) {
7650                         rc2 = print_instance(argv[optind], fsname,
7651                                              sizeof(fsname), opt_instance,
7652                                              opt_fsname, opt_mntdir);
7653                         if (!rc)
7654                                 rc = rc2;
7655                         fsname[0] = '\0';
7656                 }
7657         }
7658
7659         return rc;
7660 }
7661
7662 static int lfs_check(int argc, char **argv)
7663 {
7664         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
7665         int num_types = 1;
7666         char *obd_types[3];
7667         char obd_type1[4];
7668         char obd_type2[4];
7669         char obd_type3[4];
7670         int rc;
7671
7672         if (argc < 2 || argc > 3) {
7673                 fprintf(stderr, "%s check: server type must be specified\n",
7674                         progname);
7675                 return CMD_HELP;
7676         }
7677
7678         obd_types[0] = obd_type1;
7679         obd_types[1] = obd_type2;
7680         obd_types[2] = obd_type3;
7681
7682         if (strcmp(argv[1], "osts") == 0) {
7683                 strcpy(obd_types[0], "osc");
7684         } else if (strcmp(argv[1], "mdts") == 0 ||
7685                    strcmp(argv[1], "mds") == 0) {
7686                 strcpy(obd_types[0], "mdc");
7687         } else if (strcmp(argv[1], "mgts") == 0) {
7688                 strcpy(obd_types[0], "mgc");
7689         } else if (strcmp(argv[1], "all") == 0 ||
7690                    strcmp(argv[1], "servers") == 0) {
7691                 num_types = 3;
7692                 strcpy(obd_types[0], "osc");
7693                 strcpy(obd_types[1], "mdc");
7694                 strcpy(obd_types[2], "mgc");
7695         } else {
7696                 fprintf(stderr, "%s check: unrecognized option '%s'\n",
7697                         progname, argv[1]);
7698                 return CMD_HELP;
7699         }
7700
7701         if (argc >= 3 && !realpath(argv[2], path)) {
7702                 rc = -errno;
7703                 fprintf(stderr, "error: invalid path '%s': %s\n",
7704                         argv[2], strerror(-rc));
7705                 return rc;
7706         }
7707
7708         rc = llapi_search_mounts(path, 0, mntdir, NULL);
7709         if (rc < 0 || mntdir[0] == '\0') {
7710                 fprintf(stderr,
7711                         "%s %s: cannot find mounted Lustre filesystem: %s\n",
7712                         progname, argv[0],
7713                         (rc < 0) ? strerror(-rc) : strerror(ENODEV));
7714                 return rc;
7715         }
7716
7717         rc = llapi_target_check(num_types, obd_types, path);
7718         if (rc)
7719                 fprintf(stderr, "%s %s: cannot check target '%s': %s\n",
7720                         progname, argv[0], argv[1], strerror(-rc));
7721
7722         return rc;
7723 }
7724
7725 #ifdef HAVE_SYS_QUOTA_H
7726 #define ADD_OVERFLOW(a, b) \
7727                      ((((a) + (b)) < (a)) ? \
7728                       ((a) = ULONG_MAX) : ((a) = (a) + (b)))
7729
7730 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
7731  * returns the value or ULONG_MAX on integer overflow or incorrect format
7732  * Notes:
7733  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
7734  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
7735  *        3. empty integer value is interpreted as 0
7736  */
7737 static unsigned long str2sec(const char *timestr)
7738 {
7739         const char spec[] = "smhdw";
7740         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
7741         unsigned long val = 0;
7742         char *tail;
7743
7744         if (strpbrk(timestr, spec) == NULL) {
7745                 /*
7746                  * no specifiers inside the time string,
7747                  * should treat it as an integer value
7748                  */
7749                 val = strtoul(timestr, &tail, 10);
7750                 return *tail ? ULONG_MAX : val;
7751         }
7752
7753         /* format string is XXwXXdXXhXXmXXs */
7754         while (*timestr) {
7755                 unsigned long v;
7756                 int ind;
7757                 char *ptr;
7758
7759                 v = strtoul(timestr, &tail, 10);
7760                 if (v == ULONG_MAX || *tail == '\0')
7761                         /*
7762                          * value too large (ULONG_MAX or more)
7763                          * or missing specifier
7764                          */
7765                         goto error;
7766
7767                 ptr = strchr(spec, *tail);
7768                 if (!ptr)
7769                         /* unknown specifier */
7770                         goto error;
7771
7772                 ind = ptr - spec;
7773
7774                 /* check if product will overflow the type */
7775                 if (!(v < ULONG_MAX / mult[ind]))
7776                         goto error;
7777
7778                 ADD_OVERFLOW(val, mult[ind] * v);
7779                 if (val == ULONG_MAX)
7780                         goto error;
7781
7782                 timestr = tail + 1;
7783         }
7784
7785         return val;
7786
7787 error:
7788         return ULONG_MAX;
7789 }
7790
7791 #define ARG2ULL(nr, str, def_units)                                     \
7792 do {                                                                    \
7793         unsigned long long limit, units = def_units;                    \
7794         int rc;                                                         \
7795                                                                         \
7796         rc = llapi_parse_size(str, &limit, &units, 1);                  \
7797         if (rc < 0) {                                                   \
7798                 fprintf(stderr, "%s: invalid limit '%s'\n",             \
7799                         progname, str);                                 \
7800                 return CMD_HELP;                                        \
7801         }                                                               \
7802         nr = limit;                                                     \
7803 } while (0)
7804
7805 static inline int has_times_option(int argc, char **argv)
7806 {
7807         int i;
7808
7809         for (i = 1; i < argc; i++)
7810                 if (!strcmp(argv[i], "-t"))
7811                         return 1;
7812
7813         return 0;
7814 }
7815
7816 static inline int lfs_verify_poolarg(char *pool)
7817 {
7818         if (strnlen(optarg, LOV_MAXPOOLNAME + 1) > LOV_MAXPOOLNAME) {
7819                 fprintf(stderr,
7820                         "Pool name '%.*s' is longer than %d\n",
7821                         LOV_MAXPOOLNAME, pool, LOV_MAXPOOLNAME);
7822                 return 1;
7823         }
7824         return 0;
7825 }
7826
7827 /* special grace time, only notify the user when its quota is over soft limit
7828  * but doesn't block new writes until the hard limit is reached.
7829  */
7830 #define NOTIFY_GRACE            "notify"
7831 #define NOTIFY_GRACE_TIME       LQUOTA_GRACE_MASK
7832
7833 #ifndef toqb
7834 static inline __u64 lustre_stoqb(size_t space)
7835 {
7836         return (space + QIF_DQBLKSIZE - 1) >> QIF_DQBLKSIZE_BITS;
7837 }
7838 #else
7839 #define lustre_stoqb   toqb
7840 #endif
7841
7842 int lfs_setquota_times(int argc, char **argv, struct if_quotactl *qctl)
7843 {
7844         int c, rc;
7845         char *mnt, *obd_type = (char *)qctl->obd_type;
7846         struct obd_dqblk *dqb = &qctl->qc_dqblk;
7847         struct obd_dqinfo *dqi = &qctl->qc_dqinfo;
7848         struct option long_opts[] = {
7849         { .val = 'b',   .name = "block-grace",  .has_arg = required_argument },
7850         { .val = 'g',   .name = "group",        .has_arg = no_argument },
7851         { .val = 'h',   .name = "help",         .has_arg = no_argument },
7852         { .val = 'i',   .name = "inode-grace",  .has_arg = required_argument },
7853         { .val = 'p',   .name = "projid",       .has_arg = no_argument },
7854         { .val = 't',   .name = "times",        .has_arg = no_argument },
7855         { .val = 'u',   .name = "user",         .has_arg = no_argument },
7856         { .val = LFS_POOL_OPT,
7857                         .name = "pool",         .has_arg = required_argument },
7858         { .name = NULL } };
7859         int qtype;
7860
7861         qctl->qc_cmd  = LUSTRE_Q_SETINFO;
7862         qctl->qc_type = ALLQUOTA;
7863
7864         while ((c = getopt_long(argc, argv, "b:ghi:ptu",
7865                                 long_opts, NULL)) != -1) {
7866                 switch (c) {
7867                 case 'u':
7868                         qtype = USRQUOTA;
7869                         goto quota_type;
7870                 case 'g':
7871                         qtype = GRPQUOTA;
7872                         goto quota_type;
7873                 case 'p':
7874                         qtype = PRJQUOTA;
7875 quota_type:
7876                         if (qctl->qc_type != ALLQUOTA) {
7877                                 fprintf(stderr,
7878                                         "%s: -u/g/p cannot be used more than once\n",
7879                                         progname);
7880                                 return CMD_HELP;
7881                         }
7882                         qctl->qc_type = qtype;
7883                         break;
7884                 case 'b':
7885                         if (strncmp(optarg, NOTIFY_GRACE,
7886                                     strlen(NOTIFY_GRACE)) == 0) {
7887                                 dqi->dqi_bgrace = NOTIFY_GRACE_TIME;
7888                         } else {
7889                                 dqi->dqi_bgrace = str2sec(optarg);
7890                                 if (dqi->dqi_bgrace >= NOTIFY_GRACE_TIME) {
7891                                         fprintf(stderr,
7892                                                 "%s: bad block-grace: %s\n",
7893                                                 progname, optarg);
7894                                         return CMD_HELP;
7895                                 }
7896                         }
7897                         dqb->dqb_valid |= QIF_BTIME;
7898                         break;
7899                 case 'i':
7900                         if (strncmp(optarg, NOTIFY_GRACE,
7901                                     strlen(NOTIFY_GRACE)) == 0) {
7902                                 dqi->dqi_igrace = NOTIFY_GRACE_TIME;
7903                         } else {
7904                                 dqi->dqi_igrace = str2sec(optarg);
7905                                 if (dqi->dqi_igrace >= NOTIFY_GRACE_TIME) {
7906                                         fprintf(stderr,
7907                                                 "%s: bad inode-grace: %s\n",
7908                                                 progname, optarg);
7909                                         return CMD_HELP;
7910                                 }
7911                         }
7912                         dqb->dqb_valid |= QIF_ITIME;
7913                         break;
7914                 case 't': /* Yes, of course! */
7915                         break;
7916                 case LFS_POOL_OPT:
7917                         if (lfs_verify_poolarg(optarg))
7918                                 return -1;
7919                         strncpy(qctl->qc_poolname, optarg, LOV_MAXPOOLNAME);
7920                         qctl->qc_cmd  = LUSTRE_Q_SETINFOPOOL;
7921                         break;
7922                 /* getopt prints error message for us when opterr != 0 */
7923                 default:
7924                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7925                                 progname, argv[optind - 1]);
7926                         fallthrough;
7927                 case 'h':
7928                         return CMD_HELP;
7929                 }
7930         }
7931
7932         if (qctl->qc_type == ALLQUOTA) {
7933                 fprintf(stderr, "%s: neither -u, -g nor -p specified\n",
7934                         progname);
7935                 return CMD_HELP;
7936         }
7937
7938         if (optind != argc - 1) {
7939                 fprintf(stderr, "%s: unexpected parameter '%s'\n",
7940                         progname, argv[optind + 1]);
7941                 return CMD_HELP;
7942         }
7943
7944         mnt = argv[optind];
7945         rc = llapi_quotactl(mnt, qctl);
7946         if (rc) {
7947                 if (*obd_type)
7948                         fprintf(stderr, "%s %s ", obd_type,
7949                                 obd_uuid2str(&qctl->obd_uuid));
7950                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
7951                 return rc;
7952         }
7953
7954         return 0;
7955 }
7956
7957 static int lfs_reset_quota(char *mnt, struct if_quotactl *qctl)
7958 {
7959         struct if_quotactl tmp_qctl;
7960         int index, md_count, dt_count;
7961         int wait_phase = 0, wait_index = 0, wait_count = 0;
7962         int rc, rc2;
7963
7964         /* reset the quota ID, the existing quota setting will be returned */
7965         rc = llapi_quotactl(mnt, qctl);
7966         if (rc)
7967                 return rc;
7968
7969         /* sanity check */
7970         if ((qctl->qc_dqblk.dqb_valid & QIF_LIMITS) != QIF_LIMITS) {
7971                 fprintf(stderr,
7972                         "the existing quota settings are not returned!\n");
7973                 return -EINVAL;
7974         }
7975
7976         rc = llapi_get_obd_count(mnt, &md_count, 1);
7977         if (rc) {
7978                 fprintf(stderr, "can not get mdt count: %s\n", strerror(-rc));
7979                 return rc;
7980         }
7981
7982         rc = llapi_get_obd_count(mnt, &dt_count, 0);
7983         if (rc) {
7984                 fprintf(stderr, "can not get ost count: %s\n", strerror(-rc));
7985                 return rc;
7986         }
7987
7988         memset(&tmp_qctl, 0, sizeof(tmp_qctl));
7989         tmp_qctl.qc_type = qctl->qc_type;
7990         tmp_qctl.qc_id = qctl->qc_id;
7991         tmp_qctl.qc_cmd = LUSTRE_Q_GETQUOTA;
7992
7993 retry:
7994         if (wait_phase == 0) {
7995                 for (index = wait_index; index < md_count; index++) {
7996                         tmp_qctl.qc_idx = index;
7997                         tmp_qctl.qc_valid = QC_MDTIDX;
7998                         rc = llapi_quotactl(mnt, &tmp_qctl);
7999                         if (rc == -ENODEV || rc == -ENODATA)
8000                                 continue;
8001                         if (rc) {
8002                                 fprintf(stderr, "quotactl mdt%d failed: %s\n",
8003                                         index, strerror(-rc));
8004                                 break;
8005                         }
8006                         /* check whether the md quota grant is reset */
8007                         if (tmp_qctl.qc_dqblk.dqb_valid & QIF_LIMITS &&
8008                             tmp_qctl.qc_dqblk.dqb_ihardlimit != 0)
8009                                 break;
8010                 }
8011
8012                 if (index < md_count) {
8013                         wait_phase = 0;
8014                         wait_index = index;
8015                         goto wait;
8016                 }
8017         } else {
8018                 for (index = wait_index; index < dt_count; index++) {
8019                         tmp_qctl.qc_idx = index;
8020                         tmp_qctl.qc_valid = QC_OSTIDX;
8021                         rc = llapi_quotactl(mnt, &tmp_qctl);
8022                         if (rc == -ENODEV || rc == -ENODATA)
8023                                 continue;
8024                         if (rc) {
8025                                 fprintf(stderr, "quotactl mdt%d failed: %s\n",
8026                                         index, strerror(-rc));
8027                                 break;
8028                         }
8029                         /* check whether the dt quota grant is reset */
8030                         if (tmp_qctl.qc_dqblk.dqb_valid & QIF_LIMITS &&
8031                             tmp_qctl.qc_dqblk.dqb_bhardlimit != 0)
8032                                 break;
8033                 }
8034
8035                 if (index < dt_count) {
8036                         wait_phase = 1;
8037                         wait_index = index;
8038                         goto wait;
8039                 }
8040         }
8041
8042         if (wait_phase == 0) {
8043                 wait_phase = 1;
8044                 goto retry;
8045         }
8046
8047         goto out;
8048
8049 wait:
8050         if (rc || wait_count > 30) {
8051                 fprintf(stderr, "fail to reset the quota ID %d on OBDs\n",
8052                         qctl->qc_id);
8053                 goto out;
8054         }
8055
8056         wait_count++;
8057         sleep(1);
8058         fprintf(stdout, "wait %d seconds for OBDs to reset the quota ID %u\n",
8059                 wait_count, qctl->qc_id);
8060         goto retry;
8061
8062
8063 out:
8064         /* restore the quota setting */
8065         if (qctl->qc_dqblk.dqb_isoftlimit == 0 &&
8066             qctl->qc_dqblk.dqb_ihardlimit == 0 &&
8067             qctl->qc_dqblk.dqb_bsoftlimit == 0 &&
8068             qctl->qc_dqblk.dqb_bhardlimit == 0)
8069                 return rc;
8070
8071         memcpy(&tmp_qctl, qctl, sizeof(tmp_qctl));
8072         tmp_qctl.qc_cmd = LUSTRE_Q_SETQUOTA;
8073         rc2 = llapi_quotactl(mnt, &tmp_qctl);
8074         if (!rc2)
8075                 return rc;
8076
8077         fprintf(stderr,
8078                 "fail to restore the quota setting: %s, please restore it manually by\n  lfs setquota %s %d",
8079                 strerror(-rc2),
8080                 qctl->qc_type == USRQUOTA ? "-u" :
8081                                 (qctl->qc_type == GRPQUOTA ? "-g" : "-p"),
8082                 qctl->qc_id);
8083
8084         if (qctl->qc_dqblk.dqb_isoftlimit != 0)
8085                 fprintf(stderr, " -i %llu",
8086                         (unsigned long long)qctl->qc_dqblk.dqb_isoftlimit);
8087         if (qctl->qc_dqblk.dqb_ihardlimit != 0)
8088                 fprintf(stderr, " -I %llu",
8089                         (unsigned long long)qctl->qc_dqblk.dqb_ihardlimit);
8090         if (qctl->qc_dqblk.dqb_bsoftlimit != 0)
8091                 fprintf(stderr, " -b %llu",
8092                         (unsigned long long)qctl->qc_dqblk.dqb_bsoftlimit);
8093         if (qctl->qc_dqblk.dqb_bhardlimit != 0)
8094                 fprintf(stderr, " -B %llu",
8095                         (unsigned long long)qctl->qc_dqblk.dqb_bhardlimit);
8096
8097         fprintf(stderr, " %s\n", mnt);
8098         if (!rc)
8099                 rc = rc2;
8100
8101         return rc;
8102 }
8103
8104 #define BSLIMIT (1 << 0)
8105 #define BHLIMIT (1 << 1)
8106 #define ISLIMIT (1 << 2)
8107 #define IHLIMIT (1 << 3)
8108
8109 int lfs_setquota(int argc, char **argv)
8110 {
8111         int c, rc = 0;
8112         struct if_quotactl *qctl;
8113         char *mnt, *obd_type;
8114         struct obd_dqblk *dqb;
8115         struct option long_opts[] = {
8116         { .val = 'b',   .name = "block-softlimit",
8117                                                 .has_arg = required_argument },
8118         { .val = 'B',   .name = "block-hardlimit",
8119                                                 .has_arg = required_argument },
8120         { .val = 'd',   .name = "default",      .has_arg = no_argument },
8121         { .val = LFS_SETQUOTA_DELETE,
8122                         .name = "delete",       .has_arg = no_argument },
8123         { .val = 'g',   .name = "group",        .has_arg = required_argument },
8124         { .val = 'G',   .name = "default-grp",  .has_arg = no_argument },
8125         { .val = 'h',   .name = "help",         .has_arg = no_argument },
8126         { .val = 'i',   .name = "inode-softlimit",
8127                                                 .has_arg = required_argument },
8128         { .val = 'I',   .name = "inode-hardlimit",
8129                                                 .has_arg = required_argument },
8130         { .val = 'p',   .name = "projid",       .has_arg = required_argument },
8131         { .val = 'P',   .name = "default-prj",  .has_arg = no_argument },
8132         { .val = 'r',   .name = "reset",        .has_arg = no_argument },
8133         { .val = 'u',   .name = "user",         .has_arg = required_argument },
8134         { .val = 'U',   .name = "default-usr",  .has_arg = no_argument },
8135         { .val = LFS_POOL_OPT,
8136                         .name = "pool",         .has_arg = required_argument },
8137         { .name = NULL } };
8138         unsigned int limit_mask = 0;
8139         bool use_default = false;
8140         int qtype, qctl_len;
8141
8142         qctl_len = sizeof(*qctl) + LOV_MAXPOOLNAME + 1;
8143         qctl = malloc(qctl_len);
8144         if (!qctl)
8145                 return -ENOMEM;
8146
8147         memset(qctl, 0, qctl_len);
8148         obd_type = (char *)qctl->obd_type;
8149         dqb = &qctl->qc_dqblk;
8150
8151         if (has_times_option(argc, argv)) {
8152                 rc = lfs_setquota_times(argc, argv, qctl);
8153                 goto out;
8154         }
8155
8156         qctl->qc_cmd  = LUSTRE_Q_SETQUOTA;
8157         qctl->qc_type = ALLQUOTA; /* ALLQUOTA makes no sense for setquota,
8158                                    * so it can be used as a marker that qc_type
8159                                    * isn't reinitialized from command line
8160                                    */
8161         while ((c = getopt_long(argc, argv, "b:B:dDg:Ghi:I:p:Pru:U",
8162                 long_opts, NULL)) != -1) {
8163                 switch (c) {
8164                 case 'U':
8165                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
8166                         qtype = USRQUOTA;
8167                         qctl->qc_id = 0;
8168                         goto quota_type_def;
8169                 case 'u':
8170                         qtype = USRQUOTA;
8171                         rc = name2uid(&qctl->qc_id, optarg);
8172                         goto quota_type;
8173                 case 'G':
8174                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
8175                         qtype = GRPQUOTA;
8176                         qctl->qc_id = 0;
8177                         goto quota_type_def;
8178                 case 'g':
8179                         qtype = GRPQUOTA;
8180                         rc = name2gid(&qctl->qc_id, optarg);
8181                         goto quota_type;
8182                 case 'P':
8183                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
8184                         qtype = PRJQUOTA;
8185                         qctl->qc_id = 0;
8186                         goto quota_type_def;
8187                 case 'p':
8188                         qtype = PRJQUOTA;
8189                         rc = name2projid(&qctl->qc_id, optarg);
8190 quota_type:
8191                         if (rc) {
8192                                 if (str2quotaid(&qctl->qc_id, optarg)) {
8193                                         fprintf(stderr,
8194                                                 "%s setquota: invalid id '%s'\n",
8195                                                 progname, optarg);
8196                                         rc = -1;
8197                                         goto out;
8198                                 }
8199                         }
8200
8201                         if (qctl->qc_id == 0) {
8202                                 fprintf(stderr,
8203                                         "%s setquota: can't set quota for root usr/group/project.\n",
8204                                         progname);
8205                                 rc = -1;
8206                                 goto out;
8207                         }
8208
8209 quota_type_def:
8210                         if (qctl->qc_type != ALLQUOTA) {
8211                                 fprintf(stderr,
8212                                         "%s setquota: only one of -u, -U, -g, -G, -p or -P may be specified\n",
8213                                         progname);
8214                                 rc = CMD_HELP;
8215                                 goto out;
8216                         }
8217                         qctl->qc_type = qtype;
8218                         break;
8219 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
8220                 case 'd':
8221                         fprintf(stderr,
8222                                 "%s setquota: '-d' deprecated, use '-D' or '--default'\n",
8223                                 progname);
8224                         fallthrough;
8225 #endif
8226                 case 'D':
8227                         use_default = true;
8228                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
8229                         break;
8230                 case LFS_SETQUOTA_DELETE:
8231                         qctl->qc_cmd = LUSTRE_Q_DELETEQID;
8232                         break;
8233                 case 'b':
8234                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
8235                         dqb->dqb_bsoftlimit >>= 10;
8236                         limit_mask |= BSLIMIT;
8237                         if (dqb->dqb_bsoftlimit &&
8238                             dqb->dqb_bsoftlimit <= 1024) /* <= 1M? */
8239                                 fprintf(stderr,
8240                                         "%s setquota: warning: block softlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
8241                                         progname,
8242                                         (unsigned long long)dqb->dqb_bsoftlimit,
8243                                         progname);
8244                         break;
8245                 case 'B':
8246                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
8247                         dqb->dqb_bhardlimit >>= 10;
8248                         limit_mask |= BHLIMIT;
8249                         if (dqb->dqb_bhardlimit &&
8250                             dqb->dqb_bhardlimit <= 1024) /* <= 1M? */
8251                                 fprintf(stderr,
8252                                         "%s setquota: warning: block hardlimit '%llu' smaller than minimum qunit size\n"
8253                                         "See '%s help setquota' or Lustre manual for details\n",
8254                                         progname,
8255                                         (unsigned long long)dqb->dqb_bhardlimit,
8256                                         progname);
8257                         break;
8258                 case 'i':
8259                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
8260                         limit_mask |= ISLIMIT;
8261                         if (dqb->dqb_isoftlimit &&
8262                             dqb->dqb_isoftlimit <= 1024) /* <= 1K inodes? */
8263                                 fprintf(stderr,
8264                                         "%s setquota: warning: inode softlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
8265                                         progname,
8266                                         (unsigned long long)dqb->dqb_isoftlimit,
8267                                         progname);
8268                         break;
8269                 case 'I':
8270                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
8271                         limit_mask |= IHLIMIT;
8272                         if (dqb->dqb_ihardlimit &&
8273                             dqb->dqb_ihardlimit <= 1024) /* <= 1K inodes? */
8274                                 fprintf(stderr,
8275                                         "%s setquota: warning: inode hardlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
8276                                         progname,
8277                                         (unsigned long long)dqb->dqb_ihardlimit,
8278                                         progname);
8279                         break;
8280                 case LFS_POOL_OPT:
8281                         if (lfs_verify_poolarg(optarg)) {
8282                                 rc = -1;
8283                                 goto out;
8284                         }
8285                         strncpy(qctl->qc_poolname, optarg, LOV_MAXPOOLNAME);
8286                         qctl->qc_cmd = qctl->qc_cmd == LUSTRE_Q_SETDEFAULT ?
8287                                                 LUSTRE_Q_SETDEFAULT_POOL :
8288                                                 LUSTRE_Q_SETQUOTAPOOL;
8289                         break;
8290                 case 'r':
8291                         qctl->qc_cmd = LUSTRE_Q_RESETQID;
8292                         break;
8293                 default:
8294                         fprintf(stderr,
8295                                 "%s setquota: unrecognized option '%s'\n",
8296                                 progname, argv[optind - 1]);
8297                         fallthrough;
8298                 case 'h':
8299                         rc = CMD_HELP;
8300                         goto out;
8301                 }
8302         }
8303
8304         if (qctl->qc_type == ALLQUOTA) {
8305                 fprintf(stderr,
8306                         "%s setquota: either -u or -g must be specified\n",
8307                         progname);
8308                 rc = CMD_HELP;
8309                 goto out;
8310         }
8311
8312         if (!use_default && qctl->qc_cmd != LUSTRE_Q_DELETEQID &&
8313             qctl->qc_cmd != LUSTRE_Q_RESETQID && limit_mask == 0) {
8314                 fprintf(stderr,
8315                         "%s setquota: at least one limit must be specified\n",
8316                         progname);
8317                 rc = CMD_HELP;
8318                 goto out;
8319         }
8320
8321         if ((use_default || qctl->qc_cmd == LUSTRE_Q_DELETEQID ||
8322              qctl->qc_cmd == LUSTRE_Q_RESETQID) && limit_mask != 0) {
8323                 fprintf(stderr,
8324                         "%s setquota: limits should not be specified when using default quota, deleting or resetting quota ID\n",
8325                         progname);
8326                 rc = CMD_HELP;
8327                 goto out;
8328         }
8329
8330         if (use_default && qctl->qc_id == 0) {
8331                 fprintf(stderr,
8332                         "%s setquota: can not set default quota for root user/group/project\n",
8333                         progname);
8334                 rc = CMD_HELP;
8335                 goto out;
8336         }
8337
8338         if ((qctl->qc_cmd == LUSTRE_Q_DELETEQID ||
8339              qctl->qc_cmd == LUSTRE_Q_RESETQID)  && qctl->qc_id == 0) {
8340                 fprintf(stderr,
8341                         "%s setquota: can not delete or reset root user/group/project\n",
8342                         progname);
8343                 rc = CMD_HELP;
8344                 goto out;
8345         }
8346
8347         if (optind != argc - 1) {
8348                 fprintf(stderr,
8349                         "%s setquota: filesystem not specified or unexpected argument '%s'\n",
8350                         progname, argv[optind]);
8351                 rc = CMD_HELP;
8352                 goto out;
8353         }
8354
8355         mnt = argv[optind];
8356
8357         if (use_default) {
8358                 dqb->dqb_bhardlimit = 0;
8359                 dqb->dqb_bsoftlimit = 0;
8360                 dqb->dqb_ihardlimit = 0;
8361                 dqb->dqb_isoftlimit = 0;
8362                 dqb->dqb_itime = 0;
8363                 dqb->dqb_btime = 0;
8364                 dqb->dqb_valid |= QIF_LIMITS | QIF_TIMES;
8365                 /* do not set inode limits for Pool Quotas */
8366                 if (qctl->qc_cmd  == LUSTRE_Q_SETDEFAULT_POOL)
8367                         dqb->dqb_valid ^= QIF_ILIMITS | QIF_ITIME;
8368         } else if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
8369                    (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
8370                 /* sigh, we can't just set blimits/ilimits */
8371                 struct if_quotactl *tmp_qctl;
8372
8373                 tmp_qctl = calloc(1, sizeof(*qctl) + LOV_MAXPOOLNAME + 1);
8374                 if (!tmp_qctl)
8375                         goto out;
8376
8377                 if (qctl->qc_cmd == LUSTRE_Q_SETQUOTAPOOL) {
8378                         tmp_qctl->qc_cmd = LUSTRE_Q_GETQUOTAPOOL;
8379                         strncpy(tmp_qctl->qc_poolname, qctl->qc_poolname,
8380                                 LOV_MAXPOOLNAME);
8381                 } else {
8382                         tmp_qctl->qc_cmd  = LUSTRE_Q_GETQUOTA;
8383                 }
8384                 tmp_qctl->qc_type = qctl->qc_type;
8385                 tmp_qctl->qc_id = qctl->qc_id;
8386
8387                 rc = llapi_quotactl(mnt, tmp_qctl);
8388                 if (rc < 0) {
8389                         free(tmp_qctl);
8390                         goto out;
8391                 }
8392
8393                 if (!(limit_mask & BHLIMIT))
8394                         dqb->dqb_bhardlimit = tmp_qctl->qc_dqblk.dqb_bhardlimit;
8395                 if (!(limit_mask & BSLIMIT))
8396                         dqb->dqb_bsoftlimit = tmp_qctl->qc_dqblk.dqb_bsoftlimit;
8397                 if (!(limit_mask & IHLIMIT))
8398                         dqb->dqb_ihardlimit = tmp_qctl->qc_dqblk.dqb_ihardlimit;
8399                 if (!(limit_mask & ISLIMIT))
8400                         dqb->dqb_isoftlimit = tmp_qctl->qc_dqblk.dqb_isoftlimit;
8401
8402                 /* Keep grace times if we have got no softlimit arguments */
8403                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
8404                         dqb->dqb_valid |= QIF_BTIME;
8405                         dqb->dqb_btime = tmp_qctl->qc_dqblk.dqb_btime;
8406                 }
8407
8408                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
8409                         dqb->dqb_valid |= QIF_ITIME;
8410                         dqb->dqb_itime = tmp_qctl->qc_dqblk.dqb_itime;
8411                 }
8412                 free(tmp_qctl);
8413         }
8414
8415         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
8416         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
8417
8418         if (qctl->qc_cmd == LUSTRE_Q_RESETQID)
8419                 rc = lfs_reset_quota(mnt, qctl);
8420         else
8421                 rc = llapi_quotactl(mnt, qctl);
8422
8423         if (rc) {
8424                 if (*obd_type)
8425                         fprintf(stderr,
8426                                 "%s setquota: cannot quotactl '%s' '%s': %s\n",
8427                                 progname, obd_type,
8428                                 obd_uuid2str(&qctl->obd_uuid), strerror(-rc));
8429                 else
8430                         fprintf(stderr,
8431                                 "%s setquota: quotactl failed: %s\n",
8432                                 progname, strerror(-rc));
8433         }
8434 out:
8435         if (rc)
8436                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
8437
8438         free(qctl);
8439         return rc;
8440 }
8441
8442 /* Converts seconds value into format string
8443  * result is returned in buf
8444  * Notes:
8445  *        1. result is in descenting order: 1w2d3h4m5s
8446  *        2. zero fields are not filled (except for p. 3): 5d1s
8447  *        3. zero seconds value is presented as "0s"
8448  */
8449 static char *__sec2str(time_t seconds, char *buf)
8450 {
8451         const char spec[] = "smhdw";
8452         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
8453         unsigned long c;
8454         char *tail = buf;
8455         int i;
8456
8457         for (i = ARRAY_SIZE(mult) - 1 ; i >= 0; i--) {
8458                 c = seconds / mult[i];
8459
8460                 if (c > 0 || (i == 0 && buf == tail))
8461                         tail += scnprintf(tail, 40-(tail-buf), "%lu%c", c,
8462                                           spec[i]);
8463
8464                 seconds %= mult[i];
8465         }
8466
8467         return tail;
8468 }
8469
8470 static void sec2str(time_t seconds, char *buf, int rc)
8471 {
8472         char *tail = buf;
8473
8474         if (rc)
8475                 *tail++ = '[';
8476
8477         tail = __sec2str(seconds, tail);
8478
8479         if (rc && tail - buf < 39) {
8480                 *tail++ = ']';
8481                 *tail++ = 0;
8482         }
8483 }
8484
8485 static void diff2str(time_t seconds, char *buf, time_t now)
8486 {
8487         buf[0] = 0;
8488         if (!seconds)
8489                 return;
8490         if (seconds <= now) {
8491                 strcpy(buf, "expired");
8492                 return;
8493         }
8494         __sec2str(seconds - now, buf);
8495 }
8496
8497 static void print_quota_title(char *name, struct if_quotactl *qctl,
8498                               bool human_readable, bool show_default)
8499 {
8500         if (show_default) {
8501                 printf("Disk default %s quota:\n", qtype_name(qctl->qc_type));
8502                 printf("%15s %8s%8s%8s %8s%8s%8s\n",
8503                        "Filesystem", "bquota", "blimit", "bgrace",
8504                        "iquota", "ilimit", "igrace");
8505         } else {
8506                 printf("Disk quotas for %s %s (%cid %u):\n",
8507                        qtype_name(qctl->qc_type), name,
8508                        *qtype_name(qctl->qc_type), qctl->qc_id);
8509                 printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
8510                        "Filesystem", human_readable ? "used" : "kbytes",
8511                        "quota", "limit", "grace",
8512                        "files", "quota", "limit", "grace");
8513         }
8514 }
8515
8516 static void kbytes2str(__u64 num, char *buf, int buflen, bool h)
8517 {
8518         if (!h) {
8519                 snprintf(buf, buflen, "%ju", (uintmax_t)num);
8520         } else {
8521                 if (num >> 40)
8522                         snprintf(buf, buflen, "%5.4gP",
8523                                  (double)num / ((__u64)1 << 40));
8524                 else if (num >> 30)
8525                         snprintf(buf, buflen, "%5.4gT",
8526                                  (double)num / (1 << 30));
8527                 else if (num >> 20)
8528                         snprintf(buf, buflen, "%5.4gG",
8529                                  (double)num / (1 << 20));
8530                 else if (num >> 10)
8531                         snprintf(buf, buflen, "%5.4gM",
8532                                  (double)num / (1 << 10));
8533                 else
8534                         snprintf(buf, buflen, "%ju%s", (uintmax_t)num, "k");
8535         }
8536 }
8537
8538 #ifdef HAVE_NATIVE_CLIENT
8539 /* In the current Lustre implementation, the grace time is either the time
8540  * or the timestamp to be used after some quota ID exceeds the soft limt,
8541  * 48 bits should be enough, its high 16 bits can be used as quota flags.
8542  */
8543 #define LQUOTA_GRACE_BITS       48
8544 #define LQUOTA_GRACE_MASK       ((1ULL << LQUOTA_GRACE_BITS) - 1)
8545 #define LQUOTA_GRACE_MAX        LQUOTA_GRACE_MASK
8546 #define LQUOTA_GRACE(t)         (t & LQUOTA_GRACE_MASK)
8547 #define LQUOTA_FLAG(t)          (t >> LQUOTA_GRACE_BITS)
8548 #define LQUOTA_GRACE_FLAG(t, f) ((__u64)t | (__u64)f << LQUOTA_GRACE_BITS)
8549 #endif
8550
8551 #define STRBUF_LEN      24
8552 static void print_quota(char *mnt, struct if_quotactl *qctl, int type,
8553                         int rc, bool h, bool show_default)
8554 {
8555         time_t now;
8556
8557         time(&now);
8558
8559         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA ||
8560             qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ||
8561             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT ||
8562             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT_POOL) {
8563                 int bover = 0, iover = 0;
8564                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
8565                 char numbuf[3][STRBUF_LEN + 2]; /* 2 for brackets or wildcard */
8566                 char timebuf[40];
8567                 char strbuf[STRBUF_LEN];
8568
8569                 dqb->dqb_btime &= LQUOTA_GRACE_MASK;
8570                 dqb->dqb_itime &= LQUOTA_GRACE_MASK;
8571
8572                 if (dqb->dqb_bhardlimit &&
8573                     lustre_stoqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
8574                         bover = 1;
8575                 } else if (dqb->dqb_bsoftlimit && dqb->dqb_btime) {
8576                         if (dqb->dqb_btime > now)
8577                                 bover = 2;
8578                         else
8579                                 bover = 3;
8580                 }
8581
8582                 if (dqb->dqb_ihardlimit &&
8583                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
8584                         iover = 1;
8585                 } else if (dqb->dqb_isoftlimit && dqb->dqb_itime) {
8586                         if (dqb->dqb_itime > now)
8587                                 iover = 2;
8588                         else
8589                                 iover = 3;
8590                 }
8591
8592                 if (strlen(mnt) > 15)
8593                         printf("%s\n%15s", mnt, "");
8594                 else
8595                         printf("%15s", mnt);
8596
8597                 if (show_default)
8598                         snprintf(timebuf, sizeof(timebuf), "%llu",
8599                                  (unsigned long long)dqb->dqb_btime);
8600                 else if (bover)
8601                         diff2str(dqb->dqb_btime, timebuf, now);
8602
8603                 kbytes2str(lustre_stoqb(dqb->dqb_curspace),
8604                            strbuf, sizeof(strbuf), h);
8605                 if (rc == -EREMOTEIO)
8606                         sprintf(numbuf[0], "%s*", strbuf);
8607                 else
8608                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
8609                                 "%s" : "[%s]", strbuf);
8610
8611                 kbytes2str(dqb->dqb_bsoftlimit, strbuf, sizeof(strbuf), h);
8612                 if (type == QC_GENERAL)
8613                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS) ?
8614                                 "%s" : "[%s]", strbuf);
8615                 else
8616                         sprintf(numbuf[1], "%s", "-");
8617
8618                 kbytes2str(dqb->dqb_bhardlimit, strbuf, sizeof(strbuf), h);
8619                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS) ?
8620                         "%s" : "[%s]", strbuf);
8621
8622                 if (show_default)
8623                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
8624                 else
8625                         printf(" %7s%c %6s %7s %7s",
8626                                numbuf[0], bover ? '*' : ' ', numbuf[1],
8627                                numbuf[2], bover > 1 ? timebuf : "-");
8628
8629                 if (show_default)
8630                         snprintf(timebuf, sizeof(timebuf), "%llu",
8631                                  (unsigned long long)dqb->dqb_itime);
8632                 else if (iover)
8633                         diff2str(dqb->dqb_itime, timebuf, now);
8634
8635                 snprintf(numbuf[0], sizeof(numbuf),
8636                          (dqb->dqb_valid & QIF_INODES) ? "%ju" : "[%ju]",
8637                          (uintmax_t)dqb->dqb_curinodes);
8638
8639                 if (type == QC_GENERAL)
8640                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS) ?
8641                                 "%ju" : "[%ju]",
8642                                 (uintmax_t)dqb->dqb_isoftlimit);
8643                 else
8644                         sprintf(numbuf[1], "%s", "-");
8645
8646                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
8647                         "%ju" : "[%ju]", (uintmax_t)dqb->dqb_ihardlimit);
8648
8649                 if (show_default)
8650                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
8651                 else if (type != QC_OSTIDX)
8652                         printf(" %7s%c %6s %7s %7s",
8653                                numbuf[0], iover ? '*' : ' ', numbuf[1],
8654                                numbuf[2], iover > 1 ? timebuf : "-");
8655                 else
8656                         printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
8657                 printf("\n");
8658         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO ||
8659                    qctl->qc_cmd == LUSTRE_Q_GETINFOPOOL ||
8660                    qctl->qc_cmd == Q_GETOINFO) {
8661                 char bgtimebuf[40];
8662                 char igtimebuf[40];
8663
8664                 if (qctl->qc_dqinfo.dqi_bgrace == NOTIFY_GRACE_TIME)
8665                         strncpy(bgtimebuf, NOTIFY_GRACE, 40);
8666                 else
8667                         sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
8668                 if (qctl->qc_dqinfo.dqi_igrace == NOTIFY_GRACE_TIME)
8669                         strncpy(igtimebuf, NOTIFY_GRACE, 40);
8670                 else
8671                         sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
8672
8673                 printf("Block grace time: %s; Inode grace time: %s\n",
8674                        bgtimebuf, igtimebuf);
8675         }
8676 }
8677
8678 static int tgt_name2index(const char *tgtname, unsigned int *idx)
8679 {
8680         char *dash, *endp;
8681
8682         /* format is "lustre-OST0001" */
8683         dash = memchr(tgtname, '-', LUSTRE_MAXFSNAME + 1);
8684         if (!dash) {
8685                 fprintf(stderr, "wrong tgtname format '%s'\n", tgtname);
8686                 return -EINVAL;
8687         }
8688         dash += 4;
8689
8690         *idx = strtoul(dash, &endp, 16);
8691         if (*idx > 0xffff) {
8692                 fprintf(stderr, "wrong index %s\n", tgtname);
8693                 return -ERANGE;
8694         }
8695
8696         return 0;
8697 }
8698
8699 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt,
8700                            bool h, __u64 *total)
8701 {
8702         int rc = 0, rc1 = 0, count = 0, i = 0;
8703         char **list = NULL, *buffer = NULL;
8704         __u32 valid = qctl->qc_valid;
8705
8706         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL && is_mdt)
8707                 return 0;
8708
8709         /* Is it correct for the case OST0000, OST0002, OST0003 -
8710          * we will ask OST0001 that is absent and won't ask OST0003? */
8711         rc = llapi_get_obd_count(mnt, &count, is_mdt);
8712         if (rc) {
8713                 fprintf(stderr, "can not get %s count: %s\n",
8714                         is_mdt ? "mdt" : "ost", strerror(-rc));
8715                 return rc;
8716         }
8717
8718         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8719                 char fname[PATH_MAX];
8720                 char fsname[LUSTRE_MAXFSNAME + 1];
8721                 int bufsize = sizeof(struct obd_uuid) * count;
8722
8723                 rc = llapi_search_fsname(mnt, fsname);
8724                 if (rc) {
8725                         fprintf(stderr, "cannot get fsname for mountpoint %s\n",
8726                                 mnt);
8727                         goto out;
8728                 }
8729                 buffer = malloc(bufsize + sizeof(*list) * count);
8730                 if (!buffer)
8731                         return -ENOMEM;
8732                 list = (char **)(buffer + bufsize);
8733                 snprintf(fname, PATH_MAX, "%s.%s", fsname, qctl->qc_poolname);
8734                 count = llapi_get_poolmembers(fname, list, count,
8735                                               buffer, bufsize);
8736                 if (count <= 0)
8737                         goto out;
8738         }
8739
8740         for (i = 0; i < count; i++) {
8741                 if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8742                         unsigned int index;
8743
8744                         if (tgt_name2index(list[i], &index))
8745                                 continue;
8746                         qctl->qc_idx = index;
8747                 } else {
8748                         qctl->qc_idx = i;
8749                 }
8750
8751                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
8752                 rc = llapi_quotactl(mnt, qctl);
8753                 if (rc) {
8754                         /* It is remote client case. */
8755                         if (rc == -EOPNOTSUPP) {
8756                                 rc = 0;
8757                                 goto out;
8758                         }
8759
8760                         /* no target for this index yet */
8761                         if (rc == -ENODEV) {
8762                                 rc = 0;
8763                                 continue;
8764                         }
8765
8766                         /* inactive target */
8767                         if (rc == -ENODATA) {
8768                                 char name[UUID_MAX+8];
8769
8770                                 snprintf(name, sizeof(name), "%s[inact]",
8771                                         obd_uuid2str(&qctl->obd_uuid));
8772                                 memset(&qctl->qc_dqinfo, 0,
8773                                        sizeof(qctl->qc_dqinfo));
8774                                 memset(&qctl->qc_dqblk, 0,
8775                                        sizeof(qctl->qc_dqblk));
8776                                 print_quota(name, qctl, qctl->qc_valid, 0, h,
8777                                             false);
8778                                 rc = 0;
8779                                 continue;
8780                         }
8781
8782                         if (!rc1)
8783                                 rc1 = rc;
8784                         fprintf(stderr, "quotactl %s%d failed.\n",
8785                                 is_mdt ? "mdt" : "ost", qctl->qc_idx);
8786                         continue;
8787                 }
8788
8789                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl,
8790                             qctl->qc_valid, 0, h, false);
8791                 *total += is_mdt ? qctl->qc_dqblk.dqb_ihardlimit :
8792                                    qctl->qc_dqblk.dqb_bhardlimit;
8793         }
8794 out:
8795         if (buffer)
8796                 free(buffer);
8797         qctl->qc_valid = valid;
8798         return rc ? : rc1;
8799 }
8800
8801 static int get_print_quota(char *mnt, char *name, struct if_quotactl *qctl,
8802                            int verbose, int quiet, bool human_readable,
8803                            bool show_default)
8804 {
8805         int rc1 = 0, rc2 = 0, rc3 = 0;
8806         char *obd_type = (char *)qctl->obd_type;
8807         char *obd_uuid = (char *)qctl->obd_uuid.uuid;
8808         __u64 total_ialloc = 0, total_balloc = 0;
8809         bool use_default_for_blk = false;
8810         bool use_default_for_file = false;
8811         int inacc;
8812
8813         rc1 = llapi_quotactl(mnt, qctl);
8814         if (rc1 < 0) {
8815                 switch (rc1) {
8816                 case -ESRCH:
8817                         fprintf(stderr, "%s quotas are not enabled.\n",
8818                                 qtype_name(qctl->qc_type));
8819                         goto out;
8820                 case -EPERM:
8821                         fprintf(stderr, "Permission denied.\n");
8822                 case -ENODEV:
8823                 case -ENOENT:
8824                         /* We already got error message. */
8825                         goto out;
8826                 default:
8827                         fprintf(stderr, "Unexpected quotactl error: %s\n",
8828                                 strerror(-rc1));
8829                 }
8830         }
8831
8832         if (!show_default && qctl->qc_id == 0) {
8833                 qctl->qc_dqblk.dqb_bhardlimit = 0;
8834                 qctl->qc_dqblk.dqb_bsoftlimit = 0;
8835                 qctl->qc_dqblk.dqb_ihardlimit = 0;
8836                 qctl->qc_dqblk.dqb_isoftlimit = 0;
8837                 qctl->qc_dqblk.dqb_btime = 0;
8838                 qctl->qc_dqblk.dqb_itime = 0;
8839                 qctl->qc_dqblk.dqb_valid |= QIF_LIMITS | QIF_TIMES;
8840         }
8841
8842         if (qctl->qc_dqblk.dqb_valid & QIF_BTIME &&
8843             LQUOTA_FLAG(qctl->qc_dqblk.dqb_btime) & LQUOTA_FLAG_DEFAULT) {
8844                 use_default_for_blk = true;
8845                 qctl->qc_dqblk.dqb_btime &= LQUOTA_GRACE_MASK;
8846         }
8847
8848         if (qctl->qc_dqblk.dqb_valid & QIF_ITIME &&
8849             LQUOTA_FLAG(qctl->qc_dqblk.dqb_itime) & LQUOTA_FLAG_DEFAULT) {
8850                 use_default_for_file = true;
8851                 qctl->qc_dqblk.dqb_itime &= LQUOTA_GRACE_MASK;
8852         }
8853
8854         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8855              qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ||
8856              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT_POOL ||
8857              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) && !quiet)
8858                 print_quota_title(name, qctl, human_readable, show_default);
8859
8860         if (rc1 && *obd_type)
8861                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
8862
8863         if (qctl->qc_valid != QC_GENERAL)
8864                 mnt = "";
8865
8866         inacc = (qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8867                  qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) &&
8868                 ((qctl->qc_dqblk.dqb_valid & (QIF_LIMITS|QIF_USAGE)) !=
8869                  (QIF_LIMITS|QIF_USAGE));
8870
8871         print_quota(mnt, qctl, QC_GENERAL, rc1, human_readable, show_default);
8872
8873         if (!show_default && verbose &&
8874             qctl->qc_valid == QC_GENERAL && qctl->qc_cmd != LUSTRE_Q_GETINFO &&
8875             qctl->qc_cmd != LUSTRE_Q_GETINFOPOOL) {
8876                 char strbuf[STRBUF_LEN];
8877
8878                 rc2 = print_obd_quota(mnt, qctl, 1, human_readable,
8879                                       &total_ialloc);
8880                 rc3 = print_obd_quota(mnt, qctl, 0, human_readable,
8881                                       &total_balloc);
8882                 kbytes2str(total_balloc, strbuf, sizeof(strbuf),
8883                            human_readable);
8884                 printf("Total allocated inode limit: %ju, total allocated block limit: %s\n",
8885                        (uintmax_t)total_ialloc, strbuf);
8886         }
8887
8888         if (use_default_for_blk)
8889                 printf("%cid %u is using default block quota setting\n",
8890                        *qtype_name(qctl->qc_type), qctl->qc_id);
8891
8892         if (use_default_for_file)
8893                 printf("%cid %u is using default file quota setting\n",
8894                        *qtype_name(qctl->qc_type), qctl->qc_id);
8895
8896         if (rc1 || rc2 || rc3 || inacc)
8897                 printf("Some errors happened when getting quota info. Some devices may be not working or deactivated. The data in \"[]\" is inaccurate.\n");
8898 out:
8899         if (rc1)
8900                 return rc1;
8901         if (rc2)
8902                 return rc2;
8903         if (rc3)
8904                 return rc3;
8905         if (inacc)
8906                 return -EIO;
8907
8908         return 0;
8909 }
8910
8911 static int lfs_project(int argc, char **argv)
8912 {
8913         int ret = 0, err = 0, c, i;
8914         struct project_handle_control phc = { 0 };
8915         enum lfs_project_ops_t op;
8916
8917         phc.newline = true;
8918         phc.assign_projid = false;
8919         /* default action */
8920         op = LFS_PROJECT_LIST;
8921
8922         while ((c = getopt(argc, argv, "p:cCsdkr0")) != -1) {
8923                 switch (c) {
8924                 case 'c':
8925                         if (op != LFS_PROJECT_LIST) {
8926                                 fprintf(stderr,
8927                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8928                                         progname);
8929                                 return CMD_HELP;
8930                         }
8931
8932                         op = LFS_PROJECT_CHECK;
8933                         break;
8934                 case 'C':
8935                         if (op != LFS_PROJECT_LIST) {
8936                                 fprintf(stderr,
8937                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8938                                         progname);
8939                                 return CMD_HELP;
8940                         }
8941
8942                         op = LFS_PROJECT_CLEAR;
8943                         break;
8944                 case 's':
8945                         if (op != LFS_PROJECT_LIST) {
8946                                 fprintf(stderr,
8947                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8948                                         progname);
8949                                 return CMD_HELP;
8950                         }
8951
8952                         phc.set_inherit = true;
8953                         op = LFS_PROJECT_SET;
8954                         break;
8955                 case 'd':
8956                         phc.dironly = true;
8957                         break;
8958                 case 'k':
8959                         phc.keep_projid = true;
8960                         break;
8961                 case 'r':
8962                         phc.recursive = true;
8963                         break;
8964                 case 'p':
8965                         if (str2quotaid(&phc.projid, optarg)) {
8966                                 fprintf(stderr,
8967                                         "Invalid project ID: %s\n",
8968                                         optarg);
8969                                 return CMD_HELP;
8970                         }
8971
8972                         phc.assign_projid = true;
8973
8974                         break;
8975                 case '0':
8976                         phc.newline = false;
8977                         break;
8978                 default:
8979                         fprintf(stderr, "%s: invalid option '%c'\n",
8980                                 progname, optopt);
8981                         return CMD_HELP;
8982                 }
8983         }
8984
8985         if (phc.assign_projid && op == LFS_PROJECT_LIST) {
8986                 op = LFS_PROJECT_SET;
8987                 phc.set_projid = true;
8988         } else if (phc.assign_projid && op == LFS_PROJECT_SET) {
8989                 phc.set_projid = true;
8990         }
8991
8992         switch (op) {
8993         case LFS_PROJECT_CHECK:
8994                 if (phc.keep_projid) {
8995                         fprintf(stderr,
8996                                 "%s: '-k' is useless together with '-c'\n",
8997                                 progname);
8998                         return CMD_HELP;
8999                 }
9000                 break;
9001         case LFS_PROJECT_CLEAR:
9002                 if (!phc.newline) {
9003                         fprintf(stderr,
9004                                 "%s: '-0' is useless together with '-C'\n",
9005                                 progname);
9006                         return CMD_HELP;
9007                 }
9008                 if (phc.assign_projid) {
9009                         fprintf(stderr,
9010                                 "%s: '-p' is useless together with '-C'\n",
9011                                 progname);
9012                         return CMD_HELP;
9013                 }
9014                 break;
9015         case LFS_PROJECT_SET:
9016                 if (!phc.newline) {
9017                         fprintf(stderr,
9018                                 "%s: '-0' is useless together with '-s'\n",
9019                                 progname);
9020                         return CMD_HELP;
9021                 }
9022                 if (phc.keep_projid) {
9023                         fprintf(stderr,
9024                                 "%s: '-k' is useless together with '-s'\n",
9025                                 progname);
9026                         return CMD_HELP;
9027                 }
9028                 break;
9029         default:
9030                 if (!phc.newline) {
9031                         fprintf(stderr,
9032                                 "%s: '-0' is useless for list operations\n",
9033                                 progname);
9034                         return CMD_HELP;
9035                 }
9036                 break;
9037         }
9038
9039         argv += optind;
9040         argc -= optind;
9041         if (argc == 0) {
9042                 fprintf(stderr, "%s: missing file or directory target(s)\n",
9043                         progname);
9044                 return CMD_HELP;
9045         }
9046
9047         for (i = 0; i < argc; i++) {
9048                 switch (op) {
9049                 case LFS_PROJECT_CHECK:
9050                         err = lfs_project_check(argv[i], &phc);
9051                         break;
9052                 case LFS_PROJECT_LIST:
9053                         err = lfs_project_list(argv[i], &phc);
9054                         break;
9055                 case LFS_PROJECT_CLEAR:
9056                         err = lfs_project_clear(argv[i], &phc);
9057                         break;
9058                 case LFS_PROJECT_SET:
9059                         err = lfs_project_set(argv[i], &phc);
9060                         break;
9061                 default:
9062                         break;
9063                 }
9064                 if (err && !ret)
9065                         ret = err;
9066         }
9067
9068         return ret;
9069 }
9070
9071 static int lfs_quota(int argc, char **argv)
9072 {
9073         int c;
9074         char *mnt, *name = NULL;
9075         struct if_quotactl *qctl;
9076         char *obd_uuid;
9077         int rc = 0, rc1 = 0, verbose = 0, quiet = 0;
9078         __u32 valid = QC_GENERAL, idx = 0;
9079         bool human_readable = false;
9080         bool show_default = false;
9081         int qtype;
9082         bool show_pools = false;
9083         struct option long_opts[] = {
9084         { .val = LFS_POOL_OPT, .name = "pool", .has_arg = optional_argument },
9085         { .name = NULL } };
9086         char **poollist = NULL;
9087         char *buf = NULL;
9088         int poolcount, i;
9089
9090         qctl = calloc(1, sizeof(*qctl) + LOV_MAXPOOLNAME + 1);
9091         if (!qctl)
9092                 return -ENOMEM;
9093
9094         qctl->qc_cmd = LUSTRE_Q_GETQUOTA;
9095         qctl->qc_type = ALLQUOTA;
9096         obd_uuid = (char *)qctl->obd_uuid.uuid;
9097
9098         while ((c = getopt_long(argc, argv, "gGi:I:o:pPqtuUvh",
9099                 long_opts, NULL)) != -1) {
9100                 switch (c) {
9101                 case 'U':
9102                         show_default = true;
9103                 case 'u':
9104                         qtype = USRQUOTA;
9105                         goto quota_type;
9106                 case 'G':
9107                         show_default = true;
9108                 case 'g':
9109                         qtype = GRPQUOTA;
9110                         goto quota_type;
9111                 case 'P':
9112                         show_default = true;
9113                 case 'p':
9114                         qtype = PRJQUOTA;
9115 quota_type:
9116                         if (qctl->qc_type != ALLQUOTA) {
9117                                 fprintf(stderr,
9118                                         "%s quota: only one of -u, -g, or -p may be specified\n",
9119                                         progname);
9120                                 rc = CMD_HELP;
9121                                 goto out;
9122                         }
9123                         qctl->qc_type = qtype;
9124                         break;
9125                 case 't':
9126                         qctl->qc_cmd = LUSTRE_Q_GETINFO;
9127                         break;
9128                 case 'o':
9129                         valid = qctl->qc_valid = QC_UUID;
9130                         snprintf(obd_uuid, sizeof(*obd_uuid), "%s", optarg);
9131                         break;
9132                 case 'i':
9133                         valid = qctl->qc_valid = QC_MDTIDX;
9134                         idx = qctl->qc_idx = atoi(optarg);
9135                         if (idx == 0 && *optarg != '0') {
9136                                 fprintf(stderr,
9137                                         "%s quota: invalid MDT index '%s'\n",
9138                                         progname, optarg);
9139                                 rc = CMD_HELP;
9140                                 goto out;
9141                         }
9142                         break;
9143                 case 'I':
9144                         valid = qctl->qc_valid = QC_OSTIDX;
9145                         idx = qctl->qc_idx = atoi(optarg);
9146                         if (idx == 0 && *optarg != '0') {
9147                                 fprintf(stderr,
9148                                         "%s quota: invalid OST index '%s'\n",
9149                                         progname, optarg);
9150                                 rc = CMD_HELP;
9151                                 goto out;
9152                         }
9153                         break;
9154                 case 'v':
9155                         verbose = 1;
9156                         break;
9157                 case 'q':
9158                         quiet = 1;
9159                         break;
9160                 case 'h':
9161                         human_readable = true;
9162                         break;
9163                 case LFS_POOL_OPT:
9164                         if ((!optarg) && (argv[optind] != NULL) &&
9165                                 (argv[optind][0] != '-') &&
9166                                 (argv[optind][0] != '/')) {
9167                                 optarg = argv[optind++];
9168                                 if (lfs_verify_poolarg(optarg)) {
9169                                         rc = -EINVAL;
9170                                         goto out;
9171                                 }
9172                                 strncpy(qctl->qc_poolname, optarg,
9173                                         LOV_MAXPOOLNAME);
9174                                 if (qctl->qc_cmd == LUSTRE_Q_GETINFO)
9175                                         qctl->qc_cmd = LUSTRE_Q_GETINFOPOOL;
9176                                 else
9177                                         qctl->qc_cmd = LUSTRE_Q_GETQUOTAPOOL;
9178                                 break;
9179                         }
9180
9181                         /* optarg is NULL */
9182                         show_pools = true;
9183                         qctl->qc_cmd = LUSTRE_Q_GETQUOTAPOOL;
9184                         break;
9185                 default:
9186                         fprintf(stderr, "%s quota: unrecognized option '%s'\n",
9187                                 progname, argv[optind - 1]);
9188                         rc = CMD_HELP;
9189                         goto out;
9190                 }
9191         }
9192
9193         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
9194         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
9195              qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) &&
9196              qctl->qc_type == ALLQUOTA &&
9197              optind == argc - 1 && !show_default) {
9198                 qctl->qc_idx = idx;
9199
9200                 for (qtype = USRQUOTA; qtype <= GRPQUOTA; qtype++) {
9201                         qctl->qc_type = qtype;
9202                         qctl->qc_valid = valid;
9203                         if (qtype == USRQUOTA) {
9204                                 qctl->qc_id = geteuid();
9205                                 rc = uid2name(&name, qctl->qc_id);
9206                         } else {
9207                                 qctl->qc_id = getegid();
9208                                 rc = gid2name(&name, qctl->qc_id);
9209                                 memset(&qctl->qc_dqblk, 0,
9210                                        sizeof(qctl->qc_dqblk));
9211                         }
9212                         if (rc)
9213                                 name = "<unknown>";
9214                         mnt = argv[optind];
9215                         rc1 = get_print_quota(mnt, name, qctl, verbose, quiet,
9216                                               human_readable, show_default);
9217                         if (rc1 && !rc)
9218                                 rc = rc1;
9219                 }
9220                 goto out;
9221         /* lfs quota -u username /path/to/lustre/mount */
9222         } else if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
9223                    qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
9224                 /* options should be followed by u/g-name and mntpoint */
9225                 if ((!show_default && optind + 2 != argc) ||
9226                     (show_default && optind + 1 != argc) ||
9227                     qctl->qc_type == ALLQUOTA) {
9228                         fprintf(stderr,
9229                                 "%s quota: name and mount point must be specified\n",
9230                                 progname);
9231                         rc = CMD_HELP;
9232                         goto out;
9233                 }
9234
9235                 if (!show_default) {
9236                         name = argv[optind++];
9237                         switch (qctl->qc_type) {
9238                         case USRQUOTA:
9239                                 rc = name2uid(&qctl->qc_id, name);
9240                                 break;
9241                         case GRPQUOTA:
9242                                 rc = name2gid(&qctl->qc_id, name);
9243                                 break;
9244                         case PRJQUOTA:
9245                                 rc = name2projid(&qctl->qc_id, name);
9246                                 break;
9247                         default:
9248                                 rc = -ENOTSUP;
9249                                 break;
9250                         }
9251                 } else {
9252                         qctl->qc_valid = QC_GENERAL;
9253                         qctl->qc_cmd = qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ?
9254                                         LUSTRE_Q_GETDEFAULT_POOL :
9255                                         LUSTRE_Q_GETDEFAULT;
9256                         qctl->qc_id = 0;
9257                 }
9258
9259                 if (rc) {
9260                         if (str2quotaid(&qctl->qc_id, name)) {
9261                                 fprintf(stderr, "%s quota: invalid id '%s'\n",
9262                                         progname, name);
9263                                 rc = CMD_HELP;
9264                                 goto out;
9265                         }
9266                 }
9267         } else if (optind + 1 != argc || qctl->qc_type == ALLQUOTA) {
9268                 fprintf(stderr, "%s quota: missing quota info argument(s)\n",
9269                         progname);
9270                 rc = CMD_HELP;
9271                 goto out;
9272         }
9273
9274         mnt = argv[optind];
9275         if (show_pools) {
9276                 char *p;
9277
9278                 i = 0;
9279                 rc = llapi_get_poolbuf(mnt, &buf, &poollist, &poolcount);
9280                 if (rc)
9281                         goto out;
9282
9283                 for (i = 0; i < poolcount; i++) {
9284                         p = memchr(poollist[i], '.', MAXNAMLEN);
9285                         if (!p) {
9286                                 fprintf(stderr, "bad string format %.*s\n",
9287                                         MAXNAMLEN, poollist[i]);
9288                                 rc = -EINVAL;
9289                                 goto out;
9290                         }
9291                         p++;
9292                         printf("Quotas for pool: %s\n", p);
9293                         strncpy(qctl->qc_poolname, p, LOV_MAXPOOLNAME);
9294                         rc = get_print_quota(mnt, name, qctl, verbose, quiet,
9295                                              human_readable, show_default);
9296                         if (rc)
9297                                 break;
9298                 }
9299                 goto out;
9300         }
9301
9302         rc = get_print_quota(mnt, name, qctl, verbose, quiet,
9303                              human_readable, show_default);
9304 out:
9305         free(buf);
9306         free(qctl);
9307         return rc;
9308 }
9309 #endif /* HAVE_SYS_QUOTA_H! */
9310
9311 static int flushctx_ioctl(char *mp)
9312 {
9313         int fd, rc;
9314
9315         fd = open(mp, O_RDONLY);
9316         if (fd == -1) {
9317                 fprintf(stderr, "flushctx: error open %s: %s\n",
9318                         mp, strerror(errno));
9319                 return -1;
9320         }
9321
9322         rc = ioctl(fd, LL_IOC_FLUSHCTX);
9323         if (rc == -1)
9324                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
9325                         mp, strerror(errno));
9326
9327         close(fd);
9328         return rc;
9329 }
9330
9331 static int lfs_flushctx(int argc, char **argv)
9332 {
9333         int     kdestroy = 0, reap = 0, c;
9334         char    mntdir[PATH_MAX] = {'\0'};
9335         int     index = 0;
9336         int     rc = 0;
9337
9338         while ((c = getopt(argc, argv, "kr")) != -1) {
9339                 switch (c) {
9340                 case 'k':
9341                         kdestroy = 1;
9342                         break;
9343                 case 'r':
9344                         reap = 1;
9345                         break;
9346                 default:
9347                         fprintf(stderr,
9348                                 "error: %s: option '-%c' unrecognized\n",
9349                                 argv[0], c);
9350                         return CMD_HELP;
9351                 }
9352         }
9353
9354         if (kdestroy) {
9355                 rc = system("kdestroy > /dev/null");
9356                 if (rc) {
9357                         rc = WEXITSTATUS(rc);
9358                         fprintf(stderr,
9359                                 "error destroying tickets: %d, continuing\n",
9360                                 rc);
9361                 }
9362         }
9363
9364         if (optind >= argc) {
9365                 /* flush for all mounted lustre fs. */
9366                 while (!llapi_search_mounts(NULL, index++, mntdir, NULL)) {
9367                         /* Check if we have a mount point */
9368                         if (mntdir[0] == '\0')
9369                                 continue;
9370
9371                         if (flushctx_ioctl(mntdir))
9372                                 rc = -1;
9373
9374                         mntdir[0] = '\0'; /* avoid matching in next loop */
9375                 }
9376         } else {
9377                 /* flush fs as specified */
9378                 while (optind < argc) {
9379                         if (flushctx_ioctl(argv[optind++]))
9380                                 rc = -1;
9381                 }
9382         }
9383
9384         if (reap) {
9385                 rc = system("keyctl reap > /dev/null");
9386                 if (rc != 0) {
9387                         rc = WEXITSTATUS(rc);
9388                         fprintf(stderr, "error reaping keyring: %d\n", rc);
9389                 }
9390         }
9391
9392         return rc;
9393 }
9394
9395 static int lfs_changelog(int argc, char **argv)
9396 {
9397         void *changelog_priv;
9398         struct changelog_rec *rec;
9399         long long startrec = 0, endrec = 0;
9400         char *mdd;
9401         struct option long_opts[] = {
9402                 { .val = 'f', .name = "follow", .has_arg = no_argument },
9403                 { .name = NULL } };
9404         char short_opts[] = "f";
9405         int rc, follow = 0;
9406
9407         while ((rc = getopt_long(argc, argv, short_opts,
9408                 long_opts, NULL)) != -1) {
9409                 switch (rc) {
9410                 case 'f':
9411                         follow++;
9412                         break;
9413                 default:
9414                         fprintf(stderr,
9415                                 "%s changelog: unrecognized option '%s'\n",
9416                                 progname, argv[optind - 1]);
9417                         return CMD_HELP;
9418                 }
9419         }
9420         if (optind >= argc) {
9421                 fprintf(stderr, "%s changelog: mdtname must be specified\n",
9422                         progname);
9423                 return CMD_HELP;
9424         }
9425
9426         mdd = argv[optind++];
9427         if (argc > optind) {
9428                 errno = 0;
9429                 startrec = strtoll(argv[optind++], NULL, 10);
9430                 if (errno != 0 || startrec < 0) {
9431                         fprintf(stderr,
9432                                 "%s changelog: bad startrec\n",
9433                                 progname);
9434                         return CMD_HELP;
9435                 }
9436         }
9437
9438         if (argc > optind) {
9439                 errno = 0;
9440                 endrec = strtoll(argv[optind++], NULL, 10);
9441                 if (errno != 0 || endrec < 0) {
9442                         fprintf(stderr,
9443                                 "%s changelog: bad endrec\n",
9444                                 progname);
9445                         return CMD_HELP;
9446                 }
9447         }
9448
9449         rc = llapi_changelog_start(&changelog_priv,
9450                                    CHANGELOG_FLAG_BLOCK |
9451                                    CHANGELOG_FLAG_JOBID |
9452                                    CHANGELOG_FLAG_EXTRA_FLAGS |
9453                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
9454                                    mdd, startrec);
9455         if (rc < 0) {
9456                 fprintf(stderr, "%s changelog: cannot start changelog: %s\n",
9457                         progname, strerror(errno = -rc));
9458                 return rc;
9459         }
9460
9461         rc = llapi_changelog_set_xflags(changelog_priv,
9462                                         CHANGELOG_EXTRA_FLAG_UIDGID |
9463                                         CHANGELOG_EXTRA_FLAG_NID |
9464                                         CHANGELOG_EXTRA_FLAG_OMODE |
9465                                         CHANGELOG_EXTRA_FLAG_XATTR);
9466         if (rc < 0) {
9467                 fprintf(stderr,
9468                         "%s changelog: cannot set xflags for changelog: %s\n",
9469                         progname, strerror(errno = -rc));
9470                 return rc;
9471         }
9472
9473         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
9474                 time_t secs;
9475                 struct tm ts;
9476
9477                 if (endrec && rec->cr_index > endrec) {
9478                         llapi_changelog_free(&rec);
9479                         break;
9480                 }
9481                 if (rec->cr_index < startrec) {
9482                         llapi_changelog_free(&rec);
9483                         continue;
9484                 }
9485
9486                 secs = rec->cr_time >> 30;
9487                 gmtime_r(&secs, &ts);
9488                 printf("%ju %02d%-5s %02d:%02d:%02d.%09d %04d.%02d.%02d "
9489                        "0x%x t="DFID, (uintmax_t)rec->cr_index, rec->cr_type,
9490                        changelog_type2str(rec->cr_type),
9491                        ts.tm_hour, ts.tm_min, ts.tm_sec,
9492                        (int)(rec->cr_time & ((1 << 30) - 1)),
9493                        ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday,
9494                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
9495
9496                 if (rec->cr_flags & CLF_JOBID) {
9497                         struct changelog_ext_jobid *jid =
9498                                 changelog_rec_jobid(rec);
9499
9500                         if (jid->cr_jobid[0] != '\0')
9501                                 printf(" j=%s", jid->cr_jobid);
9502                 }
9503
9504                 if (rec->cr_flags & CLF_EXTRA_FLAGS) {
9505                         struct changelog_ext_extra_flags *ef =
9506                                 changelog_rec_extra_flags(rec);
9507
9508                         printf(" ef=0x%llx",
9509                                (unsigned long long)ef->cr_extra_flags);
9510
9511                         if (ef->cr_extra_flags & CLFE_UIDGID) {
9512                                 struct changelog_ext_uidgid *uidgid =
9513                                         changelog_rec_uidgid(rec);
9514
9515                                 printf(" u=%llu:%llu",
9516                                        (unsigned long long)uidgid->cr_uid,
9517                                        (unsigned long long)uidgid->cr_gid);
9518                         }
9519                         if (ef->cr_extra_flags & CLFE_NID) {
9520                                 struct changelog_ext_nid *nid =
9521                                         changelog_rec_nid(rec);
9522
9523                                 printf(" nid=%s",
9524                                        libcfs_nid2str(nid->cr_nid));
9525                         }
9526
9527                         if (ef->cr_extra_flags & CLFE_OPEN) {
9528                                 struct changelog_ext_openmode *omd =
9529                                         changelog_rec_openmode(rec);
9530                                 char mode[] = "---";
9531
9532                                 /* exec mode must be exclusive */
9533                                 if (omd->cr_openflags & MDS_FMODE_EXEC) {
9534                                         mode[2] = 'x';
9535                                 } else {
9536                                         if (omd->cr_openflags & MDS_FMODE_READ)
9537                                                 mode[0] = 'r';
9538                                         if (omd->cr_openflags &
9539                                             (MDS_FMODE_WRITE |
9540                                              MDS_OPEN_TRUNC |
9541                                              MDS_OPEN_APPEND))
9542                                                 mode[1] = 'w';
9543                                 }
9544
9545                                 if (strcmp(mode, "---") != 0)
9546                                         printf(" m=%s", mode);
9547                         }
9548
9549                         if (ef->cr_extra_flags & CLFE_XATTR) {
9550                                 struct changelog_ext_xattr *xattr =
9551                                         changelog_rec_xattr(rec);
9552
9553                                 if (xattr->cr_xattr[0] != '\0')
9554                                         printf(" x=%s", xattr->cr_xattr);
9555                         }
9556                 }
9557
9558                 if (!fid_is_zero(&rec->cr_pfid))
9559                         printf(" p="DFID, PFID(&rec->cr_pfid));
9560                 if (rec->cr_namelen)
9561                         printf(" %.*s", rec->cr_namelen,
9562                                changelog_rec_name(rec));
9563
9564                 if (rec->cr_flags & CLF_RENAME) {
9565                         struct changelog_ext_rename *rnm =
9566                                 changelog_rec_rename(rec);
9567
9568                         if (!fid_is_zero(&rnm->cr_sfid))
9569                                 printf(" s="DFID" sp="DFID" %.*s",
9570                                        PFID(&rnm->cr_sfid),
9571                                        PFID(&rnm->cr_spfid),
9572                                        (int)changelog_rec_snamelen(rec),
9573                                        changelog_rec_sname(rec));
9574                 }
9575                 printf("\n");
9576
9577                 llapi_changelog_free(&rec);
9578         }
9579
9580         llapi_changelog_fini(&changelog_priv);
9581
9582         if (rc < 0)
9583                 fprintf(stderr, "%s changelog: cannot access changelog: %s\n",
9584                         progname, strerror(errno = -rc));
9585
9586         return (rc == 1 ? 0 : rc);
9587 }
9588
9589 static int lfs_changelog_clear(int argc, char **argv)
9590 {
9591         long long endrec;
9592         int rc;
9593
9594         if (argc != 4)
9595                 return CMD_HELP;
9596
9597         errno = 0;
9598         endrec = strtoll(argv[3], NULL, 10);
9599         if (errno != 0 || endrec < 0) {
9600                 fprintf(stderr,
9601                         "%s: bad endrec '%s'\n",
9602                         argv[0], argv[3]);
9603                 return CMD_HELP;
9604         }
9605
9606         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
9607
9608         if (rc == -EINVAL)
9609                 fprintf(stderr, "%s: record out of range: %llu\n",
9610                         argv[0], endrec);
9611         else if (rc == -ENOENT)
9612                 fprintf(stderr, "%s: no changelog user: %s\n",
9613                         argv[0], argv[2]);
9614         else if (rc)
9615                 fprintf(stderr, "%s error: %s\n", argv[0],
9616                         strerror(-rc));
9617
9618         if (rc)
9619                 errno = -rc;
9620
9621         return rc;
9622 }
9623
9624 static void rstripc(char *str, int c)
9625 {
9626         char *end = str + strlen(str);
9627
9628         for (; str < end && end[-1] == c; --end)
9629                 end[-1] = '\0';
9630 }
9631
9632 static int lfs_fid2path(int argc, char **argv)
9633 {
9634         struct option long_opts[] = {
9635                 { .val = '0',   .name = "print0",       .has_arg = no_argument },
9636                 { .val = 'c',   .name = "cur",  .has_arg = no_argument },
9637                 { .val = 'c',   .name = "current",      .has_arg = no_argument },
9638                 { .val = 'c',   .name = "print-link",   .has_arg = no_argument },
9639                 { .val = 'f',   .name = "print-fid",    .has_arg = no_argument },
9640                 { .val = 'l',   .name = "link", .has_arg = required_argument },
9641                 { .name = NULL } };
9642         char short_opts[] = "0cfl:pr:";
9643         bool print_link = false;
9644         bool print_fid = false;
9645         bool print_mnt_dir;
9646         char mnt_dir[PATH_MAX] = "";
9647         int mnt_fd = -1;
9648         char *path_or_fsname;
9649         long long recno = -1;
9650         int linkno = -1;
9651         char *endptr = NULL;
9652         char link_separator = '\n';
9653         int rc = 0;
9654         int c;
9655         int i;
9656
9657         while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
9658                 switch (c) {
9659                 case '0':
9660                         link_separator = '\0';
9661                         break;
9662                 case 'c':
9663                         print_link = true;
9664                         break;
9665                 case 'f':
9666                         print_fid = true;
9667                         break;
9668                 case 'l':
9669                         errno = 0;
9670                         linkno = strtol(optarg, &endptr, 10);
9671                         if (errno != 0 || *endptr != '\0' || linkno < 0) {
9672                                 fprintf(stderr,
9673                                         "%s fid2path: invalid linkno '%s'\n",
9674                                         progname, optarg);
9675                                 return CMD_HELP;
9676                         }
9677                         break;
9678                 case 'r':
9679                         /* recno is something to do with changelogs
9680                          * that was never implemented. We just pass it
9681                          * through for the MDT to ignore.
9682                          */
9683                         errno = 0;
9684                         recno = strtoll(optarg, &endptr, 10);
9685                         if (errno != 0 || *endptr != '\0' || recno < 0) {
9686                                 fprintf(stderr,
9687                                         "%s fid2path: invalid recno '%s'\n",
9688                                         progname, optarg);
9689                                 return CMD_HELP;
9690                         }
9691                         break;
9692                 default:
9693                         fprintf(stderr,
9694                                 "%s fid2path: unrecognized option '%s'\n",
9695                                 progname, argv[optind - 1]);
9696                         return CMD_HELP;
9697                 }
9698         }
9699
9700         if (argc - optind < 2) {
9701                 fprintf(stderr,
9702                         "Usage: %s fid2path FSNAME|ROOT FID...\n",
9703                         progname);
9704                 return CMD_HELP;
9705         }
9706
9707         path_or_fsname = argv[optind];
9708
9709         if (*path_or_fsname == '/') {
9710                 print_mnt_dir = true;
9711                 rc = llapi_search_mounts(path_or_fsname, 0, mnt_dir, NULL);
9712         } else {
9713                 print_mnt_dir = false;
9714                 rc = llapi_search_rootpath(mnt_dir, path_or_fsname);
9715         }
9716
9717         if (rc < 0) {
9718                 fprintf(stderr,
9719                         "%s fid2path: cannot resolve mount point for '%s': %s\n",
9720                         progname, path_or_fsname, strerror(-rc));
9721                 goto out;
9722         }
9723
9724         mnt_fd = open(mnt_dir, O_RDONLY | O_DIRECTORY);
9725         if (mnt_fd < 0) {
9726                 fprintf(stderr,
9727                         "%s fid2path: cannot open mount point for '%s': %s\n",
9728                         progname, path_or_fsname, strerror(-rc));
9729                 goto out;
9730         }
9731
9732         /* Strip trailing slashes from mnt_dir. */
9733         rstripc(mnt_dir + 1, '/');
9734
9735         for (i = optind + 1; i < argc; i++) {
9736                 const char *fid_str = argv[i];
9737                 struct lu_fid fid;
9738                 int rc2;
9739
9740                 rc2 = llapi_fid_parse(fid_str, &fid, NULL);
9741                 if (rc2 < 0) {
9742                         fprintf(stderr,
9743                                 "%s fid2path: invalid FID '%s'\n",
9744                                 progname, fid_str);
9745                         if (rc == 0)
9746                                 rc = rc2;
9747
9748                         continue;
9749                 }
9750
9751                 int linktmp = (linkno >= 0) ? linkno : 0;
9752                 while (1) {
9753                         int oldtmp = linktmp;
9754                         long long rectmp = recno;
9755                         char path_buf[PATH_MAX];
9756
9757                         rc2 = llapi_fid2path_at(mnt_fd, &fid,
9758                                 path_buf, sizeof(path_buf), &rectmp, &linktmp);
9759                         if (rc2 < 0) {
9760                                 fprintf(stderr,
9761                                         "%s fid2path: cannot find %s %s: %s\n",
9762                                         progname, path_or_fsname, fid_str,
9763                                         strerror(-rc2));
9764                                 if (rc == 0)
9765                                         rc = rc2;
9766                                 break;
9767                         }
9768
9769                         if (print_fid)
9770                                 printf("%s ", fid_str);
9771
9772                         if (print_link)
9773                                 printf("%d ", linktmp);
9774
9775                         /* You may think this looks wrong or weird (and it is!)
9776                          * but we are actually trying to preserve the old quirky
9777                          * behaviors (enforced by our old quirky tests!) that
9778                          * make lfs so much fun to work on:
9779                          *
9780                          *   lustre 0x200000007:0x1:0x0 => "/"
9781                          *   /mnt/lustre 0x200000007:0x1:0x0 => "/mnt/lustre//"
9782                          *
9783                          * Note that llapi_fid2path() returns "" for the root
9784                          * FID. */
9785
9786                         printf("%s%s%s%c",
9787                                print_mnt_dir ? mnt_dir : "",
9788                                (print_mnt_dir || *path_buf == '\0') ?
9789                                "/" : "", path_buf, link_separator);
9790
9791                         if (linkno >= 0)
9792                                 /* specified linkno */
9793                                 break;
9794
9795                         if (oldtmp == linktmp)
9796                                 /* no more links */
9797                                 break;
9798                 }
9799         }
9800 out:
9801         if (!(mnt_fd < 0))
9802                 close(mnt_fd);
9803
9804         return rc;
9805 }
9806
9807 static int lfs_path2fid(int argc, char **argv)
9808 {
9809         struct option long_opts[] = {
9810                 { .val = 'p', .name = "parents", .has_arg = no_argument },
9811                 { .name = NULL } };
9812         char            **path;
9813         const char        short_opts[] = "p";
9814         const char       *sep = "";
9815         struct lu_fid     fid;
9816         int               rc = 0;
9817         bool              show_parents = false;
9818
9819         while ((rc = getopt_long(argc, argv, short_opts,
9820                                  long_opts, NULL)) != -1) {
9821                 switch (rc) {
9822                 case 'p':
9823                         show_parents = true;
9824                         break;
9825                 default:
9826                         fprintf(stderr,
9827                                 "%s path2fid: unrecognized option '%s'\n",
9828                                 progname, argv[optind - 1]);
9829                         return CMD_HELP;
9830                 }
9831         }
9832
9833         if (optind > argc - 1) {
9834                 fprintf(stderr, "%s path2fid: FILE... must be specified\n",
9835                         progname);
9836                 return CMD_HELP;
9837         } else if (optind < argc - 1) {
9838                 sep = ": ";
9839         }
9840
9841         rc = 0;
9842         for (path = argv + optind; optind < argc; path++, optind++) {
9843                 int err = 0;
9844
9845                 if (!show_parents) {
9846                         err = llapi_path2fid(*path, &fid);
9847                         if (!err)
9848                                 printf("%s%s"DFID"\n",
9849                                        *sep != '\0' ? *path : "", sep,
9850                                        PFID(&fid));
9851                 } else {
9852                         char            name[NAME_MAX + 1];
9853                         unsigned int    linkno = 0;
9854
9855                         while ((err = llapi_path2parent(*path, linkno, &fid,
9856                                                 name, sizeof(name))) == 0) {
9857                                 if (*sep != '\0' && linkno == 0)
9858                                         printf("%s%s", *path, sep);
9859
9860                                 printf("%s"DFID"/%s", linkno != 0 ? "\t" : "",
9861                                        PFID(&fid), name);
9862                                 linkno++;
9863                         }
9864
9865                         /* err == -ENODATA is end-of-loop */
9866                         if (linkno > 0 && err == -ENODATA) {
9867                                 printf("\n");
9868                                 err = 0;
9869                         }
9870                 }
9871
9872                 if (err) {
9873                         fprintf(stderr,
9874                                 "%s path2fid: cannot get %sfid for '%s': %s\n",
9875                                 progname, show_parents ? "parent " : "", *path,
9876                                 strerror(-err));
9877                         if (rc == 0) {
9878                                 rc = err;
9879                                 errno = -err;
9880                         }
9881                 }
9882         }
9883
9884         return rc;
9885 }
9886
9887 #define MAX_ERRNO       4095
9888 #define IS_ERR_VALUE(x) ((unsigned long)(x) >= (unsigned long)-MAX_ERRNO)
9889
9890 static int lfs_rmfid_and_show_errors(int rootfd, struct fid_array *fa)
9891 {
9892         int rc, rc2, k;
9893
9894         rc = llapi_rmfid_at(rootfd, fa);
9895         if (rc < 0) {
9896                 fprintf(stderr, "%s rmfid: cannot remove FIDs: %s\n",
9897                         progname, strerror(-rc));
9898                 return rc;
9899         }
9900
9901         for (k = 0; k < fa->fa_nr; k++) {
9902                 rc2 = (__s32)fa->fa_fids[k].f_ver;
9903                 if (!IS_ERR_VALUE(rc2))
9904                         continue;
9905
9906                 if (rc == 0)
9907                         rc = rc2;
9908
9909                 fa->fa_fids[k].f_ver = 0;
9910                 fprintf(stderr, "%s rmfid: cannot remove "DFID": %s\n",
9911                         progname, PFID(&fa->fa_fids[k]), strerror(-rc2));
9912         }
9913
9914         return rc;
9915 }
9916
9917 static int lfs_rmfid(int argc, char **argv)
9918 {
9919         int rc = 0, rc2, rc3 = 0, nr;
9920         struct fid_array *fa;
9921         const char *device;
9922         char *fidstr;
9923         int rootfd;
9924
9925         /* Interactive mode: Adjust optind */
9926         if (!optind)
9927                 optind++;
9928
9929         device = argv[optind++];
9930
9931         if (optind > argc - 1) {
9932                 fprintf(stderr, "%s rmfid: missing dirname\n", progname);
9933                 return CMD_HELP;
9934         }
9935
9936         nr = argc - optind;
9937
9938         rc = llapi_root_path_open(device, &rootfd);
9939         if (rc < 0) {
9940                 fprintf(stderr,
9941                         "%s rmfid: error opening device/fsname '%s': %s\n",
9942                         progname, device, strerror(-rc));
9943                 return -rc;
9944         }
9945
9946         fa = malloc(offsetof(struct fid_array, fa_fids[nr + 1]));
9947         if (!fa) {
9948                 fprintf(stderr, "%s rmfid: error allocating %zd bytes: %s\n",
9949                         progname, offsetof(struct fid_array, fa_fids[nr + 1]),
9950                         strerror(errno));
9951                 return -ENOMEM;
9952         }
9953
9954         fa->fa_nr = 0;
9955         rc = 0;
9956         while (optind < argc) {
9957                 char *origfidstr;
9958                 int found;
9959
9960                 origfidstr = fidstr = argv[optind++];
9961                 while (*fidstr == '[')
9962                         fidstr++;
9963                 found = sscanf(fidstr, SFID, RFID(&fa->fa_fids[fa->fa_nr]));
9964                 if (found != 3) {
9965                         fprintf(stderr, "lfs rmfid: '%s': Wrong FID format\n",
9966                                 origfidstr);
9967                         if (!rc3)
9968                                 rc3 = -EINVAL; /* Invalid argument */
9969                         continue;
9970                 }
9971                 fa->fa_nr++;
9972                 if (fa->fa_nr == OBD_MAX_FIDS_IN_ARRAY) {
9973                         /* start another batch */
9974                         rc2 = lfs_rmfid_and_show_errors(rootfd, fa);
9975                         if (rc2 && !rc)
9976                                 rc = rc2;
9977                         if (rc3)
9978                                 rc = rc3;
9979                         fa->fa_nr = 0;
9980                 }
9981         }
9982         if (fa->fa_nr) {
9983                 rc2 = lfs_rmfid_and_show_errors(rootfd, fa);
9984                 if (rc2 && !rc)
9985                         rc = rc2;
9986                 if (rc3)
9987                         rc = rc3;
9988         }
9989
9990         if (fa) {
9991                 free(fa);
9992                 fa = NULL;
9993         }
9994
9995         close(rootfd);
9996         return rc;
9997 }
9998
9999 static int lfs_data_version(int argc, char **argv)
10000 {
10001         int data_version_flags = LL_DV_RD_FLUSH; /* Read by default */
10002         __u64 data_version;
10003         char *path;
10004         int fd;
10005         int rc;
10006         int c;
10007
10008         if (argc < 2) {
10009                 fprintf(stderr, "%s: FILE must be specified\n",
10010                         progname);
10011                 return CMD_HELP;
10012         }
10013
10014         while ((c = getopt(argc, argv, "hnrw")) != -1) {
10015                 switch (c) {
10016                 case 'n':
10017                         data_version_flags = 0;
10018                         break;
10019                 case 'r':
10020                         data_version_flags |= LL_DV_RD_FLUSH;
10021                         break;
10022                 case 'w':
10023                         data_version_flags |= LL_DV_WR_FLUSH;
10024                         break;
10025                 default:
10026                         fprintf(stderr,
10027                                 "%s data_version: unrecognized option '%s'\n",
10028                                 progname, argv[optind - 1]);
10029                         fallthrough;
10030                 case 'h':
10031                         return CMD_HELP;
10032                 }
10033         }
10034         if (optind == argc) {
10035                 fprintf(stderr, "%s data_version: FILE must be specified\n",
10036                         progname);
10037                 return CMD_HELP;
10038         }
10039
10040         path = argv[optind];
10041         fd = open(path, O_RDONLY);
10042         if (fd < 0) {
10043                 rc = -errno;
10044                 fprintf(stderr, "%s data_version: cannot open file '%s': %s\n",
10045                         progname, path, strerror(-rc));
10046                 return rc;
10047         }
10048
10049         rc = llapi_get_data_version(fd, &data_version, data_version_flags);
10050         if (rc < 0)
10051                 fprintf(stderr,
10052                         "%s data_version: cannot get version for '%s': %s\n",
10053                         progname, path, strerror(-rc));
10054         else
10055                 printf("%ju" "\n", (uintmax_t)data_version);
10056
10057         close(fd);
10058         return rc;
10059 }
10060
10061 static int lfs_hsm_state(int argc, char **argv)
10062 {
10063         int rc = 0;
10064         int i = 1;
10065         char *path;
10066         struct hsm_user_state hus;
10067
10068         if (argc < 2)
10069                 return CMD_HELP;
10070
10071         do {
10072                 int rc2;
10073                 path = argv[i];
10074
10075                 rc2 = llapi_hsm_state_get(path, &hus);
10076                 if (rc2) {
10077                         fprintf(stderr,
10078                                 "%s %s: get HSM state for '%s' failed: %s\n",
10079                                 progname, argv[0], path, strerror(-rc2));
10080                         if (!rc)
10081                                 rc = rc2;
10082                         continue;
10083                 }
10084
10085                 /* Display path name and status flags */
10086                 printf("%s: (0x%08x)", path, hus.hus_states);
10087
10088                 if (hus.hus_states & HS_RELEASED)
10089                         printf(" released");
10090                 if (hus.hus_states & HS_EXISTS)
10091                         printf(" exists");
10092                 if (hus.hus_states & HS_DIRTY)
10093                         printf(" dirty");
10094                 if (hus.hus_states & HS_ARCHIVED)
10095                         printf(" archived");
10096                 /* Display user-settable flags */
10097                 if (hus.hus_states & HS_NORELEASE)
10098                         printf(" never_release");
10099                 if (hus.hus_states & HS_NOARCHIVE)
10100                         printf(" never_archive");
10101                 if (hus.hus_states & HS_LOST)
10102                         printf(" lost_from_hsm");
10103
10104                 if (hus.hus_archive_id != 0)
10105                         printf(", archive_id:%d", hus.hus_archive_id);
10106                 printf("\n");
10107
10108         } while (++i < argc);
10109
10110         return rc;
10111 }
10112
10113 #define LFS_HSM_SET   0
10114 #define LFS_HSM_CLEAR 1
10115
10116 /**
10117  * Generic function to set or clear HSM flags.
10118  * Used by hsm_set and hsm_clear.
10119  *
10120  * @mode  if LFS_HSM_SET, set the flags, if LFS_HSM_CLEAR, clear the flags.
10121  */
10122 static int lfs_hsm_change_flags(int argc, char **argv, int mode)
10123 {
10124         struct option long_opts[] = {
10125         { .val = 'A',   .name = "archived",     .has_arg = no_argument },
10126         { .val = 'a',   .name = "noarchive",    .has_arg = no_argument },
10127         { .val = 'd',   .name = "dirty",        .has_arg = no_argument },
10128         { .val = 'e',   .name = "exists",       .has_arg = no_argument },
10129         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10130         { .val = 'i',   .name = "archive-id",   .has_arg = required_argument },
10131         { .val = 'l',   .name = "lost",         .has_arg = no_argument },
10132         { .val = 'r',   .name = "norelease",    .has_arg = no_argument },
10133         { .name = NULL } };
10134         __u64 mask = 0;
10135         int c, rc = 0;
10136         char *path;
10137         __u32 archive_id = 0;
10138         char *end = NULL;
10139
10140         if (argc < 3)
10141                 return CMD_HELP;
10142
10143         while ((c = getopt_long(argc, argv, "aAdehi:lr",
10144                                 long_opts, NULL)) != -1) {
10145                 switch (c) {
10146                 case 'l':
10147                         mask |= HS_LOST;
10148                         break;
10149                 case 'a':
10150                         mask |= HS_NOARCHIVE;
10151                         break;
10152                 case 'A':
10153                         mask |= HS_ARCHIVED;
10154                         break;
10155                 case 'r':
10156                         mask |= HS_NORELEASE;
10157                         break;
10158                 case 'd':
10159                         mask |= HS_DIRTY;
10160                         break;
10161                 case 'e':
10162                         mask |= HS_EXISTS;
10163                         break;
10164                 case 'i':
10165                         errno = 0;
10166                         archive_id = strtol(optarg, &end, 10);
10167                         if (errno != 0 || *end != '\0' || archive_id < 0) {
10168                                 fprintf(stderr,
10169                                         "%s: invalid archive_id: '%s'\n",
10170                                         progname, end);
10171                                 return CMD_HELP;
10172                         }
10173                         break;
10174                 default:
10175                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10176                                 progname, argv[optind - 1]);
10177                         fallthrough;
10178                 case 'h':
10179                         return CMD_HELP;
10180                 }
10181         }
10182
10183         /* User should have specified a flag */
10184         if (mask == 0)
10185                 return CMD_HELP;
10186
10187         while (optind < argc) {
10188                 int rc2;
10189                 path = argv[optind];
10190
10191                 /* If mode == 0, this means we apply the mask. */
10192                 if (mode == LFS_HSM_SET)
10193                         rc2 = llapi_hsm_state_set(path, mask, 0, archive_id);
10194                 else
10195                         rc2 = llapi_hsm_state_set(path, 0, mask, 0);
10196
10197                 if (rc2) {
10198                         fprintf(stderr,
10199                                 "%s %s: change hsm flags for '%s' failed: %s\n",
10200                                 progname, argv[0], path, strerror(-rc2));
10201                         if (!rc)
10202                                 rc = rc2;
10203                 }
10204                 optind++;
10205         }
10206
10207         return rc;
10208 }
10209
10210 static int lfs_hsm_action(int argc, char **argv)
10211 {
10212         struct hsm_current_action hca;
10213         struct hsm_extent he;
10214         enum hsm_user_action hua;
10215         enum hsm_progress_states hps;
10216         int rc = 0;
10217         int i = 1;
10218         char *path;
10219
10220         if (argc < 2)
10221                 return CMD_HELP;
10222
10223         do {
10224                 int rc2;
10225                 path = argv[i];
10226
10227                 rc2 = llapi_hsm_current_action(path, &hca);
10228                 if (rc2) {
10229                         fprintf(stderr,
10230                                 "%s %s: get hsm action for '%s' failed: %s\n",
10231                                 progname, argv[0], path, strerror(-rc2));
10232
10233                         if (!rc)
10234                                 rc = rc2;
10235                         continue;
10236                 }
10237                 he = hca.hca_location;
10238                 hua = hca.hca_action;
10239                 hps = hca.hca_state;
10240
10241                 printf("%s: %s", path, hsm_user_action2name(hua));
10242
10243                 /* Skip file without action */
10244                 if (hca.hca_action == HUA_NONE) {
10245                         printf("\n");
10246                         continue;
10247                 }
10248
10249                 printf(" %s ", hsm_progress_state2name(hps));
10250
10251                 if ((hps == HPS_RUNNING) &&
10252                     (hua == HUA_ARCHIVE || hua == HUA_RESTORE))
10253                         printf("(%llu bytes moved)\n",
10254                                (unsigned long long)he.length);
10255                 else if ((he.offset + he.length) == LUSTRE_EOF)
10256                         printf("(from %llu to EOF)\n",
10257                                (unsigned long long)he.offset);
10258                 else
10259                         printf("(from %llu to %llu)\n",
10260                                (unsigned long long)he.offset,
10261                                (unsigned long long)(he.offset + he.length));
10262
10263         } while (++i < argc);
10264
10265         return rc;
10266 }
10267
10268 static int lfs_hsm_set(int argc, char **argv)
10269 {
10270         return lfs_hsm_change_flags(argc, argv, LFS_HSM_SET);
10271 }
10272
10273 static int lfs_hsm_clear(int argc, char **argv)
10274 {
10275         return lfs_hsm_change_flags(argc, argv, LFS_HSM_CLEAR);
10276 }
10277
10278 /**
10279  * Check file state and return its fid, to be used by lfs_hsm_request().
10280  *
10281  * \param[in]     file      Path to file to check
10282  * \param[in,out] fid       Pointer to allocated lu_fid struct.
10283  * \param[in,out] last_dev  Pointer to last device id used.
10284  *
10285  * \return 0 on success.
10286  */
10287 static int lfs_hsm_prepare_file(const char *file, struct lu_fid *fid,
10288                                 dev_t *last_dev)
10289 {
10290         struct stat     st;
10291         int             rc;
10292
10293         rc = lstat(file, &st);
10294         if (rc) {
10295                 fprintf(stderr, "Cannot stat %s: %s\n", file, strerror(errno));
10296                 return -errno;
10297         }
10298         /*
10299          * Checking for regular file as archiving as posix copytool
10300          * rejects archiving files other than regular files
10301          */
10302         if (!S_ISREG(st.st_mode)) {
10303                 fprintf(stderr, "error: \"%s\" is not a regular file\n", file);
10304                 return CMD_HELP;
10305         }
10306         /* A request should be ... */
10307         if (*last_dev != st.st_dev && *last_dev != 0) {
10308                 fprintf(stderr,
10309                         "All files should be on the same filesystem: %s\n",
10310                         file);
10311                 return -EINVAL;
10312         }
10313         *last_dev = st.st_dev;
10314
10315         rc = llapi_path2fid(file, fid);
10316         if (rc) {
10317                 fprintf(stderr, "Cannot read FID of %s: %s\n",
10318                         file, strerror(-rc));
10319                 return rc;
10320         }
10321         return 0;
10322 }
10323
10324 /* Fill an HSM HUR item with a given file name.
10325  *
10326  * If mntpath is set, then the filename is actually a FID, and no
10327  * lookup on the filesystem will be performed.
10328  *
10329  * \param[in]  hur         the user request to fill
10330  * \param[in]  idx         index of the item inside the HUR to fill
10331  * \param[in]  mntpath     mountpoint of Lustre
10332  * \param[in]  fname       filename (if mtnpath is NULL)
10333  *                         or FID (if mntpath is set)
10334  * \param[in]  last_dev    pointer to last device id used
10335  *
10336  * \retval 0 on success
10337  * \retval CMD_HELP or a negative errno on error
10338  */
10339 static int fill_hur_item(struct hsm_user_request *hur, unsigned int idx,
10340                          const char *mntpath, const char *fname,
10341                          dev_t *last_dev)
10342 {
10343         struct hsm_user_item *hui = &hur->hur_user_item[idx];
10344         int rc;
10345
10346         hui->hui_extent.length = -1;
10347
10348         if (mntpath) {
10349                 rc = llapi_fid_parse(fname, &hui->hui_fid, NULL);
10350                 if (rc)
10351                         fprintf(stderr, "hsm: '%s' is not a valid FID\n",
10352                                 fname);
10353         } else {
10354                 rc = lfs_hsm_prepare_file(fname, &hui->hui_fid, last_dev);
10355         }
10356
10357         if (rc == 0)
10358                 hur->hur_request.hr_itemcount++;
10359
10360         return rc;
10361 }
10362
10363 static int lfs_hsm_request(int argc, char **argv, int action)
10364 {
10365         struct option long_opts[] = {
10366         { .val = 'a',   .name = "archive",      .has_arg = required_argument },
10367         { .val = 'D',   .name = "data",         .has_arg = required_argument },
10368         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10369         { .val = 'l',   .name = "filelist",     .has_arg = required_argument },
10370         { .val = 'm',   .name = "mntpath",      .has_arg = required_argument },
10371         { .name = NULL } };
10372         dev_t last_dev = 0;
10373         struct hsm_user_request *hur, *oldhur;
10374         int c, i;
10375         size_t len;
10376         int nbfile;
10377         char *line = NULL;
10378         char *filelist = NULL;
10379         char fullpath[PATH_MAX];
10380         char *opaque = NULL;
10381         int opaque_len = 0;
10382         int archive_id = 0;
10383         FILE *fp;
10384         int nbfile_alloc = 0;
10385         char *some_file = NULL;
10386         char *mntpath = NULL;
10387         int rc;
10388
10389         if (argc < 2)
10390                 return CMD_HELP;
10391
10392         while ((c = getopt_long(argc, argv, "a:D:hl:m:",
10393                                 long_opts, NULL)) != -1) {
10394                 switch (c) {
10395                 case 'l':
10396                         filelist = optarg;
10397                         break;
10398                 case 'D':
10399                         opaque = optarg;
10400                         break;
10401                 case 'a':
10402                         if (action != HUA_ARCHIVE &&
10403                             action != HUA_REMOVE) {
10404                                 fprintf(stderr,
10405                                         "error: -a is supported only when archiving or removing\n");
10406                                 return CMD_HELP;
10407                         }
10408                         archive_id = atoi(optarg);
10409                         break;
10410                 case 'm':
10411                         if (!some_file) {
10412                                 mntpath = optarg;
10413                                 some_file = strdup(optarg);
10414                         }
10415                         break;
10416                 default:
10417                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10418                                 progname, argv[optind - 1]);
10419                         fallthrough;
10420                 case 'h':
10421                         return CMD_HELP;
10422                 }
10423         }
10424
10425         /* All remaining args are files, so we have at least nbfile */
10426         nbfile = argc - optind;
10427
10428         if ((nbfile == 0) && (!filelist))
10429                 return CMD_HELP;
10430
10431         if (opaque)
10432                 opaque_len = strlen(opaque);
10433
10434         /*
10435          * Alloc the request structure with enough place to store all files
10436          * from command line.
10437          */
10438         hur = llapi_hsm_user_request_alloc(nbfile, opaque_len);
10439         if (!hur) {
10440                 fprintf(stderr, "Cannot create the request: %s\n",
10441                         strerror(errno));
10442                 return errno;
10443         }
10444         nbfile_alloc = nbfile;
10445
10446         hur->hur_request.hr_action = action;
10447         hur->hur_request.hr_archive_id = archive_id;
10448         hur->hur_request.hr_flags = 0;
10449
10450         /* All remaining args are files, add them */
10451         if (nbfile != 0 && some_file == NULL)
10452                 some_file = strdup(argv[optind]);
10453
10454         for (i = 0; i < nbfile; i++) {
10455                 rc = fill_hur_item(hur, i, mntpath, argv[optind + i],
10456                                    &last_dev);
10457                 if (rc)
10458                         goto out_free;
10459         }
10460
10461         /* from here stop using nb_file, use hur->hur_request.hr_itemcount */
10462
10463         /* If a filelist was specified, read the filelist from it. */
10464         if (filelist) {
10465                 fp = fopen(filelist, "r");
10466                 if (!fp) {
10467                         fprintf(stderr, "Cannot read the file list %s: %s\n",
10468                                 filelist, strerror(errno));
10469                         rc = -errno;
10470                         goto out_free;
10471                 }
10472
10473                 while ((rc = getline(&line, &len, fp)) != -1) {
10474                         /*
10475                          * If allocated buffer was too small, get something
10476                          * larger
10477                          */
10478                         if (nbfile_alloc <= hur->hur_request.hr_itemcount) {
10479                                 ssize_t size;
10480
10481                                 nbfile_alloc = nbfile_alloc * 2 + 1;
10482                                 oldhur = hur;
10483                                 hur = llapi_hsm_user_request_alloc(nbfile_alloc,
10484                                                                    opaque_len);
10485                                 if (!hur) {
10486                                         fprintf(stderr,
10487                                                 "hsm: cannot allocate the request: %s\n",
10488                                                 strerror(errno));
10489                                         hur = oldhur;
10490                                         rc = -errno;
10491                                         fclose(fp);
10492                                         goto out_free;
10493                                 }
10494                                 size = hur_len(oldhur);
10495                                 if (size < 0) {
10496                                         fprintf(stderr,
10497                                                 "hsm: cannot allocate %u files + %u bytes data\n",
10498                                                 oldhur->hur_request.hr_itemcount,
10499                                                 oldhur->hur_request.hr_data_len);
10500                                         free(hur);
10501                                         hur = oldhur;
10502                                         rc = -E2BIG;
10503                                         fclose(fp);
10504                                         goto out_free;
10505                                 }
10506                                 memcpy(hur, oldhur, size);
10507                                 free(oldhur);
10508                         }
10509
10510                         /* Chop CR */
10511                         if (line[strlen(line) - 1] == '\n')
10512                                 line[strlen(line) - 1] = '\0';
10513
10514                         rc = fill_hur_item(hur, hur->hur_request.hr_itemcount,
10515                                            mntpath, line, &last_dev);
10516                         if (rc) {
10517                                 fclose(fp);
10518                                 goto out_free;
10519                         }
10520
10521                         if (!some_file) {
10522                                 some_file = line;
10523                                 line = NULL;
10524                         }
10525                 }
10526
10527                 rc = fclose(fp);
10528                 free(line);
10529         }
10530
10531         /* If a --data was used, add it to the request */
10532         hur->hur_request.hr_data_len = opaque_len;
10533         if (opaque)
10534                 memcpy(hur_data(hur), opaque, opaque_len);
10535
10536         /* Send the HSM request */
10537         if (realpath(some_file, fullpath) == NULL) {
10538                 fprintf(stderr, "Could not find path '%s': %s\n",
10539                         some_file, strerror(errno));
10540         }
10541         rc = llapi_hsm_request(fullpath, hur);
10542         if (rc) {
10543                 fprintf(stderr, "Cannot send HSM request (use of %s): %s\n",
10544                         some_file, strerror(-rc));
10545                 goto out_free;
10546         }
10547
10548 out_free:
10549         free(some_file);
10550         free(hur);
10551         return rc;
10552 }
10553
10554 static int lfs_hsm_archive(int argc, char **argv)
10555 {
10556         return lfs_hsm_request(argc, argv, HUA_ARCHIVE);
10557 }
10558
10559 static int lfs_hsm_restore(int argc, char **argv)
10560 {
10561         return lfs_hsm_request(argc, argv, HUA_RESTORE);
10562 }
10563
10564 static int lfs_hsm_release(int argc, char **argv)
10565 {
10566         return lfs_hsm_request(argc, argv, HUA_RELEASE);
10567 }
10568
10569 static int lfs_hsm_remove(int argc, char **argv)
10570 {
10571         return lfs_hsm_request(argc, argv, HUA_REMOVE);
10572 }
10573
10574 static int lfs_hsm_cancel(int argc, char **argv)
10575 {
10576         return lfs_hsm_request(argc, argv, HUA_CANCEL);
10577 }
10578
10579 static int lfs_swap_layouts(int argc, char **argv)
10580 {
10581         if (argc != 3)
10582                 return CMD_HELP;
10583
10584         return llapi_swap_layouts(argv[1], argv[2], 0, 0,
10585                                   SWAP_LAYOUTS_KEEP_MTIME |
10586                                   SWAP_LAYOUTS_KEEP_ATIME);
10587 }
10588
10589 static const char *const ladvise_names[] = LU_LADVISE_NAMES;
10590
10591 static const char *const lock_mode_names[] = LOCK_MODE_NAMES;
10592
10593 int lfs_get_mode(const char *string)
10594 {
10595         enum lock_mode_user mode;
10596
10597         for (mode = 0; mode < ARRAY_SIZE(lock_mode_names); mode++) {
10598                 if (lock_mode_names[mode] == NULL)
10599                         continue;
10600                 if (strcasecmp(string, lock_mode_names[mode]) == 0)
10601                         return mode;
10602         }
10603
10604         return -EINVAL;
10605 }
10606
10607 static enum lu_ladvise_type lfs_get_ladvice(const char *string)
10608 {
10609         enum lu_ladvise_type advice;
10610
10611         for (advice = 0;
10612              advice < ARRAY_SIZE(ladvise_names); advice++) {
10613                 if (ladvise_names[advice] == NULL)
10614                         continue;
10615                 if (strcmp(string, ladvise_names[advice]) == 0)
10616                         return advice;
10617         }
10618
10619         return LU_LADVISE_INVALID;
10620 }
10621
10622 static int lfs_ladvise(int argc, char **argv)
10623 {
10624         struct option long_opts[] = {
10625         { .val = 'a',   .name = "advice",       .has_arg = required_argument },
10626         { .val = 'b',   .name = "background",   .has_arg = no_argument },
10627         { .val = 'e',   .name = "end",          .has_arg = required_argument },
10628         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10629         { .val = 'l',   .name = "length",       .has_arg = required_argument },
10630         { .val = 'm',   .name = "mode",         .has_arg = required_argument },
10631         { .val = 's',   .name = "start",        .has_arg = required_argument },
10632         { .val = 'u',   .name = "unset",        .has_arg = no_argument },
10633         { .name = NULL } };
10634         struct llapi_lu_ladvise advice;
10635         enum lu_ladvise_type advice_type = LU_LADVISE_INVALID;
10636         unsigned long long start = 0;
10637         unsigned long long end = LUSTRE_EOF;
10638         unsigned long long length = 0;
10639         unsigned long long size_units;
10640         unsigned long long flags = 0;
10641         int c, fd, rc = 0;
10642         const char *path;
10643         int mode = 0;
10644
10645         optind = 0;
10646         while ((c = getopt_long(argc, argv, "a:be:hl:m:s:u",
10647                                 long_opts, NULL)) != -1) {
10648                 switch (c) {
10649                 case 'a':
10650                         advice_type = lfs_get_ladvice(optarg);
10651                         if (advice_type == LU_LADVISE_INVALID) {
10652                                 fprintf(stderr,
10653                                         "%s: invalid advice type '%s'\n",
10654                                         progname, optarg);
10655                                 fprintf(stderr, "Valid types:");
10656
10657                                 for (advice_type = 0;
10658                                      advice_type < ARRAY_SIZE(ladvise_names);
10659                                      advice_type++) {
10660                                         if (ladvise_names[advice_type] == NULL)
10661                                                 continue;
10662                                         fprintf(stderr, " %s",
10663                                                 ladvise_names[advice_type]);
10664                                 }
10665                                 fprintf(stderr, "\n");
10666
10667                                 return CMD_HELP;
10668                         }
10669                         break;
10670                 case 'b':
10671                         flags |= LF_ASYNC;
10672                         break;
10673                 case 'u':
10674                         flags |= LF_UNSET;
10675                         break;
10676                 case 'e':
10677                         size_units = 1;
10678                         rc = llapi_parse_size(optarg, &end,
10679                                               &size_units, 0);
10680                         if (rc) {
10681                                 fprintf(stderr, "%s: bad end offset '%s'\n",
10682                                         argv[0], optarg);
10683                                 return CMD_HELP;
10684                         }
10685                         break;
10686                 case 's':
10687                         size_units = 1;
10688                         rc = llapi_parse_size(optarg, &start,
10689                                               &size_units, 0);
10690                         if (rc) {
10691                                 fprintf(stderr,
10692                                         "%s: bad start offset '%s'\n",
10693                                         argv[0], optarg);
10694                                 return CMD_HELP;
10695                         }
10696                         break;
10697                 case 'l':
10698                         size_units = 1;
10699                         rc = llapi_parse_size(optarg, &length,
10700                                               &size_units, 0);
10701                         if (rc) {
10702                                 fprintf(stderr, "%s: bad length '%s'\n",
10703                                         argv[0], optarg);
10704                                 return CMD_HELP;
10705                         }
10706                         break;
10707                 case 'm':
10708                         mode = lfs_get_mode(optarg);
10709                         if (mode < 0) {
10710                                 fprintf(stderr,
10711                                         "%s: bad mode '%s', valid modes are READ or WRITE\n",
10712                                         argv[0], optarg);
10713                                 return CMD_HELP;
10714                         }
10715                         break;
10716                 default:
10717                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10718                                 progname, argv[optind - 1]);
10719                         fallthrough;
10720                 case 'h':
10721                         return CMD_HELP;
10722                 }
10723         }
10724
10725         if (advice_type == LU_LADVISE_INVALID) {
10726                 fprintf(stderr, "%s: please give an advice type\n", argv[0]);
10727                 fprintf(stderr, "Valid types:");
10728                 for (advice_type = 0; advice_type < ARRAY_SIZE(ladvise_names);
10729                      advice_type++) {
10730                         if (ladvise_names[advice_type] == NULL)
10731                                 continue;
10732                         fprintf(stderr, " %s", ladvise_names[advice_type]);
10733                 }
10734                 fprintf(stderr, "\n");
10735                 return CMD_HELP;
10736         }
10737
10738         if (advice_type == LU_LADVISE_LOCKNOEXPAND) {
10739                 fprintf(stderr,
10740                         "%s: Lock no expand advice is a per file descriptor advice, so when called from lfs, it does nothing.\n",
10741                         argv[0]);
10742                 return CMD_HELP;
10743         }
10744
10745         if (argc <= optind) {
10746                 fprintf(stderr, "%s: please give one or more file names\n",
10747                         argv[0]);
10748                 return CMD_HELP;
10749         }
10750
10751         if (end != LUSTRE_EOF && length != 0 && end != start + length) {
10752                 fprintf(stderr, "%s: conflicting arguments of -l and -e\n",
10753                         argv[0]);
10754                 return CMD_HELP;
10755         }
10756
10757         if (end == LUSTRE_EOF && length != 0)
10758                 end = start + length;
10759
10760         if (end <= start) {
10761                 fprintf(stderr, "%s: range [%llu, %llu] is invalid\n",
10762                         argv[0], start, end);
10763                 return CMD_HELP;
10764         }
10765
10766         if (advice_type != LU_LADVISE_LOCKAHEAD && mode != 0) {
10767                 fprintf(stderr, "%s: mode is only valid with lockahead\n",
10768                         argv[0]);
10769                 return CMD_HELP;
10770         }
10771
10772         if (advice_type == LU_LADVISE_LOCKAHEAD && mode == 0) {
10773                 fprintf(stderr, "%s: mode is required with lockahead\n",
10774                         argv[0]);
10775                 return CMD_HELP;
10776         }
10777
10778         while (optind < argc) {
10779                 int rc2;
10780
10781                 path = argv[optind++];
10782
10783                 fd = open(path, O_RDONLY);
10784                 if (fd < 0) {
10785                         rc2 = -errno;
10786                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10787                                 argv[0], path, strerror(-rc2));
10788                         if (!rc)
10789                                 rc = rc2;
10790                         continue;
10791                 }
10792
10793                 advice.lla_start = start;
10794                 advice.lla_end = end;
10795                 advice.lla_advice = advice_type;
10796                 advice.lla_value1 = 0;
10797                 advice.lla_value2 = 0;
10798                 advice.lla_value3 = 0;
10799                 advice.lla_value4 = 0;
10800                 if (advice_type == LU_LADVISE_LOCKAHEAD) {
10801                         advice.lla_lockahead_mode = mode;
10802                         advice.lla_peradvice_flags = flags;
10803                 }
10804
10805                 rc2 = llapi_ladvise(fd, flags, 1, &advice);
10806                 close(fd);
10807                 if (rc2 < 0) {
10808                         fprintf(stderr,
10809                                 "%s: cannot give advice '%s' to file '%s': %s\n",
10810                                 argv[0], ladvise_names[advice_type],
10811                                 path, strerror(errno));
10812
10813                         if (!rc)
10814                                 rc = rc2;
10815                         continue;
10816                 }
10817         }
10818
10819         return rc;
10820 }
10821
10822 static const char *const heat_names[] = LU_HEAT_NAMES;
10823
10824 static int lfs_heat_get(int argc, char **argv)
10825 {
10826         struct lu_heat *heat;
10827         int rc = 0, rc2;
10828         char *path;
10829         int fd;
10830         int i;
10831
10832         if (argc <= 1)
10833                 return CMD_HELP;
10834
10835         heat = calloc(sizeof(*heat) + sizeof(__u64) * OBD_HEAT_COUNT, 1);
10836         if (!heat) {
10837                 fprintf(stderr, "%s: memory allocation failed\n", argv[0]);
10838                 return -ENOMEM;
10839         }
10840
10841         optind = 1;
10842         while (optind < argc) {
10843                 path = argv[optind++];
10844
10845                 fd = open(path, O_RDONLY);
10846                 if (fd < 0) {
10847                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10848                                 argv[0], path, strerror(errno));
10849                         rc2 = -errno;
10850                         goto next;
10851                 }
10852
10853                 heat->lh_count = OBD_HEAT_COUNT;
10854                 rc2 = llapi_heat_get(fd, heat);
10855                 close(fd);
10856                 if (rc2 < 0) {
10857                         fprintf(stderr,
10858                                 "%s: cannot get heat of file '%s': %s\n",
10859                                 argv[0], path, strerror(errno));
10860                         goto next;
10861                 }
10862
10863                 printf("flags: %x\n", heat->lh_flags);
10864                 for (i = 0; i < heat->lh_count; i++)
10865                         printf("%s: %llu\n", heat_names[i],
10866                                (unsigned long long)heat->lh_heat[i]);
10867 next:
10868                 if (rc == 0 && rc2 < 0)
10869                         rc = rc2;
10870         }
10871
10872         free(heat);
10873         return rc;
10874 }
10875
10876 static int lfs_heat_set(int argc, char **argv)
10877 {
10878         struct option long_opts[] = {
10879         { .val = 'c',   .name = "clear",        .has_arg = no_argument },
10880         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10881         { .val = 'o',   .name = "off",          .has_arg = no_argument },
10882         { .val = 'O',   .name = "on",           .has_arg = no_argument },
10883         { .name = NULL } };
10884         enum lu_heat_flag flags = 0;
10885         int rc = 0, rc2;
10886         char *path;
10887         int fd;
10888         int c;
10889
10890         if (argc <= 1)
10891                 return CMD_HELP;
10892
10893         optind = 0;
10894         while ((c = getopt_long(argc, argv, "choO", long_opts, NULL)) != -1) {
10895                 switch (c) {
10896                 case 'c':
10897                         flags |= LU_HEAT_FLAG_CLEAR;
10898                         break;
10899                 case 'o':
10900                         flags |= LU_HEAT_FLAG_CLEAR;
10901                         flags |= LU_HEAT_FLAG_OFF;
10902                         break;
10903                 case 'O':
10904                         flags &= ~LU_HEAT_FLAG_OFF;
10905                         break;
10906                 default:
10907                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10908                                 progname, argv[optind - 1]);
10909                         fallthrough;
10910                 case 'h':
10911                         return CMD_HELP;
10912                 }
10913         }
10914
10915         if (argc <= optind) {
10916                 fprintf(stderr, "%s: please give one or more file names\n",
10917                         argv[0]);
10918                 return CMD_HELP;
10919         }
10920
10921         while (optind < argc) {
10922                 path = argv[optind++];
10923
10924                 fd = open(path, O_RDONLY);
10925                 if (fd < 0) {
10926                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10927                                 argv[0], path, strerror(errno));
10928                         rc2 = -errno;
10929                         goto next;
10930                 }
10931
10932                 rc2 = llapi_heat_set(fd, flags);
10933                 close(fd);
10934                 if (rc2 < 0) {
10935                         fprintf(stderr,
10936                                 "%s: cannot setflags heat of file '%s': %s\n",
10937                                 argv[0], path, strerror(errno));
10938                         goto next;
10939                 }
10940 next:
10941                 if (rc == 0 && rc2 < 0)
10942                         rc = rc2;
10943         }
10944         return rc;
10945 }
10946
10947 /**
10948  * The input string contains a comma delimited list of component ids and
10949  * ranges, for example "1,2-4,7".
10950  */
10951 static int parse_mirror_ids(__u16 *ids, int size, char *arg)
10952 {
10953         bool end_of_loop = false;
10954         char *ptr = NULL;
10955         int nr = 0;
10956         int rc;
10957
10958         if (!arg)
10959                 return -EINVAL;
10960
10961         while (!end_of_loop) {
10962                 int start_index;
10963                 int end_index;
10964                 int i;
10965                 char *endptr = NULL;
10966
10967                 rc = -EINVAL;
10968                 ptr = strchrnul(arg, ',');
10969                 end_of_loop = *ptr == '\0';
10970                 *ptr = '\0';
10971
10972                 start_index = strtol(arg, &endptr, 0);
10973                 if (endptr == arg) /* no data at all */
10974                         break;
10975                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
10976                         break;
10977                 if (start_index < 0)
10978                         break;
10979
10980                 end_index = start_index;
10981                 if (*endptr == '-') {
10982                         end_index = strtol(endptr + 1, &endptr, 0);
10983                         if (*endptr != '\0')
10984                                 break;
10985                         if (end_index < start_index)
10986                                 break;
10987                 }
10988
10989                 for (i = start_index; i <= end_index && size > 0; i++) {
10990                         int j;
10991
10992                         /* remove duplicate */
10993                         for (j = 0; j < nr; j++) {
10994                                 if (ids[j] == i)
10995                                         break;
10996                         }
10997                         if (j == nr) { /* no duplicate */
10998                                 ids[nr++] = i;
10999                                 --size;
11000                         }
11001                 }
11002
11003                 if (size == 0 && i < end_index)
11004                         break;
11005
11006                 *ptr = ',';
11007                 arg = ++ptr;
11008                 rc = 0;
11009         }
11010         if (!end_of_loop && ptr)
11011                 *ptr = ',';
11012
11013         return rc < 0 ? rc : nr;
11014 }
11015
11016 /**
11017  * struct verify_mirror_id - Mirror id to be verified.
11018  * @mirror_id:   A specified mirror id.
11019  * @is_valid_id: @mirror_id is valid or not in the mirrored file.
11020  */
11021 struct verify_mirror_id {
11022         __u16 mirror_id;
11023         bool is_valid_id;
11024 };
11025
11026 /**
11027  * compare_mirror_ids() - Compare mirror ids.
11028  * @layout: Mirror component list.
11029  * @cbdata: Callback data in verify_mirror_id structure.
11030  *
11031  * This is a callback function called by llapi_layout_comp_iterate()
11032  * to compare the specified mirror id with the one in the current
11033  * component of @layout. If they are the same, then the specified
11034  * mirror id is valid.
11035  *
11036  * Return: a negative error code on failure or
11037  *         LLAPI_LAYOUT_ITER_CONT: Proceed iteration
11038  *         LLAPI_LAYOUT_ITER_STOP: Stop iteration
11039  */
11040 static inline
11041 int compare_mirror_ids(struct llapi_layout *layout, void *cbdata)
11042 {
11043         struct verify_mirror_id *mirror_id_cbdata =
11044                                  (struct verify_mirror_id *)cbdata;
11045         uint32_t mirror_id;
11046         int rc = 0;
11047
11048         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
11049         if (rc < 0) {
11050                 rc = -errno;
11051                 fprintf(stderr,
11052                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
11053                         progname, strerror(errno));
11054                 return rc;
11055         }
11056
11057         if (mirror_id_cbdata->mirror_id == mirror_id) {
11058                 mirror_id_cbdata->is_valid_id = true;
11059                 return LLAPI_LAYOUT_ITER_STOP;
11060         }
11061
11062         return LLAPI_LAYOUT_ITER_CONT;
11063 }
11064
11065 /**
11066  * verify_mirror_ids() - Verify specified mirror ids.
11067  * @fname:      Mirrored file name.
11068  * @mirror_ids: Specified mirror ids to be verified.
11069  * @ids_nr:     Number of specified mirror ids.
11070  *
11071  * This function verifies that specified @mirror_ids are valid
11072  * in the mirrored file @fname.
11073  *
11074  * Return: 0 on success or a negative error code on failure.
11075  */
11076 static inline
11077 int verify_mirror_ids(const char *fname, __u16 *mirror_ids, int ids_nr)
11078 {
11079         struct llapi_layout *layout = NULL;
11080         struct verify_mirror_id mirror_id_cbdata = { 0 };
11081         struct stat stbuf;
11082         uint32_t flr_state;
11083         int i;
11084         int fd;
11085         int rc = 0;
11086         int rc2 = 0;
11087
11088         if (ids_nr <= 0)
11089                 return -EINVAL;
11090
11091         if (stat(fname, &stbuf) < 0) {
11092                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
11093                         progname, fname, strerror(errno));
11094                 rc = -errno;
11095                 goto error;
11096         }
11097
11098         if (!S_ISREG(stbuf.st_mode)) {
11099                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
11100                         progname, fname);
11101                 rc = -EINVAL;
11102                 goto error;
11103         }
11104
11105         fd = open(fname, O_DIRECT | O_RDONLY);
11106         if (fd < 0) {
11107                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
11108                         progname, fname, strerror(errno));
11109                 rc = -errno;
11110                 goto error;
11111         }
11112
11113         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
11114         if (rc < 0) {
11115                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
11116                         progname, fname, strerror(errno));
11117                 goto close_fd;
11118         }
11119
11120         layout = llapi_layout_get_by_fd(fd, 0);
11121         if (!layout) {
11122                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
11123                         progname, fname, strerror(errno));
11124                 rc = -errno;
11125                 llapi_lease_release(fd);
11126                 goto close_fd;
11127         }
11128
11129         rc = llapi_layout_flags_get(layout, &flr_state);
11130         if (rc < 0) {
11131                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
11132                         progname, fname, strerror(errno));
11133                 rc = -errno;
11134                 goto free_layout;
11135         }
11136
11137         flr_state &= LCM_FL_FLR_MASK;
11138         switch (flr_state) {
11139         case LCM_FL_NONE:
11140                 rc = -EINVAL;
11141                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
11142                         progname, fname, llapi_layout_flags_string(flr_state));
11143                 goto free_layout;
11144         default:
11145                 break;
11146         }
11147
11148         rc2 = 0;
11149         for (i = 0; i < ids_nr; i++) {
11150                 mirror_id_cbdata.mirror_id = mirror_ids[i];
11151                 mirror_id_cbdata.is_valid_id = false;
11152
11153                 rc = llapi_layout_comp_iterate(layout, compare_mirror_ids,
11154                                                &mirror_id_cbdata);
11155                 if (rc < 0) {
11156                         rc = -errno;
11157                         fprintf(stderr,
11158                                 "%s: '%s' failed to verify mirror id: %u.\n",
11159                                 progname, fname, mirror_ids[i]);
11160                         goto free_layout;
11161                 }
11162
11163                 if (!mirror_id_cbdata.is_valid_id) {
11164                         rc2 = -EINVAL;
11165                         fprintf(stderr,
11166                                 "%s: '%s' invalid specified mirror id: %u.\n",
11167                                 progname, fname, mirror_ids[i]);
11168                 }
11169         }
11170         rc = rc2;
11171
11172 free_layout:
11173         llapi_layout_free(layout);
11174         llapi_lease_release(fd);
11175 close_fd:
11176         close(fd);
11177 error:
11178         return rc;
11179 }
11180
11181 static inline
11182 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
11183                            __u16 *mirror_ids, int ids_nr)
11184 {
11185         struct llapi_resync_comp comp_array[1024] = { { 0 } };
11186         struct llapi_layout *layout;
11187         struct stat stbuf;
11188         uint32_t flr_state;
11189         uint64_t start;
11190         uint64_t end;
11191         int comp_size = 0;
11192         int idx;
11193         int fd;
11194         int rc;
11195         int rc2;
11196
11197         if (stat(fname, &stbuf) < 0) {
11198                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
11199                         progname, fname, strerror(errno));
11200                 rc = -errno;
11201                 goto error;
11202         }
11203         if (!S_ISREG(stbuf.st_mode)) {
11204                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
11205                         progname, fname);
11206                 rc = -EINVAL;
11207                 goto error;
11208         }
11209
11210         /* Allow mirror resync even without the key on encrypted files */
11211         fd = open(fname, O_DIRECT | O_RDWR | O_CIPHERTEXT);
11212         if (fd < 0) {
11213                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
11214                         progname, fname, strerror(errno));
11215                 rc = -errno;
11216                 goto error;
11217         }
11218
11219         layout = llapi_layout_get_by_fd(fd, 0);
11220         if (!layout) {
11221                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
11222                         progname, fname, strerror(errno));
11223                 rc = -errno;
11224                 goto close_fd;
11225         }
11226
11227         rc = llapi_layout_flags_get(layout, &flr_state);
11228         if (rc) {
11229                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
11230                         progname, fname, strerror(errno));
11231                 rc = -errno;
11232                 goto free_layout;
11233         }
11234
11235         flr_state &= LCM_FL_FLR_MASK;
11236         if (flr_state == LCM_FL_NONE) {
11237                 rc = -EINVAL;
11238                 fprintf(stderr, "%s: '%s' is not a FLR file.\n",
11239                         progname, fname);
11240                 goto free_layout;
11241         }
11242
11243         /* get stale component info */
11244         comp_size = llapi_mirror_find_stale(layout, comp_array,
11245                                             ARRAY_SIZE(comp_array),
11246                                             mirror_ids, ids_nr);
11247         if (comp_size <= 0) {
11248                 rc = comp_size;
11249                 goto free_layout;
11250         }
11251
11252         ioc->lil_mode = LL_LEASE_WRLCK;
11253         ioc->lil_flags = LL_LEASE_RESYNC;
11254         rc = llapi_lease_set(fd, ioc);
11255         if (rc < 0) {
11256                 if (rc == -EALREADY)
11257                         rc = 0;
11258                 else
11259                         fprintf(stderr,
11260                             "%s: '%s' llapi_lease_get_ext resync failed: %s.\n",
11261                                 progname, fname, strerror(-rc));
11262                 goto free_layout;
11263         }
11264
11265         /* get the read range [start, end) */
11266         start = comp_array[0].lrc_start;
11267         end = comp_array[0].lrc_end;
11268         for (idx = 1; idx < comp_size; idx++) {
11269                 if (comp_array[idx].lrc_start < start)
11270                         start = comp_array[idx].lrc_start;
11271                 if (end < comp_array[idx].lrc_end)
11272                         end = comp_array[idx].lrc_end;
11273         }
11274
11275         rc = llapi_lease_check(fd);
11276         if (rc != LL_LEASE_WRLCK) {
11277                 fprintf(stderr, "%s: '%s' lost lease lock.\n",
11278                         progname, fname);
11279                 goto free_layout;
11280         }
11281
11282         rc = llapi_mirror_resync_many(fd, layout, comp_array, comp_size,
11283                                       start, end);
11284         if (rc < 0)
11285                 fprintf(stderr, "%s: '%s' llapi_mirror_resync_many: %s.\n",
11286                         progname, fname, strerror(-rc));
11287
11288         rc = migrate_set_timestamps(fd, &stbuf);
11289         if (rc < 0) {
11290                 fprintf(stderr, "%s: '%s' cannot set timestamps: %s\n",
11291                         progname, fname, strerror(-rc));
11292                 goto free_layout;
11293         }
11294
11295         /* need to do the lease unlock even resync fails */
11296         ioc->lil_mode = LL_LEASE_UNLCK;
11297         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
11298         ioc->lil_count = 0;
11299         for (idx = 0; idx < comp_size; idx++) {
11300                 if (comp_array[idx].lrc_synced) {
11301                         ioc->lil_ids[ioc->lil_count] = comp_array[idx].lrc_id;
11302                         ioc->lil_count++;
11303                 }
11304         }
11305
11306         rc2 = llapi_lease_set(fd, ioc);
11307         /**
11308          * llapi_lease_set returns lease mode when it request to unlock
11309          * the lease lock.
11310          */
11311         if (rc2 <= 0) {
11312                 /* rc2 == 0 means lost lease lock */
11313                 if (rc2 == 0 && rc == 0)
11314                         rc = -EBUSY;
11315                 else
11316                         rc = rc2;
11317                 fprintf(stderr, "%s: resync file '%s' failed: %s.\n",
11318                         progname, fname,
11319                         rc2 == 0 ? "lost lease lock" : strerror(-rc2));
11320
11321                 llapi_lease_release(fd);
11322                 goto free_layout;
11323         }
11324
11325 free_layout:
11326         llapi_layout_free(layout);
11327 close_fd:
11328         close(fd);
11329 error:
11330         return rc;
11331 }
11332
11333 static inline int lfs_mirror_resync(int argc, char **argv)
11334 {
11335         struct option long_opts[] = {
11336         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11337         { .val = 'o',   .name = "only",         .has_arg = required_argument },
11338         { .name = NULL } };
11339         struct ll_ioc_lease *ioc = NULL;
11340         __u16 mirror_ids[128] = { 0 };
11341         int ids_nr = 0;
11342         int c;
11343         int rc = 0;
11344
11345         while ((c = getopt_long(argc, argv, "ho:", long_opts, NULL)) >= 0) {
11346                 switch (c) {
11347                 case 'o':
11348                         rc = parse_mirror_ids(mirror_ids,
11349                                         sizeof(mirror_ids) / sizeof(__u16),
11350                                         optarg);
11351                         if (rc < 0) {
11352                                 fprintf(stderr,
11353                                         "%s: bad mirror ids '%s'.\n",
11354                                         argv[0], optarg);
11355                                 goto error;
11356                         }
11357                         ids_nr = rc;
11358                         break;
11359                 default:
11360                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11361                                 progname, argv[optind - 1]);
11362                         fallthrough;
11363                 case 'h':
11364                         rc = CMD_HELP;
11365                         goto error;
11366                 }
11367         }
11368
11369         if (argc == optind) {
11370                 fprintf(stderr, "%s: no file name given.\n", argv[0]);
11371                 rc = CMD_HELP;
11372                 goto error;
11373         }
11374
11375         if (ids_nr > 0 && argc > optind + 1) {
11376                 fprintf(stderr,
11377                     "%s: option '--only' cannot be used upon multiple files.\n",
11378                         argv[0]);
11379                 rc = CMD_HELP;
11380                 goto error;
11381         }
11382
11383         if (ids_nr > 0) {
11384                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
11385                 if (rc < 0)
11386                         goto error;
11387         }
11388
11389         /* set the lease on the file */
11390         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
11391         if (!ioc) {
11392                 fprintf(stderr, "%s: cannot alloc id array for ioc: %s.\n",
11393                         argv[0], strerror(errno));
11394                 rc = -errno;
11395                 goto error;
11396         }
11397
11398         for (; optind < argc; optind++) {
11399                 rc = lfs_mirror_resync_file(argv[optind], ioc,
11400                                             mirror_ids, ids_nr);
11401                 /* ignore previous file's error, continue with next file */
11402
11403                 /* reset ioc */
11404                 memset(ioc, 0, sizeof(*ioc) + sizeof(__u32) * 4096);
11405         }
11406
11407         free(ioc);
11408 error:
11409         return rc;
11410 }
11411
11412 static inline int verify_mirror_id_by_fd(int fd, __u16 mirror_id)
11413 {
11414         struct llapi_layout *layout;
11415         int rc;
11416
11417         layout = llapi_layout_get_by_fd(fd, 0);
11418         if (!layout) {
11419                 fprintf(stderr, "could not get layout.\n");
11420                 return  -EINVAL;
11421         }
11422
11423         rc = llapi_layout_comp_iterate(layout, find_mirror_id, &mirror_id);
11424         if (rc < 0) {
11425                 fprintf(stderr, "failed to iterate layout\n");
11426                 llapi_layout_free(layout);
11427
11428                 return rc;
11429         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
11430                 fprintf(stderr, "does not find mirror with ID %u\n", mirror_id);
11431                 llapi_layout_free(layout);
11432
11433                 return -EINVAL;
11434         }
11435         llapi_layout_free(layout);
11436
11437         return 0;
11438 }
11439
11440 /**
11441  * Check whether two files are the same file
11442  * \retval      0  same file
11443  * \retval      1  not the same file
11444  * \retval      <0 error code
11445  */
11446 static inline int check_same_file(int fd, const char *f2)
11447 {
11448         struct stat stbuf1;
11449         struct stat stbuf2;
11450
11451         if (fstat(fd, &stbuf1) < 0)
11452                 return -errno;
11453
11454         if (stat(f2, &stbuf2) < 0)
11455                 return 1;
11456
11457         if (stbuf1.st_rdev == stbuf2.st_rdev &&
11458             stbuf1.st_ino == stbuf2.st_ino)
11459                 return 0;
11460
11461         return 1;
11462 }
11463
11464 static inline int lfs_mirror_read(int argc, char **argv)
11465 {
11466         int rc = CMD_HELP;
11467         __u16 mirror_id = 0;
11468         const char *outfile = NULL;
11469         char *fname;
11470         int fd = 0;
11471         int outfd;
11472         int c;
11473         void *buf;
11474         const size_t buflen = 4 << 20;
11475         off_t pos;
11476         struct option long_opts[] = {
11477         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11478         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
11479         { .val = 'o',   .name = "outfile",      .has_arg = required_argument },
11480         { .name = NULL } };
11481
11482         while ((c = getopt_long(argc, argv, "hN:o:", long_opts, NULL)) >= 0) {
11483                 char *end;
11484
11485                 switch (c) {
11486                 case 'N': {
11487                         unsigned long int id;
11488
11489                         errno = 0;
11490                         id = strtoul(optarg, &end, 0);
11491                         if (errno != 0 || *end != '\0' || id == 0 ||
11492                             id > UINT16_MAX) {
11493                                 fprintf(stderr,
11494                                         "%s %s: invalid mirror ID '%s'\n",
11495                                         progname, argv[0], optarg);
11496                                 return rc;
11497                         }
11498
11499                         mirror_id = (__u16)id;
11500                         break;
11501                 }
11502                 case 'o':
11503                         outfile = optarg;
11504                         break;
11505                 default:
11506                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11507                                 progname, argv[optind - 1]);
11508                         fallthrough;
11509                 case 'h':
11510                         return CMD_HELP;
11511                 }
11512         }
11513
11514         if (argc == optind) {
11515                 fprintf(stderr, "%s %s: no mirrored file provided\n",
11516                         progname, argv[0]);
11517                 return rc;
11518         } else if (argc > optind + 1) {
11519                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
11520                 return rc;
11521         }
11522
11523         if (mirror_id == 0) {
11524                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
11525                         progname, argv[0]);
11526                 return rc;
11527         }
11528
11529         /* open mirror file */
11530         fname = argv[optind];
11531         fd = open(fname, O_DIRECT | O_RDONLY);
11532         if (fd < 0) {
11533                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
11534                         progname, argv[0], fname, strerror(errno));
11535                 return rc;
11536         }
11537
11538         /* verify mirror id */
11539         rc = verify_mirror_id_by_fd(fd, mirror_id);
11540         if (rc) {
11541                 fprintf(stderr,
11542                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11543                         progname, argv[0], mirror_id, fname);
11544                 goto close_fd;
11545         }
11546
11547         /* open output file - O_EXCL ensures output is not the same as input */
11548         if (outfile) {
11549                 outfd = open(outfile, O_EXCL | O_WRONLY | O_CREAT, 0644);
11550                 if (outfd < 0) {
11551                         fprintf(stderr, "%s %s: cannot create file '%s': %s\n",
11552                                 progname, argv[0], outfile, strerror(errno));
11553                         rc = -errno;
11554                         goto close_fd;
11555                 }
11556         } else {
11557                 outfd = STDOUT_FILENO;
11558         }
11559
11560         /* allocate buffer */
11561         rc = posix_memalign(&buf, sysconf(_SC_PAGESIZE), buflen);
11562         if (rc) {
11563                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
11564                                 progname, argv[0], rc);
11565                 goto close_outfd;
11566         }
11567
11568         pos = 0;
11569         while (1) {
11570                 ssize_t bytes_read;
11571                 ssize_t written = 0;
11572
11573                 bytes_read = llapi_mirror_read(fd, mirror_id, buf, buflen, pos);
11574                 if (bytes_read < 0) {
11575                         rc = bytes_read;
11576                         fprintf(stderr,
11577                                 "%s %s: fail to read data from mirror %u: %s\n",
11578                                 progname, argv[0], mirror_id, strerror(-rc));
11579                         goto free_buf;
11580                 }
11581
11582                 /* EOF reached */
11583                 if (bytes_read == 0)
11584                         break;
11585
11586                 while (written < bytes_read) {
11587                         ssize_t written2;
11588
11589                         written2 = write(outfd, buf + written,
11590                                          bytes_read - written);
11591                         if (written2 < 0) {
11592                                 fprintf(stderr,
11593                                         "%s %s: fail to write %s: %s\n",
11594                                         progname, argv[0], outfile ? : "STDOUT",
11595                                         strerror(errno));
11596                                 rc = -errno;
11597                                 goto free_buf;
11598                         }
11599                         written += written2;
11600                 }
11601
11602                 if (written != bytes_read) {
11603                         fprintf(stderr,
11604                 "%s %s: written %ld bytes does not match with %ld read.\n",
11605                                 progname, argv[0], written, bytes_read);
11606                         rc = -EIO;
11607                         goto free_buf;
11608                 }
11609
11610                 pos += bytes_read;
11611         }
11612
11613         fsync(outfd);
11614         rc = 0;
11615
11616 free_buf:
11617         free(buf);
11618 close_outfd:
11619         if (outfile)
11620                 close(outfd);
11621 close_fd:
11622         close(fd);
11623
11624         return rc;
11625 }
11626
11627 static inline int lfs_mirror_write(int argc, char **argv)
11628 {
11629         int rc = CMD_HELP;
11630         __u16 mirror_id = 0;
11631         const char *inputfile = NULL;
11632         char *fname;
11633         int fd = 0;
11634         int inputfd;
11635         int c;
11636         void *buf;
11637         const size_t buflen = 4 << 20;
11638         off_t pos;
11639         size_t page_size = sysconf(_SC_PAGESIZE);
11640         struct ll_ioc_lease_id ioc;
11641         struct option long_opts[] = {
11642         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11643         { .val = 'i',   .name = "inputfile",    .has_arg = required_argument },
11644         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
11645         { .name = NULL } };
11646
11647         while ((c = getopt_long(argc, argv, "hi:N:", long_opts, NULL)) >= 0) {
11648                 char *end;
11649
11650                 switch (c) {
11651                 case 'N': {
11652                         unsigned long int id;
11653
11654                         errno = 0;
11655                         id = strtoul(optarg, &end, 0);
11656                         if (errno != 0 || *end != '\0' || id == 0 ||
11657                             id > UINT16_MAX) {
11658                                 fprintf(stderr,
11659                                         "%s %s: invalid mirror ID '%s'\n",
11660                                         progname, argv[0], optarg);
11661                                 return rc;
11662                         }
11663
11664                         mirror_id = (__u16)id;
11665                         break;
11666                 }
11667                 case 'i':
11668                         inputfile = optarg;
11669                         break;
11670                 default:
11671                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11672                                 progname, argv[optind - 1]);
11673                         fallthrough;
11674                 case 'h':
11675                         return CMD_HELP;
11676                 }
11677         }
11678
11679         if (argc == optind) {
11680                 fprintf(stderr, "%s %s: no mirrored file provided\n",
11681                         progname, argv[0]);
11682                 return rc;
11683         } else if (argc > optind + 1) {
11684                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
11685                 return rc;
11686         }
11687
11688         if (mirror_id == 0) {
11689                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
11690                         progname, argv[0]);
11691                 return rc;
11692         }
11693
11694         /* open mirror file */
11695         fname = argv[optind];
11696         fd = open(fname, O_DIRECT | O_WRONLY);
11697         if (fd < 0) {
11698                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
11699                         progname, argv[0], fname, strerror(errno));
11700                 return rc;
11701         }
11702
11703         /* verify mirror id */
11704         rc = verify_mirror_id_by_fd(fd, mirror_id);
11705         if (rc) {
11706                 fprintf(stderr,
11707                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11708                         progname, argv[0], mirror_id, fname);
11709                 goto close_fd;
11710         }
11711
11712         /* open input file */
11713         if (inputfile) {
11714                 rc = check_same_file(fd, inputfile);
11715                 if (rc == 0) {
11716                         fprintf(stderr,
11717                         "%s %s: input file cannot be the mirrored file '%s'\n",
11718                                 progname, argv[0], fname);
11719                         goto close_fd;
11720                 }
11721                 if (rc < 0)
11722                         goto close_fd;
11723
11724                 inputfd = open(inputfile, O_RDONLY, 0644);
11725                 if (inputfd < 0) {
11726                         fprintf(stderr, "%s %s: cannot open file '%s': %s\n",
11727                                 progname, argv[0], inputfile, strerror(errno));
11728                         rc = -errno;
11729                         goto close_fd;
11730                 }
11731         } else {
11732                 inputfd = STDIN_FILENO;
11733         }
11734
11735         /* allocate buffer */
11736         rc = posix_memalign(&buf, page_size, buflen);
11737         if (rc) {
11738                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
11739                         progname, argv[0], rc);
11740                 goto close_inputfd;
11741         }
11742
11743         /* prepare target mirror components instantiation */
11744         ioc.lil_mode = LL_LEASE_WRLCK;
11745         ioc.lil_flags = LL_LEASE_RESYNC;
11746         ioc.lil_mirror_id = mirror_id;
11747         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
11748         if (rc < 0) {
11749                 fprintf(stderr,
11750                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
11751                         progname, argv[0], fname, strerror(errno));
11752                 goto free_buf;
11753         }
11754
11755         pos = 0;
11756         while (1) {
11757                 ssize_t bytes_read;
11758                 ssize_t written;
11759                 size_t to_write;
11760
11761                 rc = llapi_lease_check(fd);
11762                 if (rc != LL_LEASE_WRLCK) {
11763                         fprintf(stderr, "%s %s: '%s' lost lease lock\n",
11764                                 progname, argv[0], fname);
11765                         goto free_buf;
11766                 }
11767
11768                 bytes_read = read(inputfd, buf, buflen);
11769                 if (bytes_read < 0) {
11770                         rc = bytes_read;
11771                         fprintf(stderr,
11772                                 "%s %s: fail to read data from '%s': %s\n",
11773                                 progname, argv[0], inputfile ? : "STDIN",
11774                                 strerror(errno));
11775                         rc = -errno;
11776                         goto free_buf;
11777                 }
11778
11779                 /* EOF reached */
11780                 if (bytes_read == 0)
11781                         break;
11782
11783                 /* round up to page align to make direct IO happy. */
11784                 to_write = (bytes_read + page_size - 1) & ~(page_size - 1);
11785
11786                 written = llapi_mirror_write(fd, mirror_id, buf, to_write,
11787                                              pos);
11788                 if (written < 0) {
11789                         rc = written;
11790                         fprintf(stderr,
11791                               "%s %s: fail to write to mirror %u: %s\n",
11792                                 progname, argv[0], mirror_id,
11793                                 strerror(-rc));
11794                         goto free_buf;
11795                 }
11796
11797                 pos += bytes_read;
11798         }
11799
11800         if (pos & (page_size - 1)) {
11801                 rc = llapi_mirror_truncate(fd, mirror_id, pos);
11802                 if (rc < 0)
11803                         goto free_buf;
11804         }
11805
11806         ioc.lil_mode = LL_LEASE_UNLCK;
11807         ioc.lil_flags = LL_LEASE_RESYNC_DONE;
11808         ioc.lil_count = 0;
11809         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
11810         if (rc <= 0) {
11811                 if (rc == 0)
11812                         rc = -EBUSY;
11813                 fprintf(stderr,
11814                         "%s %s: release lease lock of '%s' failed: %s\n",
11815                         progname, argv[0], fname, strerror(-rc));
11816                 goto free_buf;
11817         }
11818
11819         rc = 0;
11820
11821 free_buf:
11822         free(buf);
11823 close_inputfd:
11824         if (inputfile)
11825                 close(inputfd);
11826 close_fd:
11827         close(fd);
11828
11829         return rc;
11830 }
11831
11832 static inline int get_other_mirror_ids(int fd, __u16 *ids, __u16 exclude_id)
11833 {
11834         struct llapi_layout *layout;
11835         struct collect_ids_data cid = { .cid_ids = ids,
11836                                         .cid_count = 0,
11837                                         .cid_exclude = exclude_id, };
11838         int rc;
11839
11840         layout = llapi_layout_get_by_fd(fd, 0);
11841         if (!layout) {
11842                 fprintf(stderr, "could not get layout\n");
11843                 return -EINVAL;
11844         }
11845
11846         rc = llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
11847         if (rc < 0) {
11848                 fprintf(stderr, "failed to iterate layout\n");
11849                 llapi_layout_free(layout);
11850
11851                 return rc;
11852         }
11853         llapi_layout_free(layout);
11854
11855         return cid.cid_count;
11856 }
11857
11858 #ifndef MIRROR_ID_NEG
11859 #define MIRROR_ID_NEG         0x8000
11860 #endif
11861
11862 static inline int lfs_mirror_copy(int argc, char **argv)
11863 {
11864         int rc = CMD_HELP;
11865         __u16 read_mirror_id = 0;
11866         __u16 ids[128] = { 0 };
11867         int count = 0;
11868         struct llapi_layout *layout = NULL;
11869         struct llapi_resync_comp comp_array[1024] = { { 0 } };
11870         int comp_size = 0;
11871         char *fname;
11872         int fd = 0;
11873         int c;
11874         int i;
11875         ssize_t copied;
11876         struct ll_ioc_lease *ioc = NULL;
11877         struct ll_ioc_lease_id *resync_ioc;
11878         struct option long_opts[] = {
11879         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11880         { .val = 'i',   .name = "read-mirror",  .has_arg = required_argument },
11881         { .val = 'o',   .name = "write-mirror", .has_arg = required_argument },
11882         { .name = NULL } };
11883         char cmd[PATH_MAX];
11884
11885         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
11886         progname = cmd;
11887         while ((c = getopt_long(argc, argv, "hi:o:", long_opts, NULL)) >= 0) {
11888                 char *end;
11889
11890                 switch (c) {
11891                 case 'i': {
11892                         unsigned long int id;
11893
11894                         errno = 0;
11895                         id = strtoul(optarg, &end, 0);
11896                         if (errno != 0 || *end != '\0' || id == 0 ||
11897                             id > UINT16_MAX) {
11898                                 fprintf(stderr,
11899                                         "%s: invalid read mirror ID '%s'\n",
11900                                         progname, optarg);
11901                                 return rc;
11902                         }
11903
11904                         read_mirror_id = (__u16)id;
11905                         break;
11906                 }
11907                 case 'o':
11908                         if (!strcmp(optarg, "-1")) {
11909                                 /* specify all other mirrors */
11910                                 ids[0] = (__u16)-1;
11911                                 count = 1;
11912                         } else {
11913                                 count = parse_mirror_ids((__u16 *)ids,
11914                                                          ARRAY_SIZE(ids),
11915                                                          optarg);
11916                                 if (count < 0)
11917                                         return rc;
11918                         }
11919                         break;
11920                 default:
11921                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11922                                 progname, argv[optind - 1]);
11923                         fallthrough;
11924                 case 'h':
11925                         return CMD_HELP;
11926                 }
11927         }
11928
11929         if (argc == optind) {
11930                 fprintf(stderr, "%s %s: no mirrored file provided\n",
11931                         progname, argv[0]);
11932                 return rc;
11933         } else if (argc > optind + 1) {
11934                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
11935                 return rc;
11936         }
11937
11938         if (read_mirror_id == 0) {
11939                 fprintf(stderr,
11940                         "%s %s: no valid read mirror ID %d is provided\n",
11941                         progname, argv[0], read_mirror_id);
11942                 return rc;
11943         }
11944
11945         if (count == 0) {
11946                 fprintf(stderr,
11947                         "%s %s: no write mirror ID is provided\n",
11948                         progname, argv[0]);
11949                 return rc;
11950         }
11951
11952         for (i = 0; i < count; i++) {
11953                 if (read_mirror_id == ids[i]) {
11954                         fprintf(stderr,
11955                         "%s %s: read and write mirror ID cannot be the same\n",
11956                                 progname, argv[0]);
11957                         return rc;
11958                 }
11959         }
11960
11961         /* open mirror file */
11962         fname = argv[optind];
11963
11964         fd = open(fname, O_DIRECT | O_RDWR);
11965         if (fd < 0) {
11966                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
11967                         progname, argv[0], fname, strerror(errno));
11968                 return rc;
11969         }
11970
11971         /* write to all other mirrors */
11972         if (ids[0] == (__u16)-1) {
11973                 count = get_other_mirror_ids(fd, ids, read_mirror_id);
11974                 if (count <= 0) {
11975                         rc = count;
11976                         fprintf(stderr,
11977                         "%s %s: failed to get other mirror ids in '%s': %d\n",
11978                                 progname, argv[0], fname, rc);
11979                         goto close_fd;
11980                 }
11981         }
11982
11983         /* verify mirror id */
11984         rc = verify_mirror_id_by_fd(fd, read_mirror_id);
11985         if (rc) {
11986                 fprintf(stderr,
11987                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11988                         progname, argv[0], read_mirror_id, fname);
11989                 goto close_fd;
11990         }
11991
11992         for (i = 0; i < count; i++) {
11993                 rc = verify_mirror_id_by_fd(fd, ids[i]);
11994                 if (rc) {
11995                         fprintf(stderr,
11996                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11997                                 progname, argv[0], ids[i], fname);
11998                         goto close_fd;
11999                 }
12000         }
12001
12002         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
12003         if (!ioc) {
12004                 fprintf(stderr,
12005                         "%s %s: cannot alloc comp id array for ioc: %s\n",
12006                         progname, argv[0], strerror(errno));
12007                 rc = -errno;
12008                 goto close_fd;
12009         }
12010
12011         /* get stale component info */
12012         layout = llapi_layout_get_by_fd(fd, 0);
12013         if (!layout) {
12014                 fprintf(stderr, "%s %s: failed to get layout of '%s': %s\n",
12015                         progname, argv[0], fname, strerror(errno));
12016                 rc = -errno;
12017                 goto free_ioc;
12018         }
12019         comp_size = llapi_mirror_find_stale(layout, comp_array,
12020                                             ARRAY_SIZE(comp_array),
12021                                             ids, count);
12022         llapi_layout_free(layout);
12023         if (comp_size < 0) {
12024                 rc = comp_size;
12025                 goto free_ioc;
12026         }
12027
12028         /* prepare target mirror components instantiation */
12029         resync_ioc = (struct ll_ioc_lease_id *)ioc;
12030         resync_ioc->lil_mode = LL_LEASE_WRLCK;
12031         resync_ioc->lil_flags = LL_LEASE_RESYNC;
12032         if (count == 1)
12033                 resync_ioc->lil_mirror_id = ids[0];
12034         else
12035                 resync_ioc->lil_mirror_id = read_mirror_id | MIRROR_ID_NEG;
12036         rc = llapi_lease_set(fd, ioc);
12037         if (rc < 0) {
12038                 fprintf(stderr,
12039                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
12040                         progname, argv[0], fname, strerror(errno));
12041                 goto free_ioc;
12042         }
12043
12044         copied = llapi_mirror_copy_many(fd, read_mirror_id, ids, count);
12045         if (copied < 0) {
12046                 rc = copied;
12047                 fprintf(stderr, "%s %s: copy error: %d\n",
12048                         progname, argv[0], rc);
12049                 goto free_ioc;
12050         }
12051
12052         fprintf(stdout, "mirror copied successfully: ");
12053         for (i = 0; i < copied; i++)
12054                 fprintf(stdout, "%d ", ids[i]);
12055         fprintf(stdout, "\n");
12056
12057         ioc->lil_mode = LL_LEASE_UNLCK;
12058         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
12059         ioc->lil_count = 0;
12060         for (i = 0; i < comp_size; i++) {
12061                 int j;
12062
12063                 for (j = 0; j < copied; j++) {
12064                         if (comp_array[i].lrc_mirror_id != ids[j])
12065                                 continue;
12066
12067                         ioc->lil_ids[ioc->lil_count] = comp_array[i].lrc_id;
12068                         ioc->lil_count++;
12069                 }
12070         }
12071         rc = llapi_lease_set(fd, ioc);
12072         if (rc <= 0) {
12073                 if (rc == 0)
12074                         rc = -EBUSY;
12075                 fprintf(stderr,
12076                         "%s %s: release lease lock of '%s' failed: %s\n",
12077                         progname, argv[0], fname, strerror(errno));
12078                 goto free_ioc;
12079         }
12080
12081         rc = 0;
12082
12083 free_ioc:
12084         free(ioc);
12085 close_fd:
12086         close(fd);
12087
12088         return rc;
12089 }
12090
12091 /**
12092  * struct verify_chunk - Mirror chunk to be verified.
12093  * @chunk:        [start, end) of the chunk.
12094  * @mirror_count: Number of mirror ids in @mirror_id array.
12095  * @mirror_id:    Array of valid mirror ids that cover the chunk.
12096  */
12097 struct verify_chunk {
12098         struct lu_extent chunk;
12099         unsigned int mirror_count;
12100         __u16 mirror_id[LUSTRE_MIRROR_COUNT_MAX];
12101 };
12102
12103 /**
12104  * print_chunks() - Print chunk information.
12105  * @fname:       Mirrored file name.
12106  * @chunks:      Array of chunks.
12107  * @chunk_count: Number of chunks in @chunks array.
12108  *
12109  * This function prints [start, end) of each chunk in @chunks
12110  * for mirrored file @fname, and also prints the valid mirror ids
12111  * that cover the chunk.
12112  *
12113  * Return: void.
12114  */
12115 static inline
12116 void print_chunks(const char *fname, struct verify_chunk *chunks,
12117                   int chunk_count)
12118 {
12119         int i;
12120         int j;
12121
12122         fprintf(stdout, "Chunks to be verified in %s:\n", fname);
12123         for (i = 0; i < chunk_count; i++) {
12124                 fprintf(stdout, DEXT, PEXT(&chunks[i].chunk));
12125
12126                 if (chunks[i].mirror_count == 0)
12127                         fprintf(stdout, "\t[");
12128                 else {
12129                         fprintf(stdout, "\t[%u", chunks[i].mirror_id[0]);
12130                         for (j = 1; j < chunks[i].mirror_count; j++)
12131                                 fprintf(stdout, ", %u", chunks[i].mirror_id[j]);
12132                 }
12133                 fprintf(stdout, "]\t%u\n", chunks[i].mirror_count);
12134         }
12135         fprintf(stdout, "\n");
12136 }
12137
12138 /**
12139  * print_checksums() - Print CRC-32 checksum values.
12140  * @chunk: A chunk and its corresponding valid mirror ids.
12141  * @crc:   CRC-32 checksum values on the chunk for each valid mirror.
12142  *
12143  * This function prints CRC-32 checksum values on @chunk for
12144  * each valid mirror that covers it.
12145  *
12146  * Return: void.
12147  */
12148 static inline
12149 void print_checksums(struct verify_chunk *chunk, unsigned long *crc,
12150                      unsigned long long pos, unsigned long long len)
12151 {
12152         int i;
12153
12154         fprintf(stdout,
12155                 "CRC-32 checksum value for chunk "DEXT":\n", pos, pos + len);
12156         for (i = 0; i < chunk->mirror_count; i++)
12157                 fprintf(stdout, "Mirror %u:\t%#lx\n",
12158                         chunk->mirror_id[i], crc[i]);
12159         fprintf(stdout, "\n");
12160 }
12161
12162 /**
12163  * filter_mirror_id() - Filter specified mirror ids.
12164  * @chunks:      Array of chunks.
12165  * @chunk_count: Number of chunks in @chunks array.
12166  * @mirror_ids:  Specified mirror ids to be verified.
12167  * @ids_nr:      Number of specified mirror ids.
12168  *
12169  * This function scans valid mirror ids that cover each chunk in @chunks
12170  * and filters specified mirror ids.
12171  *
12172  * Return: void.
12173  */
12174 static inline
12175 void filter_mirror_id(struct verify_chunk *chunks, int chunk_count,
12176                       __u16 *mirror_ids, int ids_nr)
12177 {
12178         int i;
12179         int j;
12180         int k;
12181         __u16 valid_id[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
12182         unsigned int valid_count = 0;
12183
12184         for (i = 0; i < chunk_count; i++) {
12185                 if (chunks[i].mirror_count == 0)
12186                         continue;
12187
12188                 valid_count = 0;
12189                 for (j = 0; j < ids_nr; j++) {
12190                         for (k = 0; k < chunks[i].mirror_count; k++) {
12191                                 if (chunks[i].mirror_id[k] == mirror_ids[j]) {
12192                                         valid_id[valid_count] = mirror_ids[j];
12193                                         valid_count++;
12194                                         break;
12195                                 }
12196                         }
12197                 }
12198
12199                 memcpy(chunks[i].mirror_id, valid_id,
12200                        sizeof(__u16) * valid_count);
12201                 chunks[i].mirror_count = valid_count;
12202         }
12203 }
12204
12205 /**
12206  * lfs_mirror_prepare_chunk() - Find mirror chunks to be verified.
12207  * @layout:      Mirror component list.
12208  * @chunks:      Array of chunks.
12209  * @chunks_size: Array size of @chunks.
12210  *
12211  * This function scans the components in @layout from offset 0 to LUSTRE_EOF
12212  * to find out chunk segments and store them in @chunks array.
12213  *
12214  * The @mirror_id array in each element of @chunks will store the valid
12215  * mirror ids that cover the chunk. If a mirror component covering the
12216  * chunk has LCME_FL_STALE or LCME_FL_OFFLINE flag, then the mirror id
12217  * will not be stored into the @mirror_id array, and the chunk for that
12218  * mirror will not be verified.
12219  *
12220  * The @mirror_count in each element of @chunks will store the number of
12221  * mirror ids in @mirror_id array. If @mirror_count is 0, it indicates the
12222  * chunk is invalid in all of the mirrors. And if @mirror_count is 1, it
12223  * indicates the chunk is valid in only one mirror. In both cases, the
12224  * chunk will not be verified.
12225  *
12226  * Here is an example:
12227  *
12228  *  0      1M     2M     3M     4M           EOF
12229  *  +------+-------------+--------------------+
12230  *  |      |             |      S             |       mirror1
12231  *  +------+------+------+------+-------------+
12232  *  |             |   S  |   S  |             |       mirror2
12233  *  +-------------+------+------+-------------+
12234  *
12235  * prepared @chunks array will contain 5 elements:
12236  * (([0, 1M), [1, 2], 2),
12237  *  ([1M, 2M), [1, 2], 2),
12238  *  ([2M, 3M), [1], 1),
12239  *  ([3M, 4M], [], 0),
12240  *  ([4M, EOF), [2], 1))
12241  *
12242  * Return: the actual array size of @chunks on success
12243  *         or a negative error code on failure.
12244  */
12245 static inline
12246 int lfs_mirror_prepare_chunk(struct llapi_layout *layout,
12247                              struct verify_chunk *chunks,
12248                              size_t chunks_size)
12249 {
12250         uint64_t start;
12251         uint64_t end;
12252         uint32_t mirror_id;
12253         uint32_t flags;
12254         int idx = 0;
12255         int i = 0;
12256         int rc = 0;
12257
12258         memset(chunks, 0, sizeof(*chunks) * chunks_size);
12259
12260         while (1) {
12261                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
12262                 if (rc < 0) {
12263                         fprintf(stderr,
12264                                 "%s: move to the first layout component: %s.\n",
12265                                 progname, strerror(errno));
12266                         goto error;
12267                 }
12268
12269                 i = 0;
12270                 rc = 0;
12271                 chunks[idx].chunk.e_end = LUSTRE_EOF;
12272                 while (rc == 0) {
12273                         rc = llapi_layout_comp_extent_get(layout, &start, &end);
12274                         if (rc < 0) {
12275                                 fprintf(stderr,
12276                                         "%s: llapi_layout_comp_extent_get failed: %s.\n",
12277                                         progname, strerror(errno));
12278                                 goto error;
12279                         }
12280
12281                         if (start > chunks[idx].chunk.e_start ||
12282                             end <= chunks[idx].chunk.e_start)
12283                                 goto next;
12284
12285                         if (end < chunks[idx].chunk.e_end)
12286                                 chunks[idx].chunk.e_end = end;
12287
12288                         rc = llapi_layout_comp_flags_get(layout, &flags);
12289                         if (rc < 0) {
12290                                 fprintf(stderr,
12291                                         "%s: llapi_layout_comp_flags_get failed: %s.\n",
12292                                         progname, strerror(errno));
12293                                 goto error;
12294                         }
12295
12296                         if (flags & LCME_FL_STALE || flags & LCME_FL_OFFLINE)
12297                                 goto next;
12298
12299                         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
12300                         if (rc < 0) {
12301                                 fprintf(stderr,
12302                                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
12303                                         progname, strerror(errno));
12304                                 goto error;
12305                         }
12306
12307                         if (i >= ARRAY_SIZE(chunks[idx].mirror_id)) {
12308                                 fprintf(stderr,
12309                                         "%s: mirror_id array is too small.\n",
12310                                         progname);
12311                                 rc = -EINVAL;
12312                                 goto error;
12313                         }
12314                         chunks[idx].mirror_id[i] = mirror_id;
12315                         i++;
12316
12317 next:
12318                         rc = llapi_layout_comp_use(layout,
12319                                                    LLAPI_LAYOUT_COMP_USE_NEXT);
12320                         if (rc < 0) {
12321                                 fprintf(stderr,
12322                                         "%s: move to the next layout component: %s.\n",
12323                                         progname, strerror(errno));
12324                                 goto error;
12325                         }
12326                 } /* loop through all components */
12327
12328                 chunks[idx].mirror_count = i;
12329
12330                 if (chunks[idx].chunk.e_end == LUSTRE_EOF)
12331                         break;
12332
12333                 idx++;
12334                 if (idx >= chunks_size) {
12335                         fprintf(stderr, "%s: chunks array is too small.\n",
12336                                 progname);
12337                         rc = -EINVAL;
12338                         goto error;
12339                 }
12340
12341                 chunks[idx].chunk.e_start = chunks[idx - 1].chunk.e_end;
12342         }
12343
12344 error:
12345         return rc < 0 ? rc : idx + 1;
12346 }
12347
12348 /**
12349  * lfs_mirror_verify_chunk() - Verify a chunk.
12350  * @fd:        File descriptor of the mirrored file.
12351  * @file_size: Size of the mirrored file.
12352  * @chunk:     A chunk and its corresponding valid mirror ids.
12353  * @verbose:   Verbose mode.
12354  *
12355  * This function verifies a @chunk contains exactly the same data
12356  * ammong the mirrors that cover it.
12357  *
12358  * If @verbose is specified, then the function will print where the
12359  * differences are if the data do not match. Otherwise, it will
12360  * just return an error in that case.
12361  *
12362  * Return: 0 on success or a negative error code on failure.
12363  */
12364 static inline
12365 int lfs_mirror_verify_chunk(int fd, size_t file_size,
12366                             struct verify_chunk *chunk, int verbose)
12367 {
12368         const size_t buflen = 4 * 1024 * 1024; /* 4M */
12369         void *buf;
12370         size_t page_size = sysconf(_SC_PAGESIZE);
12371         ssize_t bytes_read;
12372         ssize_t bytes_done;
12373         size_t count;
12374         off_t pos;
12375         unsigned long crc;
12376         unsigned long crc_array[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
12377         int i;
12378         int rc = 0;
12379
12380         if (file_size == 0)
12381                 return 0;
12382
12383         rc = posix_memalign(&buf, page_size, buflen);
12384         if (rc) /* error code is returned directly */
12385                 return -rc;
12386
12387         if (verbose > 1) {
12388                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
12389                         PEXT(&chunk->chunk));
12390                 for (i = 0; i < chunk->mirror_count; i++)
12391                         fprintf(stdout, " %u", chunk->mirror_id[i]);
12392                 fprintf(stdout, "\n");
12393         }
12394
12395         bytes_done = 0;
12396         count = MIN(chunk->chunk.e_end, file_size) - chunk->chunk.e_start;
12397         pos = chunk->chunk.e_start;
12398         while (bytes_done < count) {
12399                 /* compute initial CRC-32 checksum */
12400                 crc = crc32(0L, Z_NULL, 0);
12401                 memset(crc_array, 0, sizeof(crc_array));
12402
12403                 bytes_read = 0;
12404                 for (i = 0; i < chunk->mirror_count; i++) {
12405                         bytes_read = llapi_mirror_read(fd, chunk->mirror_id[i],
12406                                                        buf, buflen, pos);
12407                         if (bytes_read < 0) {
12408                                 rc = bytes_read;
12409                                 fprintf(stderr,
12410                                         "%s: failed to read data from mirror %u: %s.\n",
12411                                         progname, chunk->mirror_id[i],
12412                                         strerror(-rc));
12413                                 goto error;
12414                         }
12415
12416                         /* compute new CRC-32 checksum */
12417                         crc_array[i] = crc32(crc, buf, bytes_read);
12418                 }
12419
12420                 if (verbose)
12421                         print_checksums(chunk, crc_array, pos, buflen);
12422
12423                 /* compare CRC-32 checksum values */
12424                 for (i = 1; i < chunk->mirror_count; i++) {
12425                         if (crc_array[i] != crc_array[0]) {
12426                                 rc = -EINVAL;
12427
12428                                 fprintf(stderr,
12429                                         "%s: chunk "DEXT" has different checksum value on mirror %u and mirror %u.\n",
12430                                         progname, PEXT(&chunk->chunk),
12431                                         chunk->mirror_id[0],
12432                                         chunk->mirror_id[i]);
12433                         }
12434                 }
12435
12436                 pos += bytes_read;
12437                 bytes_done += bytes_read;
12438         }
12439
12440         if (verbose > 1 && rc == 0) {
12441                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
12442                         PEXT(&chunk->chunk));
12443                 for (i = 0; i < chunk->mirror_count; i++)
12444                         fprintf(stdout, " %u", chunk->mirror_id[i]);
12445                 fprintf(stdout, " PASS\n\n");
12446         }
12447
12448 error:
12449         free(buf);
12450         return rc;
12451 }
12452
12453 /**
12454  * lfs_mirror_verify_file() - Verify a mirrored file.
12455  * @fname:      Mirrored file name.
12456  * @mirror_ids: Specified mirror ids to be verified.
12457  * @ids_nr:     Number of specified mirror ids.
12458  * @verbose:    Verbose mode.
12459  *
12460  * This function verifies that each SYNC mirror of a mirrored file
12461  * specified by @fname contains exactly the same data.
12462  *
12463  * If @mirror_ids is specified, then the function will verify the
12464  * mirrors specified by @mirror_ids contain exactly the same data.
12465  *
12466  * If @verbose is specified, then the function will print where the
12467  * differences are if the data do not match. Otherwise, it will
12468  * just return an error in that case.
12469  *
12470  * Return: 0 on success or a negative error code on failure.
12471  */
12472 static inline
12473 int lfs_mirror_verify_file(const char *fname, __u16 *mirror_ids, int ids_nr,
12474                            int verbose)
12475 {
12476         struct verify_chunk chunks_array[1024] = { };
12477         struct llapi_layout *layout = NULL;
12478         struct stat stbuf;
12479         uint32_t flr_state;
12480         int fd;
12481         int chunk_count = 0;
12482         int idx = 0;
12483         int rc = 0;
12484         int rc1 = 0;
12485         int rc2 = 0;
12486
12487         if (stat(fname, &stbuf) < 0) {
12488                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
12489                         progname, fname, strerror(errno));
12490                 rc = -errno;
12491                 goto error;
12492         }
12493
12494         if (!S_ISREG(stbuf.st_mode)) {
12495                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
12496                         progname, fname);
12497                 rc = -EINVAL;
12498                 goto error;
12499         }
12500
12501         if (stbuf.st_size == 0) {
12502                 if (verbose)
12503                         fprintf(stdout, "%s: '%s' file size is 0.\n",
12504                                 progname, fname);
12505                 rc = 0;
12506                 goto error;
12507         }
12508
12509         /* Allow mirror verify even without the key on encrypted files */
12510         fd = open(fname, O_DIRECT | O_RDONLY | O_CIPHERTEXT);
12511         if (fd < 0) {
12512                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
12513                         progname, fname, strerror(errno));
12514                 rc = -errno;
12515                 goto error;
12516         }
12517
12518         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
12519         if (rc < 0) {
12520                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
12521                         progname, fname, strerror(errno));
12522                 goto close_fd;
12523         }
12524
12525         layout = llapi_layout_get_by_fd(fd, 0);
12526         if (!layout) {
12527                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
12528                         progname, fname, strerror(errno));
12529                 rc = -errno;
12530                 llapi_lease_release(fd);
12531                 goto close_fd;
12532         }
12533
12534         rc = llapi_layout_flags_get(layout, &flr_state);
12535         if (rc < 0) {
12536                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
12537                         progname, fname, strerror(errno));
12538                 rc = -errno;
12539                 goto free_layout;
12540         }
12541
12542         flr_state &= LCM_FL_FLR_MASK;
12543         switch (flr_state) {
12544         case LCM_FL_NONE:
12545                 rc = -EINVAL;
12546                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
12547                         progname, fname, llapi_layout_flags_string(flr_state));
12548                 goto free_layout;
12549         default:
12550                 break;
12551         }
12552
12553         /* find out mirror chunks to be verified */
12554         chunk_count = lfs_mirror_prepare_chunk(layout, chunks_array,
12555                                                ARRAY_SIZE(chunks_array));
12556         if (chunk_count < 0) {
12557                 rc = chunk_count;
12558                 goto free_layout;
12559         }
12560
12561         if (ids_nr > 0)
12562                 /* filter specified mirror ids */
12563                 filter_mirror_id(chunks_array, chunk_count, mirror_ids, ids_nr);
12564
12565         if (verbose > 2)
12566                 print_chunks(fname, chunks_array, chunk_count);
12567
12568         for (idx = 0; idx < chunk_count; idx++) {
12569                 if (chunks_array[idx].chunk.e_start >= stbuf.st_size) {
12570                         if (verbose)
12571                                 fprintf(stdout,
12572                                         "%s: '%s' chunk "DEXT" exceeds file size %#llx: skipped\n",
12573                                         progname, fname,
12574                                         PEXT(&chunks_array[idx].chunk),
12575                                         (unsigned long long)stbuf.st_size);
12576                         break;
12577                 }
12578
12579                 if (chunks_array[idx].mirror_count == 0) {
12580                         fprintf(stderr,
12581                                 "%s: '%s' chunk "DEXT" is invalid in all of the mirrors: ",
12582                                 progname, fname,
12583                                 PEXT(&chunks_array[idx].chunk));
12584                         if (verbose) {
12585                                 fprintf(stderr, "skipped\n");
12586                                 continue;
12587                         }
12588                         rc = -EINVAL;
12589                         fprintf(stderr, "failed\n");
12590                         goto free_layout;
12591                 }
12592
12593                 if (chunks_array[idx].mirror_count == 1) {
12594                         if (verbose)
12595                                 fprintf(stdout,
12596                                         "%s: '%s' chunk "DEXT" is only valid in mirror %u: skipped\n",
12597                                         progname, fname,
12598                                         PEXT(&chunks_array[idx].chunk),
12599                                         chunks_array[idx].mirror_id[0]);
12600                         continue;
12601                 }
12602
12603                 rc = llapi_lease_check(fd);
12604                 if (rc != LL_LEASE_RDLCK) {
12605                         fprintf(stderr, "%s: '%s' lost lease lock.\n",
12606                                 progname, fname);
12607                         goto free_layout;
12608                 }
12609
12610                 /* verify one chunk */
12611                 rc1 = lfs_mirror_verify_chunk(fd, stbuf.st_size,
12612                                               &chunks_array[idx], verbose);
12613                 if (rc1 < 0) {
12614                         rc2 = rc1;
12615                         if (!verbose) {
12616                                 rc = rc1;
12617                                 goto free_layout;
12618                         }
12619                 }
12620         }
12621
12622         if (rc2 < 0)
12623                 rc = rc2;
12624
12625 free_layout:
12626         llapi_layout_free(layout);
12627         llapi_lease_release(fd);
12628 close_fd:
12629         close(fd);
12630 error:
12631         return rc;
12632 }
12633
12634 /**
12635  * lfs_mirror_verify() - Parse and execute lfs mirror verify command.
12636  * @argc: The count of lfs mirror verify command line arguments.
12637  * @argv: Array of strings for lfs mirror verify command line arguments.
12638  *
12639  * This function parses lfs mirror verify command and verifies the
12640  * specified mirrored file(s).
12641  *
12642  * Return: 0 on success or a negative error code on failure.
12643  */
12644 static inline int lfs_mirror_verify(int argc, char **argv)
12645 {
12646         __u16 mirror_ids[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
12647         int ids_nr = 0;
12648         int c;
12649         int verbose = 0;
12650         int rc = 0;
12651         int rc1 = 0;
12652         char cmd[PATH_MAX];
12653
12654         struct option long_opts[] = {
12655         { .val = 'h',   .name = "help",         .has_arg = no_argument },
12656         { .val = 'o',   .name = "only",         .has_arg = required_argument },
12657         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
12658         { .name = NULL } };
12659
12660         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
12661         progname = cmd;
12662         while ((c = getopt_long(argc, argv, "ho:v", long_opts, NULL)) >= 0) {
12663                 switch (c) {
12664                 case 'o':
12665                         rc = parse_mirror_ids(mirror_ids,
12666                                               ARRAY_SIZE(mirror_ids),
12667                                               optarg);
12668                         if (rc < 0) {
12669                                 fprintf(stderr,
12670                                         "%s: bad mirror ids '%s'.\n",
12671                                         progname, optarg);
12672                                 goto error;
12673                         }
12674                         ids_nr = rc;
12675                         if (ids_nr < 2) {
12676                                 fprintf(stderr,
12677                                         "%s: at least 2 mirror ids needed with '--only' option.\n",
12678                                         progname);
12679                                 rc = CMD_HELP;
12680                                 goto error;
12681                         }
12682                         break;
12683                 case 'v':
12684                         verbose++;
12685                         break;
12686                 default:
12687                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12688                                 progname, argv[optind - 1]);
12689                         fallthrough;
12690                 case 'h':
12691                         rc = CMD_HELP;
12692                         goto error;
12693                 }
12694         }
12695
12696         if (argc == optind) {
12697                 fprintf(stderr, "%s: no file name given.\n", progname);
12698                 rc = CMD_HELP;
12699                 goto error;
12700         }
12701
12702         if (ids_nr > 0 && argc > optind + 1) {
12703                 fprintf(stderr,
12704                         "%s: '--only' cannot be used upon multiple files.\n",
12705                         progname);
12706                 rc = CMD_HELP;
12707                 goto error;
12708         }
12709
12710         if (ids_nr > 0) {
12711                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
12712                 if (rc < 0)
12713                         goto error;
12714         }
12715
12716         rc = 0;
12717         for (; optind < argc; optind++) {
12718                 rc1 = lfs_mirror_verify_file(argv[optind], mirror_ids, ids_nr,
12719                                              verbose);
12720                 if (rc1 < 0)
12721                         rc = rc1;
12722         }
12723 error:
12724         return rc;
12725 }
12726
12727 /**
12728  * lfs_mirror() - Parse and execute lfs mirror commands.
12729  * @argc: The count of lfs mirror command line arguments.
12730  * @argv: Array of strings for lfs mirror command line arguments.
12731  *
12732  * This function parses lfs mirror commands and performs the
12733  * corresponding functions specified in mirror_cmdlist[].
12734  *
12735  * Return: 0 on success or an error code on failure.
12736  */
12737 static int lfs_mirror(int argc, char **argv)
12738 {
12739         char cmd[PATH_MAX];
12740         int rc = 0;
12741
12742         setlinebuf(stdout);
12743
12744         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
12745         progname = cmd;
12746         program_invocation_short_name = cmd;
12747         rc = cfs_parser(argc, argv, mirror_cmdlist);
12748
12749         return rc < 0 ? -rc : rc;
12750 }
12751
12752 static void lustre_som_swab(struct lustre_som_attrs *attrs)
12753 {
12754 #if __BYTE_ORDER == __BIG_ENDIAN
12755         __swab16s(&attrs->lsa_valid);
12756         __swab64s(&attrs->lsa_size);
12757         __swab64s(&attrs->lsa_blocks);
12758 #endif
12759 }
12760
12761 enum lfs_som_type {
12762         LFS_SOM_SIZE = 0x1,
12763         LFS_SOM_BLOCKS = 0x2,
12764         LFS_SOM_FLAGS = 0x4,
12765         LFS_SOM_ATTR_ALL = LFS_SOM_SIZE | LFS_SOM_BLOCKS |
12766                            LFS_SOM_FLAGS,
12767 };
12768
12769 static int lfs_getsom(int argc, char **argv)
12770 {
12771         const char *path;
12772         struct lustre_som_attrs *attrs;
12773         char buf[sizeof(*attrs) + 64];
12774         enum lfs_som_type type = LFS_SOM_ATTR_ALL;
12775         int rc = 0, c;
12776
12777         while ((c = getopt(argc, argv, "bfhs")) != -1) {
12778                 switch (c) {
12779                 case 'b':
12780                         type = LFS_SOM_BLOCKS;
12781                         break;
12782                 case 'f':
12783                         type = LFS_SOM_FLAGS;
12784                         break;
12785                 case 's':
12786                         type = LFS_SOM_SIZE;
12787                         break;
12788                 default:
12789                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12790                                 progname, argv[optind - 1]);
12791                         fallthrough;
12792                 case 'h':
12793                         return CMD_HELP;
12794                 }
12795         }
12796
12797         argc -= optind;
12798         argv += optind;
12799
12800         if (argc != 1) {
12801                 fprintf(stderr, "%s: %s\n",
12802                         progname, argc == 0 ? "miss file target" :
12803                         "input more than 2 files");
12804                 return CMD_HELP;
12805         }
12806
12807         path = argv[0];
12808         attrs = (void *)buf;
12809         rc = lgetxattr(path, "trusted.som", attrs, sizeof(buf));
12810         if (rc < 0) {
12811                 rc = -errno;
12812                 fprintf(stderr, "%s failed to get som xattr: %s (%d)\n",
12813                         argv[0], strerror(errno), errno);
12814                 return rc;
12815         }
12816
12817         lustre_som_swab(attrs);
12818
12819         switch (type) {
12820         case LFS_SOM_ATTR_ALL:
12821                 printf("file: %s size: %llu blocks: %llu flags: %x\n",
12822                        path, (unsigned long long)attrs->lsa_size,
12823                        (unsigned long long)attrs->lsa_blocks,
12824                        attrs->lsa_valid);
12825                 break;
12826         case LFS_SOM_SIZE:
12827                 printf("%llu\n", (unsigned long long)attrs->lsa_size);
12828                 break;
12829         case LFS_SOM_BLOCKS:
12830                 printf("%llu\n", (unsigned long long)attrs->lsa_blocks);
12831                 break;
12832         case LFS_SOM_FLAGS:
12833                 printf("%x\n", attrs->lsa_valid);
12834                 break;
12835         default:
12836                 fprintf(stderr, "%s: unknown option\n", progname);
12837                 return CMD_HELP;
12838         }
12839
12840         return 0;
12841 }
12842
12843 static int lfs_pcc_attach(int argc, char **argv)
12844 {
12845         struct option long_opts[] = {
12846         { .val = 'h',   .name = "help", .has_arg = no_argument },
12847         { .val = 'i',   .name = "id",   .has_arg = required_argument },
12848         { .name = NULL } };
12849         int c;
12850         int rc = 0;
12851         __u32 archive_id = 0;
12852         const char *path;
12853         char *end;
12854         char fullpath[PATH_MAX];
12855         enum lu_pcc_type type = LU_PCC_READWRITE;
12856
12857         optind = 0;
12858         while ((c = getopt_long(argc, argv, "hi:",
12859                                 long_opts, NULL)) != -1) {
12860                 switch (c) {
12861                 case 'i':
12862                         errno = 0;
12863                         archive_id = strtoul(optarg, &end, 0);
12864                         if (errno != 0 || *end != '\0' ||
12865                             archive_id == 0 || archive_id > UINT32_MAX) {
12866                                 fprintf(stderr,
12867                                         "error: %s: bad archive ID '%s'\n",
12868                                         progname, optarg);
12869                                 return CMD_HELP;
12870                         }
12871                         break;
12872                 default:
12873                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12874                                 progname, argv[optind - 1]);
12875                         fallthrough;
12876                 case 'h':
12877                         return CMD_HELP;
12878                 }
12879         }
12880
12881         if (archive_id == 0) {
12882                 fprintf(stderr, "%s: must specify attach ID\n", argv[0]);
12883                 return CMD_HELP;
12884         }
12885
12886         if (argc <= optind) {
12887                 fprintf(stderr, "%s: must specify one or more file names\n",
12888                         argv[0]);
12889                 return CMD_HELP;
12890         }
12891
12892         while (optind < argc) {
12893                 int rc2;
12894
12895                 path = argv[optind++];
12896                 if (!realpath(path, fullpath)) {
12897                         fprintf(stderr, "%s: could not find path '%s': %s\n",
12898                                 argv[0], path, strerror(errno));
12899                         if (rc == 0)
12900                                 rc = -EINVAL;
12901                         continue;
12902                 }
12903
12904                 rc2 = llapi_pcc_attach(fullpath, archive_id, type);
12905                 if (rc2 < 0) {
12906                         fprintf(stderr,
12907                                 "%s: cannot attach '%s' to PCC with archive ID '%u': %s\n",
12908                                 argv[0], path, archive_id, strerror(-rc2));
12909                         if (rc == 0)
12910                                 rc = rc2;
12911                 }
12912         }
12913         return rc;
12914 }
12915
12916 static int lfs_pcc_attach_fid(int argc, char **argv)
12917 {
12918         struct option long_opts[] = {
12919         { .val = 'h',   .name = "help", .has_arg = no_argument },
12920         { .val = 'i',   .name = "id",   .has_arg = required_argument },
12921         { .val = 'm',   .name = "mnt",  .has_arg = required_argument },
12922         { .name = NULL } };
12923         int c;
12924         int rc = 0;
12925         __u32 archive_id = 0;
12926         char *end;
12927         const char *mntpath = NULL;
12928         const char *fidstr;
12929         enum lu_pcc_type type = LU_PCC_READWRITE;
12930
12931         optind = 0;
12932         while ((c = getopt_long(argc, argv, "hi:m:",
12933                                 long_opts, NULL)) != -1) {
12934                 switch (c) {
12935                 case 'i':
12936                         errno = 0;
12937                         archive_id = strtoul(optarg, &end, 0);
12938                         if (errno != 0 || *end != '\0' ||
12939                             archive_id > UINT32_MAX) {
12940                                 fprintf(stderr,
12941                                         "error: %s: bad archive ID '%s'\n",
12942                                         argv[0], optarg);
12943                                 return CMD_HELP;
12944                         }
12945                         break;
12946                 case 'm':
12947                         mntpath = optarg;
12948                         break;
12949                 default:
12950                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12951                                 progname, argv[optind - 1]);
12952                         fallthrough;
12953                 case 'h':
12954                         return CMD_HELP;
12955                 }
12956         }
12957
12958         if (archive_id == 0) {
12959                 fprintf(stderr, "%s: must specify an archive ID\n", argv[0]);
12960                 return CMD_HELP;
12961         }
12962
12963         if (!mntpath) {
12964                 fprintf(stderr, "%s: must specify Lustre mount point\n",
12965                         argv[0]);
12966                 return CMD_HELP;
12967         }
12968
12969         if (argc <= optind) {
12970                 fprintf(stderr, "%s: must specify one or more fids\n", argv[0]);
12971                 return CMD_HELP;
12972         }
12973
12974         while (optind < argc) {
12975                 int rc2;
12976
12977                 fidstr = argv[optind++];
12978
12979                 rc2 = llapi_pcc_attach_fid_str(mntpath, fidstr,
12980                                                archive_id, type);
12981                 if (rc2 < 0) {
12982                         fprintf(stderr,
12983                                 "%s: cannot attach '%s' on '%s' to PCC with archive ID '%u': %s\n",
12984                                 argv[0], fidstr, mntpath, archive_id,
12985                                 strerror(rc2));
12986                 }
12987                 if (rc == 0 && rc2 < 0)
12988                         rc = rc2;
12989         }
12990         return rc;
12991 }
12992
12993 static int lfs_pcc_detach(int argc, char **argv)
12994 {
12995         struct option long_opts[] = {
12996         { .val = 'h',   .name = "help", .has_arg = no_argument },
12997         { .val = 'k',   .name = "keep", .has_arg = no_argument },
12998         { .name = NULL } };
12999         int c;
13000         int rc = 0;
13001         const char *path;
13002         char fullpath[PATH_MAX];
13003         __u32 detach_opt = PCC_DETACH_OPT_UNCACHE;
13004
13005         optind = 0;
13006         while ((c = getopt_long(argc, argv, "hk",
13007                                 long_opts, NULL)) != -1) {
13008                 switch (c) {
13009                 case 'k':
13010                         detach_opt = PCC_DETACH_OPT_NONE;
13011                         break;
13012                 default:
13013                         fprintf(stderr, "%s: unrecognized option '%s'\n",
13014                                 progname, argv[optind - 1]);
13015                         fallthrough;
13016                 case 'h':
13017                         return CMD_HELP;
13018                 }
13019         }
13020
13021         while (optind < argc) {
13022                 int rc2;
13023
13024                 path = argv[optind++];
13025                 if (!realpath(path, fullpath)) {
13026                         fprintf(stderr, "%s: could not find path '%s': %s\n",
13027                                 argv[0], path, strerror(errno));
13028                         if (rc == 0)
13029                                 rc = -EINVAL;
13030                         continue;
13031                 }
13032
13033                 rc2 = llapi_pcc_detach_file(fullpath, detach_opt);
13034                 if (rc2 < 0) {
13035                         rc2 = -errno;
13036                         fprintf(stderr,
13037                                 "%s: cannot detach '%s' from PCC: %s\n",
13038                                 argv[0], path, strerror(errno));
13039                         if (rc == 0)
13040                                 rc = rc2;
13041                 }
13042         }
13043         return rc;
13044 }
13045
13046 static int lfs_pcc_detach_fid(int argc, char **argv)
13047 {
13048         struct option long_opts[] = {
13049         { .val = 'h',   .name = "help", .has_arg = no_argument },
13050         { .val = 'k',   .name = "keep", .has_arg = no_argument },
13051         { .name = NULL } };
13052         int c;
13053         int rc = 0;
13054         const char *fid;
13055         const char *mntpath;
13056         __u32 detach_opt = PCC_DETACH_OPT_UNCACHE;
13057
13058         optind = 0;
13059         while ((c = getopt_long(argc, argv, "hk",
13060                                 long_opts, NULL)) != -1) {
13061                 switch (c) {
13062                 case 'k':
13063                         detach_opt = PCC_DETACH_OPT_NONE;
13064                         break;
13065                 default:
13066                         fprintf(stderr, "%s: unrecognized option '%s'\n",
13067                                 progname, argv[optind - 1]);
13068                         fallthrough;
13069                 case 'h':
13070                         return CMD_HELP;
13071                 }
13072         }
13073
13074         mntpath = argv[optind++];
13075
13076         while (optind < argc) {
13077                 int rc2;
13078
13079                 fid = argv[optind++];
13080
13081                 rc2 = llapi_pcc_detach_fid_str(mntpath, fid, detach_opt);
13082                 if (rc2 < 0) {
13083                         fprintf(stderr,
13084                                 "%s: cannot detach '%s' on '%s' from PCC: %s\n",
13085                                 argv[0], fid, mntpath, strerror(-rc2));
13086                         if (rc == 0)
13087                                 rc = rc2;
13088                 }
13089         }
13090         return rc;
13091 }
13092
13093 static int lfs_pcc_state(int argc, char **argv)
13094 {
13095         int rc = 0;
13096         const char *path;
13097         char fullpath[PATH_MAX];
13098         struct lu_pcc_state state;
13099
13100         optind = 1;
13101
13102         if (argc <= 1) {
13103                 fprintf(stderr, "%s: must specify one or more file names\n",
13104                         progname);
13105                 return CMD_HELP;
13106         }
13107
13108         while (optind < argc) {
13109                 int rc2;
13110
13111                 path = argv[optind++];
13112                 if (!realpath(path, fullpath)) {
13113                         fprintf(stderr, "%s: could not find path '%s': %s\n",
13114                                 argv[0], path, strerror(errno));
13115                         if (rc == 0)
13116                                 rc = -EINVAL;
13117                         continue;
13118                 }
13119
13120                 rc2 = llapi_pcc_state_get(fullpath, &state);
13121                 if (rc2 < 0) {
13122                         if (rc == 0)
13123                                 rc = rc2;
13124                         fprintf(stderr,
13125                                 "%s: cannot get PCC state of '%s': %s\n",
13126                                 argv[0], path, strerror(-rc2));
13127                         continue;
13128                 }
13129
13130                 printf("file: %s", path);
13131                 printf(", type: %s", pcc_type2string(state.pccs_type));
13132                 if (state.pccs_type == LU_PCC_NONE &&
13133                     state.pccs_open_count == 0) {
13134                         printf("\n");
13135                         continue;
13136                 }
13137
13138                 printf(", PCC file: %s", state.pccs_path);
13139                 printf(", user number: %u", state.pccs_open_count);
13140                 printf(", flags: %x", state.pccs_flags);
13141                 printf("\n");
13142         }
13143         return rc;
13144 }
13145
13146 /**
13147  * lfs_pcc() - Parse and execute lfs pcc commands.
13148  * @argc: The count of lfs pcc command line arguments.
13149  * @argv: Array of strings for lfs pcc command line arguments.
13150  *
13151  * This function parses lfs pcc commands and performs the
13152  * corresponding functions specified in pcc_cmdlist[].
13153  *
13154  * Return: 0 on success or an error code on failure.
13155  */
13156 static int lfs_pcc(int argc, char **argv)
13157 {
13158         char cmd[PATH_MAX];
13159         int rc = 0;
13160
13161         setlinebuf(stdout);
13162
13163         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
13164         progname = cmd;
13165         program_invocation_short_name = cmd;
13166         rc = cfs_parser(argc, argv, pcc_cmdlist);
13167
13168         return rc < 0 ? -rc : rc;
13169 }
13170
13171 int main(int argc, char **argv)
13172 {
13173         int rc;
13174
13175         /* Ensure that liblustreapi constructor has run */
13176         if (!llapi_liblustreapi_initialized())
13177                 fprintf(stderr, "liblustreapi was not properly initialized\n");
13178
13179         setlinebuf(stdout);
13180         opterr = 0;
13181
13182         progname = program_invocation_short_name; /* Used in error messages */
13183         llapi_set_command_name(argv[1]);
13184         rc = cfs_parser(argc, argv, cmdlist);
13185         llapi_clear_command_name();
13186
13187         return rc < 0 ? -rc : rc;
13188 }
13189
13190 #ifdef _LUSTRE_IDL_H_
13191 /* Everything we need here should be included by lustreapi.h. */
13192 # error "lfs should not depend on lustre_idl.h"
13193 #endif /* _LUSTRE_IDL_H_ */