Whamcloud - gitweb
LU-930 utils: add --help option to lfs sub-commands
[fs/lustre-release.git] / lustre / utils / lfs.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * lustre/utils/lfs.c
32  *
33  * Author: Peter J. Braam <braam@clusterfs.com>
34  * Author: Phil Schwan <phil@clusterfs.com>
35  * Author: Robert Read <rread@clusterfs.com>
36  */
37
38 /* for O_DIRECTORY */
39 #ifndef _GNU_SOURCE
40 #define _GNU_SOURCE
41 #endif
42
43 #include <stdlib.h>
44 #include <stdio.h>
45 #include <inttypes.h>
46 #include <getopt.h>
47 #include <string.h>
48 #include <mntent.h>
49 #include <unistd.h>
50 #include <errno.h>
51 #include <err.h>
52 #include <pwd.h>
53 #include <grp.h>
54 #include <sys/ioctl.h>
55 #include <sys/quota.h>
56 #include <sys/time.h>
57 #include <sys/types.h>
58 #include <sys/stat.h>
59 #include <sys/param.h>
60 #include <sys/xattr.h>
61 #include <fcntl.h>
62 #include <dirent.h>
63 #include <time.h>
64 #include <ctype.h>
65 #include <zlib.h>
66 #include <libgen.h>
67 #include <asm/byteorder.h>
68 #include "lfs_project.h"
69
70 #include <libcfs/util/string.h>
71 #include <libcfs/util/ioctl.h>
72 #include <libcfs/util/parser.h>
73 #include <libcfs/util/string.h>
74 #include <lustre/lustreapi.h>
75 #include <linux/lustre/lustre_ver.h>
76 #include <linux/lustre/lustre_param.h>
77 #include <linux/lnet/nidstr.h>
78 #include <lnetconfig/cyaml.h>
79 #include "lstddef.h"
80
81 /* all functions */
82 static int lfs_find(int argc, char **argv);
83 static int lfs_getstripe(int argc, char **argv);
84 static int lfs_getdirstripe(int argc, char **argv);
85 static int lfs_setdirstripe(int argc, char **argv);
86 static int lfs_rmentry(int argc, char **argv);
87 static int lfs_unlink_foreign(int argc, char **argv);
88 static int lfs_osts(int argc, char **argv);
89 static int lfs_mdts(int argc, char **argv);
90 static int lfs_df(int argc, char **argv);
91 static int lfs_getname(int argc, char **argv);
92 static int lfs_check(int argc, char **argv);
93 #ifdef HAVE_SYS_QUOTA_H
94 static int lfs_setquota(int argc, char **argv);
95 static int lfs_quota(int argc, char **argv);
96 static int lfs_project(int argc, char **argv);
97 #endif
98 static int lfs_flushctx(int argc, char **argv);
99 static int lfs_poollist(int argc, char **argv);
100 static int lfs_changelog(int argc, char **argv);
101 static int lfs_changelog_clear(int argc, char **argv);
102 static int lfs_fid2path(int argc, char **argv);
103 static int lfs_path2fid(int argc, char **argv);
104 static int lfs_rmfid(int argc, char **argv);
105 static int lfs_data_version(int argc, char **argv);
106 static int lfs_hsm_state(int argc, char **argv);
107 static int lfs_hsm_set(int argc, char **argv);
108 static int lfs_hsm_clear(int argc, char **argv);
109 static int lfs_hsm_action(int argc, char **argv);
110 static int lfs_hsm_archive(int argc, char **argv);
111 static int lfs_hsm_restore(int argc, char **argv);
112 static int lfs_hsm_release(int argc, char **argv);
113 static int lfs_hsm_remove(int argc, char **argv);
114 static int lfs_hsm_cancel(int argc, char **argv);
115 static int lfs_swap_layouts(int argc, char **argv);
116 static int lfs_mv(int argc, char **argv);
117 static int lfs_ladvise(int argc, char **argv);
118 static int lfs_getsom(int argc, char **argv);
119 static int lfs_heat_get(int argc, char **argv);
120 static int lfs_heat_set(int argc, char **argv);
121 static int lfs_mirror(int argc, char **argv);
122 static int lfs_mirror_list_commands(int argc, char **argv);
123 static int lfs_list_commands(int argc, char **argv);
124 static inline int lfs_mirror_resync(int argc, char **argv);
125 static inline int lfs_mirror_verify(int argc, char **argv);
126 static inline int lfs_mirror_read(int argc, char **argv);
127 static inline int lfs_mirror_write(int argc, char **argv);
128 static inline int lfs_mirror_copy(int argc, char **argv);
129 static int lfs_pcc_attach(int argc, char **argv);
130 static int lfs_pcc_attach_fid(int argc, char **argv);
131 static int lfs_pcc_detach(int argc, char **argv);
132 static int lfs_pcc_detach_fid(int argc, char **argv);
133 static int lfs_pcc_state(int argc, char **argv);
134 static int lfs_pcc(int argc, char **argv);
135 static int lfs_pcc_list_commands(int argc, char **argv);
136 static int lfs_migrate_to_dom(int fd, int fdv, char *name,
137                               __u64 migration_flags,
138                               struct llapi_stripe_param *param,
139                               struct llapi_layout *layout);
140
141 struct pool_to_id_cbdata {
142         const char *pool;
143         __u32 id;
144 };
145 static int find_comp_id_by_pool(struct llapi_layout *layout, void *cbdata);
146 static int find_mirror_id_by_pool(struct llapi_layout *layout, void *cbdata);
147
148 enum setstripe_origin {
149         SO_SETSTRIPE,
150         SO_MIGRATE,
151         SO_MIGRATE_MDT,
152         SO_MIRROR_CREATE,
153         SO_MIRROR_EXTEND,
154         SO_MIRROR_SPLIT,
155         SO_MIRROR_DELETE,
156 };
157
158 static int lfs_setstripe_internal(int argc, char **argv,
159                                   enum setstripe_origin opc);
160
161 static inline int lfs_setstripe(int argc, char **argv)
162 {
163         return lfs_setstripe_internal(argc, argv, SO_SETSTRIPE);
164 }
165
166 static inline int lfs_setstripe_migrate(int argc, char **argv)
167 {
168         return lfs_setstripe_internal(argc, argv, SO_MIGRATE);
169 }
170
171 static inline int lfs_mirror_create(int argc, char **argv)
172 {
173         return lfs_setstripe_internal(argc, argv, SO_MIRROR_CREATE);
174 }
175
176 static inline int lfs_mirror_extend(int argc, char **argv)
177 {
178         return lfs_setstripe_internal(argc, argv, SO_MIRROR_EXTEND);
179 }
180
181 static inline int lfs_mirror_split(int argc, char **argv)
182 {
183         return lfs_setstripe_internal(argc, argv, SO_MIRROR_SPLIT);
184 }
185
186 static inline int lfs_mirror_delete(int argc, char **argv)
187 {
188         return lfs_setstripe_internal(argc, argv, SO_MIRROR_DELETE);
189 }
190
191 /* Setstripe and migrate share mostly the same parameters */
192 #define SSM_CMD_COMMON(cmd) \
193         "usage: "cmd" [--component-end|-E COMP_END]\n"                  \
194         "                 [--stripe-count|-c STRIPE_COUNT]\n"           \
195         "                 [--overstripe-count|-C STRIPE_COUNT]\n"       \
196         "                 [--stripe-index|-i START_OST_IDX]\n"          \
197         "                 [--stripe-size|-S STRIPE_SIZE]\n"             \
198         "                 [--extension-size|--ext-size|-z]\n"           \
199         "                 [--help|-h] [--layout|-L PATTERN]\n"          \
200         "                 [--mirror_count|-N[MIRROR_COUNT]]\n"          \
201         "                 [--ost|-o OST_INDICES]\n"                     \
202         "                 [--pool|-p POOL_NAME]\n"                      \
203         "                 [--yaml|-y YAML_TEMPLATE_FILE]\n"             \
204         "                 [--copy=LUSTRE_SRC]\n"
205
206 #define SSM_HELP_COMMON \
207         "\tSTRIPE_COUNT: Number of OSTs to stripe on (0=fs default, -1 all)\n" \
208         "\t              Using -C instead of -c allows overstriping, which\n"  \
209         "\t              will place more than one stripe per OST if\n"         \
210         "\t              stripe_count is greater than the number of OSTs.\n"   \
211         "\tSTART_OST_IDX: OST index of first stripe (-1=default round robin)\n"\
212         "\tSTRIPE_SIZE:  Number of bytes on each OST (0=fs default)\n"         \
213         "\t              Optional K, M, or G suffix (for KB, MB, GB\n"         \
214         "\t              respectively).  Must be a multiple of 64KiB.\n"       \
215         "\tEXTENSION_SIZE:\n"                                                  \
216         "\t              Number of bytes the previous component is extended\n" \
217         "\t              each time. Optional K, M, or G suffix (for KB,\n"     \
218         "\t              MB, GB respectively)\n"                               \
219         "\tPOOL_NAME:    Name of OST pool to use (default none)\n"             \
220         "\tLAYOUT:       stripe pattern type: raid0, mdt (default raid0)\n"    \
221         "\tOST_INDICES:  List of OST indices, can be repeated multiple times\n"\
222         "\t              Indices be specified in a format of:\n"               \
223         "\t                -o OST_1,OST_I-OST_J,OST_N\n"                       \
224         "\t              Or:\n"                                                \
225         "\t                -o OST_1 -o OST_I-OST_J -o OST_N\n"                 \
226         "\t              If --pool is set with --ost then the OSTs\n"          \
227         "\t              must be the members of the pool.\n"                   \
228         "\tCOMP_END:     Extent end of component, start after previous end.\n" \
229         "\t              Optional K, M, or G suffix (for KiB, MiB, GiB), or\n" \
230         "\t              -1 or 'eof' for max file size). Must be a multiple\n" \
231         "\t              of stripe_size and a multiple of 64KiB.\n"            \
232         "\tYAML_TEMPLATE_FILE:\n"                                              \
233         "\t              YAML layout template file, can't be used with -c,\n"  \
234         "\t              -i, -S, -p, -o, or -E arguments.\n"                   \
235         "\tLUSTRE_SRC:   Lustre file/dir whose layout info is used to set\n"   \
236         "\t              another lustre file or directory, can't used with\n"  \
237         "\t              -c, -i, -S, -p, -o, or -E arguments.\n"
238
239 #define MIRROR_CREATE_HELP                                                     \
240         "\tMIRROR_COUNT: Number of mirrors to be created with the upcoming\n"  \
241         "\t              setstripe layout options\n"                           \
242         "\t              It defaults to 1 if not specified; if specified,\n"   \
243         "\t              it must follow the option without a space.\n"         \
244         "\t              The option can also be repeated multiple times to\n"  \
245         "\t              separate mirrors that have different layouts.\n"      \
246         "\tSETSTRIPE_OPTIONS: Mirror layout as with 'setstripe'\n"             \
247         "\t              It can be a plain layout or a composite layout.\n"    \
248         "\t              If not specified, the stripe options inherited\n"     \
249         "\t              from the previous component will be used.\n"          \
250         "\tFLAGS:        set flags to the component of the current mirror.\n"  \
251         "\t              Only \"prefer\" flag is supported so far.\n"
252
253 #define MIRROR_EXTEND_HELP                                                     \
254         MIRROR_CREATE_HELP                                                     \
255         "\tVICTIM_FILE:  The layout of victim_file will be split and used\n"   \
256         "\t              as a mirror added to the mirrored file.\n"            \
257         "\tno-verify:    This option indicates not to verify the mirror(s)\n"  \
258         "\t              from victim file(s) in case the victim file(s)\n"     \
259         "\t              contains the same data as the original mirrored\n"    \
260         "\t              file.\n"
261
262 #define MIRROR_EXTEND_USAGE                                                    \
263         "                 {--mirror-count|-N[mirror_count]}\n"                 \
264         "                 [SETSTRIPE_OPTIONS|-f|--file VICTIM_FILE]\n"         \
265         "                 [--no-verify]\n"
266
267 #define SETSTRIPE_USAGE                                                 \
268         SSM_CMD_COMMON("setstripe")                                     \
269         MIRROR_EXTEND_USAGE                                             \
270         "                 <directory|filename>\n"                       \
271         SSM_HELP_COMMON                                                 \
272         MIRROR_EXTEND_HELP
273
274 #define MIGRATE_USAGE                                                   \
275         SSM_CMD_COMMON("migrate  ")                                     \
276         "                 [--block|-b] [--non-block|-n]\n"              \
277         "                 [--non-direct|-D] [--verbose|-v]\n"           \
278         "                 <filename>\n"                                 \
279         SSM_HELP_COMMON                                                 \
280         "\n"                                                            \
281         "\tblock:        Block file access during data migration (default)\n" \
282         "\tnon-block:    Abort migrations if concurrent access is detected\n" \
283         "\tnon-direct:   Do not use direct I/O to copy file contents\n" \
284         "\tverbose:      Print each filename as it is migrated\n"       \
285
286 #define SETDIRSTRIPE_USAGE                                              \
287         "               [--mdt-count|-c stripe_count>\n"                \
288         "               [--help|-h] [--mdt-hash|-H mdt_hash]\n"         \
289         "               [--mdt-index|-i mdt_index[,mdt_index,...]\n"    \
290         "               [--default|-D] [--mode|-o mode]\n"              \
291         "               [--max-inherit|-X max_inherit]\n"               \
292         "               [--max-inherit-rr max_inherit_rr] <dir>\n"      \
293         "\tstripe_count: stripe count of the striped directory\n"       \
294         "\tmdt_index: MDT index of first stripe\n"                      \
295         "\tmdt_hash:  hash type of the striped directory. mdt types:\n" \
296         "       crush     CRUSH hash algorithm (default)\n" \
297         "       fnv_1a_64 FNV-1a hash algorithm\n"              \
298         "       all_char  sum of characters % MDT_COUNT (not recommended)\n" \
299         "\tdefault_stripe: set default dirstripe of the directory\n"    \
300         "\tmode: the file access permission of the directory (octal)\n" \
301         "To create dir with a foreign (free format) layout :\n"         \
302         "setdirstripe|mkdir --foreign[=FOREIGN_TYPE] -x|-xattr STRING " \
303                 "[--mode|-o MODE] [--flags HEX] <dir>\n" \
304         "\tmode: the file access permissions of the directory\n"        \
305         "\tforeign_type: none, daos, symlink, or numeric value\n"
306
307 /**
308  * command_t mirror_cmdlist - lfs mirror commands.
309  */
310 command_t mirror_cmdlist[] = {
311         { .pc_name = "create", .pc_func = lfs_mirror_create,
312           .pc_help = "Create a mirrored file.\n"
313                 "usage: lfs mirror create {--mirror-count|-N[MIRROR_COUNT]}\n"
314                 "\t\t[SETSTRIPE_OPTIONS] <filename|directory> ...\n"
315           MIRROR_CREATE_HELP },
316         { .pc_name = "delete", .pc_func = lfs_mirror_delete,
317           .pc_help = "Delete a mirror from a file.\n"
318         "usage: lfs mirror delete {--mirror-id MIRROR_ID|-p POOL|\n"
319         "\t               --component-id|--comp-id|-I COMP_ID} <mirror_file>\n"
320         },
321         { .pc_name = "extend", .pc_func = lfs_mirror_extend,
322           .pc_help = "Extend a mirrored file.\n"
323                 "usage: lfs mirror extend {--mirror-count|-N[MIRROR_COUNT]}\n"
324                 "\t\t[--no-verify] [SETSTRIPE_OPTIONS|-f VICTIM_FILE] ... <filename> ...\n"
325           MIRROR_EXTEND_HELP },
326         { .pc_name = "split", .pc_func = lfs_mirror_split,
327           .pc_help = "Split a mirrored file.\n"
328         "usage: lfs mirror split [--destroy|-d] [-f NEW_FILE] [--help|-h]\n"
329         "\t\t{--mirror-id MIRROR_ID|--component-id|-I COMP_ID|-p POOL}\n"
330         "\t\t<mirrored file> ...\n"
331         "\tMIRROR_ID: The numerical unique identifier for a mirror.\n"
332         "\t           It can be fetched by the 'lfs getstripe' command.\n"
333         "\tCOMP_ID:   Unique component ID within a mirror.\n"
334         "\tPOOL:      Components using specified pool.\n"
335         "\tNEW_FILE:  This option indicates the layout of the split\n"
336         "\t           mirror will be stored into. If not specified,\n"
337         "\t           a new file named <mirrored_file>.mirror~MIRROR_ID\n"
338         "\t           will be used.\n" },
339         { .pc_name = "read", .pc_func = lfs_mirror_read,
340           .pc_help = "Read the content of a specified mirror of a file.\n"
341                 "usage: lfs mirror read {--mirror-id|-N MIRROR_ID}\n"
342                 "\t\t[--outfile|-o <output_file>] <mirrored_file>\n" },
343         { .pc_name = "write", .pc_func = lfs_mirror_write,
344           .pc_help = "Write to a specified mirror of a file.\n"
345                 "usage: lfs mirror write {--mirror-id|-N MIRROR_ID}\n"
346                 "\t\t[--inputfile|-i <input_file>] <mirrored_file>\n" },
347         { .pc_name = "copy", .pc_func = lfs_mirror_copy,
348           .pc_help = "Copy a specified mirror to other mirror(s) of a file.\n"
349                 "usage: lfs mirror copy {--read-mirror|-i MIRROR_ID0}\n"
350                 "\t\t{--write-mirror|-o MIRROR_ID1[,...]} <mirrored_file>\n" },
351         { .pc_name = "resync", .pc_func = lfs_mirror_resync,
352           .pc_help = "Resynchronizes out-of-sync mirrored file(s).\n"
353                 "usage: lfs mirror resync [--only MIRROR_ID[,...]>]\n"
354                 "\t\t<mirrored_file> [<mirrored_file2>...]\n" },
355         { .pc_name = "verify", .pc_func = lfs_mirror_verify,
356           .pc_help = "Verify mirrored file(s).\n"
357                 "usage: lfs mirror verify [--only MIRROR_ID[,...]]\n"
358                 "\t\t[--verbose|-v] <mirrored_file> [<mirrored_file2> ...]\n" },
359         { .pc_name = "list-commands", .pc_func = lfs_mirror_list_commands,
360           .pc_help = "list commands supported by lfs mirror"},
361         { .pc_name = "help", .pc_func = Parser_help, .pc_help = "help" },
362         { .pc_name = "exit", .pc_func = Parser_quit, .pc_help = "quit" },
363         { .pc_name = "quit", .pc_func = Parser_quit, .pc_help = "quit" },
364         { .pc_help = NULL }
365 };
366
367 /**
368  * command_t pcc_cmdlist - lfs pcc commands.
369  */
370 command_t pcc_cmdlist[] = {
371         { .pc_name = "attach", .pc_func = lfs_pcc_attach,
372           .pc_help = "Attach given files to the Persistent Client Cache.\n"
373                 "usage: lfs pcc attach <--id|-i NUM> <file> ...\n"
374                 "\t-i: archive id for RW-PCC\n" },
375         { .pc_name = "attach_fid", .pc_func = lfs_pcc_attach_fid,
376           .pc_help = "Attach given files into PCC by FID(s).\n"
377                 "usage: lfs pcc attach_id {--id|-i NUM} {--mnt|-m MOUNTPOINT} FID ...\n"
378                 "\t-i: archive id for RW-PCC\n"
379                 "\t-m: Lustre mount point\n" },
380         { .pc_name = "state", .pc_func = lfs_pcc_state,
381           .pc_help = "Display the PCC state for given files.\n"
382                 "usage: lfs pcc state <file> ...\n" },
383         { .pc_name = "detach", .pc_func = lfs_pcc_detach,
384           .pc_help = "Detach given files from the Persistent Client Cache.\n"
385                 "usage: lfs pcc detach <file> ...\n" },
386         { .pc_name = "detach_fid", .pc_func = lfs_pcc_detach_fid,
387           .pc_help = "Detach given files from PCC by FID(s).\n"
388                 "usage: lfs pcc detach_fid <mntpath> <fid>...\n" },
389         { .pc_name = "list-commands", .pc_func = lfs_pcc_list_commands,
390           .pc_help = "list commands supported by lfs pcc"},
391         { .pc_name = "help", .pc_func = Parser_help, .pc_help = "help" },
392         { .pc_name = "exit", .pc_func = Parser_quit, .pc_help = "quit" },
393         { .pc_name = "quit", .pc_func = Parser_quit, .pc_help = "quit" },
394         { .pc_help = NULL }
395 };
396
397 /* all available commands */
398 command_t cmdlist[] = {
399         {"setstripe", lfs_setstripe, 0,
400          "To create a file with specified striping/composite layout, or\n"
401          "create/replace the default layout on an existing directory:\n"
402          SSM_CMD_COMMON("setstripe")
403          "                 [--mode MODE]\n"
404          "                 <directory|filename>\n"
405          " or\n"
406          "To add component(s) to an existing composite file:\n"
407          SSM_CMD_COMMON("setstripe --component-add")
408          SSM_HELP_COMMON
409          "To totally delete the default striping from an existing directory:\n"
410          "usage: setstripe [--delete|-d] <directory>\n"
411          " or\n"
412          "To create a mirrored file or set s default mirror layout on a directory:\n"
413          "usage: setstripe {--mirror-count|-N}[MIRROR_COUNT] [SETSTRIPE_OPTIONS] <directory|filename>\n"
414          " or\n"
415          "To delete the last component(s) from an existing composite file\n"
416          "(note that this will also delete any data in those components):\n"
417          "usage: setstripe --component-del [--component-id|-I COMP_ID]\n"
418          "                               [--component-flags|-F COMP_FLAGS]\n"
419          "                               <filename>\n"
420          "\tCOMP_ID:     Unique component ID to delete\n"
421          "\tCOMP_FLAGS:  'init' indicating all instantiated components\n"
422          "\t             '^init' indicating all uninstantiated components\n"
423          "\t-I and -F cannot be specified at the same time\n"
424          " or\n"
425          "To set or clear flags on a specific component\n"
426          "(note that this command can only be applied to mirrored files:\n"
427          "usage: setstripe --comp-set {-I COMP_ID|--comp-flags=COMP_FLAGS}\n"
428          "                            <filename>\n"
429          " or\n"
430          "To create a file with a foreign (free format) layout:\n"
431          "usage: setstripe --foreign[=FOREIGN_TYPE]\n"
432          "                 --xattr|-x LAYOUT_STRING [--flags HEX]\n"
433          "                 [--mode MODE] <filename>\n"},
434         {"getstripe", lfs_getstripe, 0,
435          "To list the layout pattern for a given file or files in a\n"
436          "directory or recursively for all files in a directory tree.\n"
437          "usage: getstripe [--ost|-O UUID] [--quiet|-q] [--verbose|-v]\n"
438          "                 [--stripe-count|-c] [--stripe-index|-i] [--fid|-F]\n"
439          "                 [--pool|-p] [--stripe-size|-S] [--directory|-d]\n"
440          "                 [--mdt-index|-m] [--recursive|-r] [--raw|-R]\n"
441          "                 [--layout|-L] [--generation|-g] [--yaml|-y]\n"
442          "                 [--help|-h] [--component-id|-I[=COMP_ID]]\n"
443          "                 [--component-flags[=COMP_FLAGS]]\n"
444          "                 [--component-count]\n"
445          "                 [--extension-size|--ext-size|-z]\n"
446          "                 [--component-start[=[+-]COMP_START]]\n"
447          "                 [--component-end[=[+-]COMP_END]|-E[[+-]comp_end]]\n"
448          "                 [[!] --mirror-index=[+-]INDEX |\n"
449          "                 [!] --mirror-id=[+-]MIRROR_ID] [--mirror-count|-N]\n"
450          "                 <directory|filename> ..."},
451         {"setdirstripe", lfs_setdirstripe, 0,
452          "Create striped directory on specified MDT, same as mkdir.\n"
453          "May be restricted to root or group users, depending on settings.\n"
454          "usage: setdirstripe [OPTION] <directory>\n"
455          SETDIRSTRIPE_USAGE},
456         {"getdirstripe", lfs_getdirstripe, 0,
457          "To list the layout pattern info for a given directory\n"
458          "or recursively for all directories in a directory tree.\n"
459          "usage: getdirstripe [--mdt-count|-c] [--mdt-index|-m|-i]\n"
460          "                    [--help|-h] [--mdt-hash|-H] [--obd|-O UUID]\n"
461          "                    [--recursive|-r] [--yaml|-y]\n"
462          "                    [--verbose|-v] [--default|-D]\n"
463          "                    [--max-inherit|-X]\n"
464          "                    [--max-inherit-rr] <dir> ..."},
465         {"mkdir", lfs_setdirstripe, 0,
466          "Create striped directory on specified MDT, same as setdirstripe.\n"
467          "usage: mkdir [OPTION] <directory>\n"
468          SETDIRSTRIPE_USAGE},
469         {"rm_entry", lfs_rmentry, 0,
470          "To remove the name entry of the remote directory. Note: This\n"
471          "command will only delete the name entry, i.e. the remote directory\n"
472          "will become inaccessable after this command. This can only be done\n"
473          "by the administrator\n"
474          "usage: rm_entry <dir>\n"},
475         {"unlink_foreign", lfs_unlink_foreign, 0,
476          "To remove the foreign file/dir.\n"
477          "Note: This is for files/dirs prevented to be removed using\n"
478          "unlink/rmdir, but works also for regular ones\n"
479          "usage: unlink_foreign <foreign_dir/file> [<foreign_dir/file> ...]\n"},
480         {"pool_list", lfs_poollist, 0,
481          "List pools or pool OSTs\n"
482          "usage: pool_list <fsname>[.<pool>] | <pathname>\n"},
483         {"find", lfs_find, 0,
484          "find files matching given attributes recursively in directory tree.\n"
485          "usage: find <directory|filename> ...\n"
486          "     [[!] --atime|-A [+-]N[smhdwy]] [[!] --ctime|-C [+-]N[smhdwy]]\n"
487          "     [[!] --mtime|-M [+-]N[smhdwy]]\n"
488          "     [[!] --btime|--Btime|-B [+-]N[smhdwy]] [--help|-h]\n"
489          "     [[!] --newer[XY] <reference>] [[!] --blocks|-b N]\n"
490          "     [--maxdepth|-D N] [[!] --mdt-index|--mdt|-m <uuid|index,...>]\n"
491          "     [[!] --name|-n <pattern>] [[!] --ost|-O <uuid|index,...>]\n"
492          "     [[!] --perm [/-]mode] [[!] --pool <pool>] [--print|-P]\n"
493          "     [--print0|-0] [[!] --projid <projid>]\n"
494          "     [[!] --size|-s [+-]N[bkMGTPE]]\n"
495          "     [[!] --stripe-count|-c [+-]<stripes>]\n"
496          "     [[!] --stripe-index|-i <index,...>]\n"
497          "     [[!] --stripe-size|-S [+-]N[kMGT]] [[!] --type|-t <filetype>]\n"
498          "     [[!] --extension-size|--ext-size|-z [+-]N[kMGT]]\n"
499          "     [[!] --gid|-g|--group|-G <gid>|<gname>]\n"
500          "     [[!] --uid|-u|--user|-U <uid>|<uname>]\n"
501          "     [[!] --layout|-L released,raid0,mdt]\n"
502          "     [[!] --foreign[=<foreign_type>]]\n"
503          "     [[!] --component-count [+-]<comp_cnt>]\n"
504          "     [[!] --component-start [+-]N[kMGTPE]]\n"
505          "     [[!] --component-end|-E [+-]N[kMGTPE]]\n"
506          "     [[!] --component-flags {init,stale,prefer,offline,nosync,extension}]\n"
507          "     [[!] --mirror-count|-N [+-]<n>]\n"
508          "     [[!] --mirror-state <[^]state>]\n"
509          "     [[!] --mdt-count|-T [+-]<stripes>]\n"
510          "     [[!] --mdt-hash|-H <[^][blm],[^]fnv_1a_64,all_char,crush,...>\n"
511          "     [[!] --mdt-index|-m <uuid|index,...>]\n"
512          "\t !: used before an option indicates 'NOT' requested attribute\n"
513          "\t -: used before a value indicates less than requested value\n"
514          "\t +: used before a value indicates more than requested value\n"
515          "\t ^: used before a flag indicates to exclude it\n"},
516         {"check", lfs_check, 0,
517          "Display the status of MGTs, MDTs or OSTs (as specified in the command)\n"
518          "or all the servers (MGTs, MDTs and OSTs).\n"
519          "usage: check {mgts|osts|mdts|all}"},
520         {"osts", lfs_osts, 0, "list OSTs connected to client "
521          "[for specified path only]\n" "usage: osts [path]"},
522         {"mdts", lfs_mdts, 0, "list MDTs connected to client "
523          "[for specified path only]\n" "usage: mdts [path]"},
524         {"df", lfs_df, 0,
525          "report filesystem disk space usage or inodes usage "
526          "of each MDS and all OSDs or a batch belonging to a specific pool.\n"
527          "Usage: df [--inodes|-i] [--human-readable|-h] [--lazy|-l]\n"
528          "          [--pool|-p <fsname>[.<pool>]] [path]"},
529         {"getname", lfs_getname, 0,
530          "list instances and specified mount points [for specified path only]\n"
531          "Usage: getname [--help|-h] [--instance|-i] [--fsname|-n] [path ...]"},
532 #ifdef HAVE_SYS_QUOTA_H
533         {"setquota", lfs_setquota, 0, "Set filesystem quotas.\n"
534          "usage: setquota {-u|-g|-p} UNAME|UID|GNAME|GID|PROJID\n"
535          "                -b BLOCK_SOFTLIMIT -B BLOCK_HARDLIMIT\n"
536          "                -i INODE_SOFTLIMIT -I INODE_HARDLIMIT <filesystem>\n"
537          "       setquota {-u|--user USER|UID|-g|--group GROUP|GID|-p|--projid PROJID}\n"
538          "                [--block-softlimit BLOCK_SOFTLIMIT]\n"
539          "                [--block-hardlimit BLOCK_HARDLIMIT]\n"
540          "                [--inode-softlimit INODE_SOFTLIMIT]\n"
541          "                [--inode-hardlimit INODE_HARDLIMIT] <filesystem>\n"
542          "       setquota [-t] {-h|--help|-u|--user|-g|--group|-p|--projid}\n"
543          "                [--block-grace 'notify'|BLOCK_GRACE]\n"
544          "                [--inode-grace 'notify'|INODE_GRACE] <filesystem>\n"
545          "       setquota {-U|-G|-P}\n"
546          "                -b BLOCK_SOFTLIMIT -B BLOCK_HARDLIMIT\n"
547          "                -i INODE_SOFTLIMIT -I INODE_HARDLIMIT <filesystem>\n"
548          "       setquota {-U|--default-usr|-G|--default-grp|-P|--default-prj}\n"
549          "                [--block-softlimit BLOCK_SOFTLIMIT]\n"
550          "                [--block-hardlimit BLOCK_HARDLIMIT]\n"
551          "                [--inode-softlimit INODE_SOFTLIMIT]\n"
552          "                [--inode-hardlimit INODE_HARDLIMIT] <filesystem>\n"
553          "       setquota {-u|-g|-p} UNAME|UID|GNAME|GID|PROJID\n"
554          "                {-d|--default}\n"
555          "       -b can be used instead of --block-softlimit/--block-grace\n"
556          "       -B can be used instead of --block-hardlimit\n"
557          "       -i can be used instead of --inode-softlimit/--inode-grace\n"
558          "       -I can be used instead of --inode-hardlimit\n"
559          "       -d can be used instead of --default\n\n"
560          "Note: The total quota space will be split into many qunits and\n"
561          "      balanced over all server targets, the minimal qunit size is\n"
562          "      1M bytes for block space and 1K inodes for inode space.\n\n"
563          "      The maximum quota grace time is 2^48 - 1 seconds.\n\n"
564          "      Quota space rebalancing process will stop when this mininum\n"
565          "      value is reached. As a result, quota exceeded can be returned\n"
566          "      while many targets still have 1MB or 1K inodes of spare\n"
567          "      quota space.\n\n"
568          "      When setting the grace time, 'notify' can be used as grace to\n"
569          "      be notified after the quota is over soft limit but prevents\n"
570          "      the soft limit from becoming the hard limit."},
571         {"quota", lfs_quota, 0, "Display disk usage and limits.\n"
572          "usage: quota [-q] [-v] [-h] [-o OBD_UUID|-i MDT_IDX|-I OST_IDX]\n"
573          "             [{-u|-g|-p} UNAME|UID|GNAME|GID|PROJID] <filesystem>\n"
574          "       quota [-o OBD_UUID|-i MDT_IDX|-I OST_IDX] -t {-u|-g|-p} <filesystem>\n"
575         "        quota [-q] [-v] [h] {-U|-G|-P} <filesystem>"},
576         {"project", lfs_project, 0,
577          "Change or list project attribute for specified file or directory.\n"
578          "usage: project [-d|-r] <file|directory...>\n"
579          "         list project ID and flags on file(s) or directories\n"
580          "       project [-p id] [-s] [-r] <file|directory...>\n"
581          "         set project ID and/or inherit flag for specified file(s) or directories\n"
582          "       project -c [-d|-r [-p id] [-0]] <file|directory...>\n"
583          "         check project ID and flags on file(s) or directories, print outliers\n"
584          "       project -C [-r] [-k] <file|directory...>\n"
585          "         clear the project inherit flag and ID on the file or directory\n"
586         },
587 #endif
588         {"flushctx", lfs_flushctx, 0,
589          "Flush security context for current user.\n"
590          "usage: flushctx [-k] [-r] [mountpoint...]"},
591         {"changelog", lfs_changelog, 0,
592          "Show the metadata changes on an MDT."
593          "\nusage: changelog <mdtname> [startrec [endrec]]"},
594         {"changelog_clear", lfs_changelog_clear, 0,
595          "Indicate that old changelog records up to <endrec> are no longer of "
596          "interest to consumer <id>, allowing the system to free up space.\n"
597          "An <endrec> of 0 means all records.\n"
598          "usage: changelog_clear <mdtname> <id> <endrec>"},
599         {"fid2path", lfs_fid2path, 0,
600          "Resolve the full path(s) for given FID(s). For a specific hardlink "
601          "specify link number <linkno>.\n"
602          "usage: fid2path [--print-fid|-f] [--print-link|-c] [--link|-l <linkno>] "
603          "<fsname|root> <fid>..."},
604         {"path2fid", lfs_path2fid, 0, "Display the fid(s) for a given path(s).\n"
605          "usage: path2fid [--parents] <path> ..."},
606         {"rmfid", lfs_rmfid, 0, "Remove file(s) by FID(s)\n"
607          "usage: rmfid <fsname|rootpath> <fid> ..."},
608         {"data_version", lfs_data_version, 0, "Display file data version for "
609          "a given path.\n" "usage: data_version [-n|-r|-w] <path>"},
610         {"hsm_state", lfs_hsm_state, 0, "Display the HSM information (states, "
611          "undergoing actions) for given files.\n usage: hsm_state <file> ..."},
612         {"hsm_set", lfs_hsm_set, 0, "Set HSM user flag on specified files.\n"
613          "usage: hsm_set [--norelease] [--noarchive] [--dirty] [--exists] "
614          "[--archived] [--lost] [--archive-id NUM] <file> ..."},
615         {"hsm_clear", lfs_hsm_clear, 0, "Clear HSM user flag on specified "
616          "files.\n"
617          "usage: hsm_clear [--norelease] [--noarchive] [--dirty] [--exists] "
618          "[--archived] [--lost] <file> ..."},
619         {"hsm_action", lfs_hsm_action, 0, "Display current HSM request for "
620          "given files.\n" "usage: hsm_action <file> ..."},
621         {"hsm_archive", lfs_hsm_archive, 0,
622          "Archive file to external storage.\n"
623          "usage: hsm_archive [--filelist FILELIST] [--data DATA] [--archive NUM] "
624          "<file> ..."},
625         {"hsm_restore", lfs_hsm_restore, 0,
626          "Restore file from external storage.\n"
627          "usage: hsm_restore [--filelist FILELIST] [--data DATA] <file> ..."},
628         {"hsm_release", lfs_hsm_release, 0,
629          "Release files from Lustre.\n"
630          "usage: hsm_release [--filelist FILELIST] [--data DATA] <file> ..."},
631         {"hsm_remove", lfs_hsm_remove, 0,
632          "Remove file copy from external storage.\n"
633          "usage: hsm_remove [--filelist FILELIST] [--data DATA] "
634          "[--archive NUM]\n"
635          "                  (FILE [FILE ...] | "
636          "--mntpath MOUNTPATH FID [FID ...])\n"
637          "\n"
638          "Note: To remove an archived copy of a file already deleted from a "
639          "Lustre FS, the\n"
640          "--mntpath option and a list of FIDs must be specified"
641         },
642         {"hsm_cancel", lfs_hsm_cancel, 0,
643          "Cancel requests related to specified files.\n"
644          "usage: hsm_cancel [--filelist FILELIST] [--data DATA] <file> ..."},
645         {"swap_layouts", lfs_swap_layouts, 0, "Swap layouts between 2 files.\n"
646          "usage: swap_layouts <path1> <path2>"},
647         {"migrate", lfs_setstripe_migrate, 0,
648          "migrate a directory between MDTs.\n"
649          "usage: migrate [--mdt-count|-c STRIPE_COUNT]\n"
650          "               [--mdt-hash|-H HASH_TYPE]\n"
651          "               [--mdt-index|-m START_MDT_INDEX] [--verbose|-v]\n"
652          "               <directory>\n"
653          "\tmdt:        MDTs to stripe over, if only one MDT is specified\n"
654          "                      it's the MDT index of first stripe\n"
655          "\tmdt_count:  number of MDTs to stripe a directory over\n"
656          "\tmdt_hash:   hash type of the striped directory. mdt types:\n"
657          "              all_char  (type 1)sum of characters % MDT_COUNT\n"
658          "              fnv_1a_64 (type 2)FNV-1a hash algorithm (default)\n"
659          "              crush     (type 3)CRUSH hash algorithm\n"
660          "\n"
661          "migrate file objects from one OST "
662          "layout\nto another (may be not safe with concurent writes).\n"
663          "usage: migrate [--stripe-count|-c STRIPE_COUNT]\n"
664          "               [--overstripe-count|-C STRIPE_COUNT]\n"
665          "               [--stripe-index|-i START_OST_INDEX]\n"
666          "               [--stripe-size|-S STRIPE_SIZE]\n"
667          "               [--pool|-p <pool_name>] [--ost|-o OST_INDICES]\n"
668          "               [--block|-b] [--non-block|-n] [--non-direct|-D]\n"
669          "               <file|directory>\n"
670          "\tstripe_count:   number of OSTs to stripe a file over\n"
671          "\t                Using -C instead of -c allows overstriping, which\n"
672          "\t                will place more than one stripe per OST if\n"
673          "\t                stripe_count is greater than the number of OSTs\n"
674          "\tstripe_ost_index: index of the first OST to stripe a file over\n"
675          "\tstripe_size:      number of bytes to store before moving to the next OST\n"
676          "\tpool_name:        name of the predefined pool of OSTs\n"
677          "\tost_indices:      OSTs to stripe over, in order\n"
678          "\tblock:        Block file access during data migration (default)\n"
679          "\tnon-block:    Abort migrations if concurrent access is detected\n"
680          "\tnon-direct:       do not use direct I/O to copy file contents.\n"},
681         {"mv", lfs_mv, 0,
682          "To move directories between MDTs. This command is deprecated, "
683          "use \"migrate\" instead.\n"
684          "usage: mv <directory|filename> [--mdt-index|-m MDT_INDEX] "
685          "[--verbose|-v]\n"},
686         {"ladvise", lfs_ladvise, 0,
687          "Provide servers with advice about access patterns for a file.\n"
688          "usage: ladvise [--advice|-a ADVICE] [--start|-s START[kMGT]]\n"
689          "               [--background|-b] [--unset|-u]\n\n"
690          "               {--end|-e END[kMGT]|--length|-l LENGTH[kMGT]}\n"
691          "               {[--mode|-m [READ,WRITE]}\n"
692          "               <file> ...\n"},
693         {"mirror", lfs_mirror, mirror_cmdlist,
694          "lfs commands used to manage files with mirrored components:\n"
695          "lfs mirror create - create a mirrored file or directory\n"
696          "lfs mirror extend - add mirror(s) to an existing file\n"
697          "lfs mirror split  - split a mirror from an existing mirrored file\n"
698          "lfs mirror resync - resynchronize out-of-sync mirrored file(s)\n"
699          "lfs mirror read   - read a mirror content of a mirrored file\n"
700          "lfs mirror write  - write to a mirror of a mirrored file\n"
701          "lfs mirror copy   - copy a mirror to other mirror(s) of a file\n"
702          "lfs mirror verify - verify mirrored file(s)\n"},
703         {"getsom", lfs_getsom, 0, "To list the SOM info for a given file.\n"
704          "usage: getsom [-s] [-b] [-f] <path>\n"
705          "\t-s: Only show the size value of the SOM data for a given file\n"
706          "\t-b: Only show the blocks value of the SOM data for a given file\n"
707          "\t-f: Only show the flags value of the SOM data for a given file\n"},
708         {"heat_get", lfs_heat_get, 0,
709          "To get heat of files.\n"
710          "usage: heat_get <file> ...\n"},
711         {"heat_set", lfs_heat_set, 0,
712          "To set heat flags of files.\n"
713          "usage: heat_set [--clear|-c] [--off|-o] [--on|-O] <file> ...\n"
714          "\t--clear|-c: Clear file heat for given files\n"
715          "\t--off|-o:   Turn off file heat for given files\n"
716          "\t--on|-O:    Turn on file heat for given files\n"},
717         {"pcc", lfs_pcc, pcc_cmdlist,
718          "lfs commands used to interact with PCC features:\n"
719          "lfs pcc attach - attach given files to Persistent Client Cache\n"
720          "lfs pcc attach_fid - attach given files into PCC by FID(s)\n"
721          "lfs pcc state  - display the PCC state for given files\n"
722          "lfs pcc detach - detach given files from Persistent Client Cache\n"
723          "lfs pcc detach_fid - detach given files from PCC by FID(s)\n"},
724         {"help", Parser_help, 0, "help"},
725         {"exit", Parser_quit, 0, "quit"},
726         {"quit", Parser_quit, 0, "quit"},
727         {"--version", Parser_version, 0,
728          "output build version of the utility and exit"},
729         {"--list-commands", lfs_list_commands, 0,
730          "list commands supported by the utility and exit"},
731         { 0, 0, 0, NULL }
732 };
733
734 static int check_hashtype(const char *hashtype)
735 {
736         int type_num = atoi(hashtype);
737         int i;
738
739         /* numeric hash type */
740         if (hashtype && strlen(hashtype) == 1 &&
741             (type_num > 0 && type_num < LMV_HASH_TYPE_MAX))
742                 return type_num;
743         /* string hash type */
744         for (i = LMV_HASH_TYPE_ALL_CHARS; i < LMV_HASH_TYPE_MAX; i++)
745                 if (strcmp(hashtype, mdt_hash_name[i]) == 0)
746                         return i;
747
748         return 0;
749 }
750
751 static uint32_t check_foreign_type_name(const char *foreign_type_name)
752 {
753         uint32_t i;
754
755         for (i = 0; i < LU_FOREIGN_TYPE_UNKNOWN; i++) {
756                 if (!lu_foreign_types[i].lft_name)
757                         break;
758                 if (strcmp(foreign_type_name,
759                            lu_foreign_types[i].lft_name) == 0)
760                         return lu_foreign_types[i].lft_type;
761         }
762
763         return LU_FOREIGN_TYPE_UNKNOWN;
764 }
765
766 static const char *error_loc = "syserror";
767
768 enum {
769         MIGRATION_NONBLOCK      = 0x0001,
770         MIGRATION_MIRROR        = 0x0002,
771         MIGRATION_NONDIRECT     = 0x0004,
772         MIGRATION_VERBOSE       = 0x0008,
773 };
774
775 static int
776 migrate_open_files(const char *name, __u64 migration_flags,
777                    const struct llapi_stripe_param *param,
778                    struct llapi_layout *layout, int *fd_src, int *fd_tgt)
779 {
780         int                      fd = -1;
781         int                      fdv = -1;
782         int                      rflags;
783         int                      mdt_index;
784         int                      random_value;
785         char                     parent[PATH_MAX];
786         char                     volatile_file[PATH_MAX];
787         char                    *ptr;
788         int                      rc;
789         struct stat              st;
790         struct stat              stv;
791
792         if (!param && !layout) {
793                 error_loc = "layout information";
794                 return -EINVAL;
795         }
796
797         /* search for file directory pathname */
798         if (strlen(name) > sizeof(parent) - 1) {
799                 error_loc = "source file name";
800                 return -ERANGE;
801         }
802
803         strncpy(parent, name, sizeof(parent));
804         ptr = strrchr(parent, '/');
805         if (!ptr) {
806                 if (!getcwd(parent, sizeof(parent))) {
807                         error_loc = "getcwd";
808                         return -errno;
809                 }
810         } else {
811                 if (ptr == parent) /* leading '/' */
812                         ptr = parent + 1;
813                 *ptr = '\0';
814         }
815
816         /* open file, direct io */
817         /* even if the file is only read, WR mode is nedeed to allow
818          * layout swap on fd
819          */
820         rflags = O_RDWR;
821         if (!(migration_flags & MIGRATION_NONDIRECT))
822                 rflags |= O_DIRECT;
823         fd = open(name, rflags);
824         if (fd < 0) {
825                 rc = -errno;
826                 error_loc = "cannot open source file";
827                 return rc;
828         }
829
830         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
831         if (rc < 0) {
832                 error_loc = "cannot get MDT index";
833                 goto out;
834         }
835
836         do {
837                 int open_flags = O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW;
838                 mode_t open_mode = S_IRUSR | S_IWUSR;
839
840                 random_value = random();
841                 rc = snprintf(volatile_file, sizeof(volatile_file),
842                               "%s/%s:%.4X:%.4X", parent, LUSTRE_VOLATILE_HDR,
843                               mdt_index, random_value);
844                 if (rc >= sizeof(volatile_file)) {
845                         rc = -ENAMETOOLONG;
846                         break;
847                 }
848
849                 /* create, open a volatile file, use caching (ie no directio) */
850                 if (layout) {
851                         /* Returns -1 and sets errno on error: */
852                         fdv = llapi_layout_file_open(volatile_file, open_flags,
853                                                      open_mode, layout);
854                         if (fdv < 0)
855                                 fdv = -errno;
856                 } else {
857                         /* Does the right thing on error: */
858                         fdv = llapi_file_open_param(volatile_file, open_flags,
859                                                     open_mode, param);
860                 }
861         } while (fdv < 0 && (rc = fdv) == -EEXIST);
862
863         if (rc < 0) {
864                 error_loc = "cannot create volatile file";
865                 goto out;
866         }
867
868         /*
869          * In case the MDT does not support creation of volatile files
870          * we should try to unlink it.
871          */
872         (void)unlink(volatile_file);
873
874         /*
875          * Not-owner (root?) special case.
876          * Need to set owner/group of volatile file like original.
877          * This will allow to pass related check during layout_swap.
878          */
879         rc = fstat(fd, &st);
880         if (rc != 0) {
881                 rc = -errno;
882                 error_loc = "cannot stat source file";
883                 goto out;
884         }
885
886         rc = fstat(fdv, &stv);
887         if (rc != 0) {
888                 rc = -errno;
889                 error_loc = "cannot stat volatile";
890                 goto out;
891         }
892
893         if (st.st_uid != stv.st_uid || st.st_gid != stv.st_gid) {
894                 rc = fchown(fdv, st.st_uid, st.st_gid);
895                 if (rc != 0) {
896                         rc = -errno;
897                         error_loc = "cannot change ownwership of volatile";
898                         goto out;
899                 }
900         }
901
902 out:
903         if (rc < 0) {
904                 if (fd > 0)
905                         close(fd);
906                 if (fdv > 0)
907                         close(fdv);
908         } else {
909                 *fd_src = fd;
910                 *fd_tgt = fdv;
911                 error_loc = NULL;
912         }
913         return rc;
914 }
915
916 static int migrate_copy_data(int fd_src, int fd_dst, int (*check_file)(int))
917 {
918         struct llapi_layout *layout;
919         size_t buf_size = 4 * 1024 * 1024;
920         void *buf = NULL;
921         off_t pos = 0;
922         off_t data_end = 0;
923         size_t page_size = sysconf(_SC_PAGESIZE);
924         bool sparse;
925         int rc;
926
927         layout = llapi_layout_get_by_fd(fd_src, 0);
928         if (layout) {
929                 uint64_t stripe_size;
930
931                 rc = llapi_layout_stripe_size_get(layout, &stripe_size);
932                 if (rc == 0)
933                         buf_size = stripe_size;
934
935                 llapi_layout_free(layout);
936         }
937
938         /* Use a page-aligned buffer for direct I/O */
939         rc = posix_memalign(&buf, page_size, buf_size);
940         if (rc != 0)
941                 return -rc;
942
943         sparse = llapi_file_is_sparse(fd_src);
944         if (sparse) {
945                 rc = ftruncate(fd_dst, pos);
946                 if (rc < 0) {
947                         rc = -errno;
948                         return rc;
949                 }
950         }
951
952         while (1) {
953                 off_t data_off;
954                 size_t to_read, to_write;
955                 ssize_t rsize;
956
957                 if (sparse && pos >= data_end) {
958                         size_t data_size;
959
960                         data_off = llapi_data_seek(fd_src, pos, &data_size);
961                         if (data_off < 0) {
962                                 /* Non-fatal, switch to full copy */
963                                 sparse = false;
964                                 continue;
965                         }
966                         /* hole at the end of file, truncate up to it */
967                         if (!data_size) {
968                                 rc = ftruncate(fd_dst, data_off);
969                                 if (rc < 0)
970                                         goto out;
971                         }
972                         pos = data_off & ~(page_size - 1);
973                         data_end = data_off + data_size;
974                         to_read = ((data_end - pos - 1) | (page_size - 1)) + 1;
975                         to_read = MIN(to_read, buf_size);
976                 } else {
977                         to_read = buf_size;
978                 }
979
980                 if (check_file) {
981                         rc = check_file(fd_src);
982                         if (rc < 0)
983                                 goto out;
984                 }
985
986                 rsize = pread(fd_src, buf, to_read, pos);
987                 if (rsize < 0) {
988                         rc = -errno;
989                         goto out;
990                 }
991                 /* EOF */
992                 if (rsize == 0)
993                         break;
994
995                 to_write = rsize;
996                 while (to_write > 0) {
997                         ssize_t written;
998
999                         written = pwrite(fd_dst, buf, to_write, pos);
1000                         if (written < 0) {
1001                                 rc = -errno;
1002                                 goto out;
1003                         }
1004                         pos += written;
1005                         to_write -= written;
1006                 }
1007                 if (rc || rsize < to_read)
1008                         break;
1009         }
1010
1011         rc = fsync(fd_dst);
1012         if (rc < 0)
1013                 rc = -errno;
1014 out:
1015         /* Try to avoid page cache pollution after migration. */
1016         (void)posix_fadvise(fd_src, 0, 0, POSIX_FADV_DONTNEED);
1017         (void)posix_fadvise(fd_dst, 0, 0, POSIX_FADV_DONTNEED);
1018
1019         free(buf);
1020         return rc;
1021 }
1022
1023 static int migrate_copy_timestamps(int fd, int fdv)
1024 {
1025         struct stat st;
1026
1027         if (fstat(fd, &st) == 0) {
1028                 struct timeval tv[2] = {
1029                         {.tv_sec = st.st_atime},
1030                         {.tv_sec = st.st_mtime}
1031                 };
1032
1033                 return futimes(fdv, tv);
1034         }
1035
1036         return -errno;
1037 }
1038
1039 static int migrate_block(int fd, int fdv)
1040 {
1041         __u64   dv1;
1042         int     gid;
1043         int     rc;
1044         int     rc2;
1045
1046         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
1047         if (rc < 0) {
1048                 error_loc = "cannot get dataversion";
1049                 return rc;
1050         }
1051
1052         do
1053                 gid = random();
1054         while (gid == 0);
1055
1056         /*
1057          * The grouplock blocks all concurrent accesses to the file.
1058          * It has to be taken after llapi_get_data_version as it would
1059          * block it too.
1060          */
1061         rc = llapi_group_lock(fd, gid);
1062         if (rc < 0) {
1063                 error_loc = "cannot get group lock";
1064                 return rc;
1065         }
1066
1067         rc = migrate_copy_data(fd, fdv, NULL);
1068         if (rc < 0) {
1069                 error_loc = "data copy failed";
1070                 goto out_unlock;
1071         }
1072
1073         /* Make sure we keep original atime/mtime values */
1074         rc = migrate_copy_timestamps(fd, fdv);
1075         if (rc < 0) {
1076                 error_loc = "timestamp copy failed";
1077                 goto out_unlock;
1078         }
1079
1080         /*
1081          * swap layouts
1082          * for a migration we need to check data version on file did
1083          * not change.
1084          *
1085          * Pass in gid=0 since we already own grouplock.
1086          */
1087         rc = llapi_fswap_layouts_grouplock(fd, fdv, dv1, 0, 0,
1088                                            SWAP_LAYOUTS_CHECK_DV1);
1089         if (rc == -EAGAIN) {
1090                 error_loc = "file changed";
1091                 goto out_unlock;
1092         } else if (rc < 0) {
1093                 error_loc = "cannot swap layout";
1094                 goto out_unlock;
1095         }
1096
1097 out_unlock:
1098         rc2 = llapi_group_unlock(fd, gid);
1099         if (rc2 < 0 && rc == 0) {
1100                 error_loc = "unlock group lock";
1101                 rc = rc2;
1102         }
1103
1104         return rc;
1105 }
1106
1107 /**
1108  * Internal helper for migrate_copy_data(). Check lease and report error if
1109  * need be.
1110  *
1111  * \param[in]  fd           File descriptor on which to check the lease.
1112  *
1113  * \retval 0       Migration can keep on going.
1114  * \retval -errno  Error occurred, abort migration.
1115  */
1116 static int check_lease(int fd)
1117 {
1118         int rc;
1119
1120         rc = llapi_lease_check(fd);
1121         if (rc > 0)
1122                 return 0; /* llapi_check_lease returns > 0 on success. */
1123
1124         return -EBUSY;
1125 }
1126
1127 static int migrate_nonblock(int fd, int fdv)
1128 {
1129         __u64   dv1;
1130         __u64   dv2;
1131         int     rc;
1132
1133         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
1134         if (rc < 0) {
1135                 error_loc = "cannot get data version";
1136                 return rc;
1137         }
1138
1139         rc = migrate_copy_data(fd, fdv, check_lease);
1140         if (rc < 0) {
1141                 error_loc = "data copy failed";
1142                 return rc;
1143         }
1144
1145         rc = llapi_get_data_version(fd, &dv2, LL_DV_RD_FLUSH);
1146         if (rc != 0) {
1147                 error_loc = "cannot get data version";
1148                 return rc;
1149         }
1150
1151         if (dv1 != dv2) {
1152                 rc = -EAGAIN;
1153                 error_loc = "source file changed";
1154                 return rc;
1155         }
1156
1157         /* Make sure we keep original atime/mtime values */
1158         rc = migrate_copy_timestamps(fd, fdv);
1159         if (rc < 0) {
1160                 error_loc = "timestamp copy failed";
1161                 return rc;
1162         }
1163
1164         return 0;
1165 }
1166
1167 static
1168 int lfs_layout_compid_by_pool(char *fname, const char *pool, int *comp_id)
1169 {
1170         struct pool_to_id_cbdata data = { .pool = pool };
1171         struct llapi_layout *layout = NULL;
1172         int rc;
1173
1174         layout = llapi_layout_get_by_path(fname, 0);
1175         if (!layout) {
1176                 fprintf(stderr,
1177                         "error %s: file '%s' couldn't get layout: rc=%d\n",
1178                         progname, fname, errno);
1179                 rc = -errno;
1180                 goto free_layout;
1181         }
1182         rc = llapi_layout_sanity(layout, fname, false, true);
1183         if (rc < 0) {
1184                 llapi_layout_sanity_perror(errno);
1185                 goto free_layout;
1186         }
1187         rc = llapi_layout_comp_iterate(layout, find_comp_id_by_pool, &data);
1188         if (rc < 0)
1189                 goto free_layout;
1190
1191         *comp_id = data.id;
1192         rc = 0;
1193
1194 free_layout:
1195         if (layout)
1196                 llapi_layout_free(layout);
1197         return rc;
1198 }
1199
1200 static int lfs_component_set(char *fname, int comp_id, const char *pool,
1201                              __u32 flags, __u32 neg_flags)
1202 {
1203         __u32 ids[2];
1204         __u32 flags_array[2];
1205         size_t count = 0;
1206         int rc;
1207
1208         if (!comp_id) {
1209                 if (pool == NULL) {
1210                         fprintf(stderr,
1211                                 "error %s: neither component id nor pool is specified\n",
1212                                 progname);
1213                         return -EINVAL;
1214                 }
1215                 rc = lfs_layout_compid_by_pool(fname, pool, &comp_id);
1216                 if (rc)
1217                         return rc;
1218         }
1219
1220         if (flags) {
1221                 ids[count] = comp_id;
1222                 flags_array[count] = flags;
1223                 ++count;
1224         }
1225
1226         if (neg_flags) {
1227                 if (neg_flags & LCME_FL_STALE) {
1228                         fprintf(stderr,
1229                                 "%s: cannot clear 'stale' flags from component. Please use lfs-mirror-resync(1) instead\n",
1230                                 progname);
1231                         return -EINVAL;
1232                 }
1233
1234                 ids[count] = comp_id;
1235                 flags_array[count] = neg_flags | LCME_FL_NEG;
1236                 ++count;
1237         }
1238
1239         rc = llapi_layout_file_comp_set(fname, ids, flags_array, count);
1240         if (rc) {
1241                 if (errno == EUCLEAN) {
1242                         rc = -errno;
1243                         fprintf(stderr,
1244                                 "%s: cannot set 'stale' flag on component '%#x' of the last non-stale mirror of '%s'\n",
1245                                 progname, comp_id, fname);
1246                 } else {
1247                         fprintf(stderr,
1248                                 "%s: cannot change the flags of component '%#x' of file '%s': %x / ^(%x)\n",
1249                                 progname, comp_id, fname, flags, neg_flags);
1250                 }
1251         }
1252
1253         return rc;
1254 }
1255
1256 static int lfs_component_del(char *fname, __u32 comp_id,
1257                              __u32 flags, __u32 neg_flags)
1258 {
1259         int     rc = 0;
1260
1261         if (flags && neg_flags)
1262                 return -EINVAL;
1263
1264         if (!flags && neg_flags)
1265                 flags = neg_flags | LCME_FL_NEG;
1266
1267         if ((flags && comp_id) || (!flags && !comp_id))
1268                 return -EINVAL;
1269
1270         if (flags) {
1271                 if (flags & ~LCME_KNOWN_FLAGS) {
1272                         fprintf(stderr,
1273                                 "%s setstripe: unknown flags %#x\n",
1274                                 progname, flags);
1275                         return -EINVAL;
1276                 }
1277         } else if (comp_id > LCME_ID_MAX) {
1278                 fprintf(stderr, "%s setstripe: invalid component id %u\n",
1279                         progname, comp_id);
1280                 return -EINVAL;
1281         }
1282
1283         rc = llapi_layout_file_comp_del(fname, comp_id, flags);
1284         if (rc)
1285                 fprintf(stderr,
1286                         "%s setstripe: cannot delete component %#x from '%s': %s\n",
1287                         progname, comp_id, fname, strerror(errno));
1288         return rc;
1289 }
1290
1291 static int lfs_component_add(char *fname, struct llapi_layout *layout)
1292 {
1293         int     rc;
1294
1295         if (!layout)
1296                 return -EINVAL;
1297
1298         rc = llapi_layout_file_comp_add(fname, layout);
1299         if (rc)
1300                 fprintf(stderr, "Add layout component(s) to %s failed. %s\n",
1301                         fname, strerror(errno));
1302         return rc;
1303 }
1304
1305 static int lfs_component_create(char *fname, int open_flags, mode_t open_mode,
1306                                 struct llapi_layout *layout)
1307 {
1308         struct stat     st;
1309         int     fd;
1310
1311         if (!layout)
1312                 return -EINVAL;
1313
1314         fd = lstat(fname, &st);
1315         if (fd == 0 && S_ISDIR(st.st_mode))
1316                 open_flags = O_DIRECTORY | O_RDONLY;
1317
1318         fd = llapi_layout_file_open(fname, open_flags, open_mode, layout);
1319         if (fd < 0)
1320                 fprintf(stderr, "%s: cannot %s '%s': %s\n", progname,
1321                         S_ISDIR(st.st_mode) ?
1322                                 "set default composite layout for" :
1323                                 "create composite file",
1324                         fname, strerror(errno));
1325         return fd;
1326 }
1327
1328 static int lfs_migrate(char *name, __u64 migration_flags,
1329                        struct llapi_stripe_param *param,
1330                        struct llapi_layout *layout)
1331 {
1332         struct llapi_layout *existing;
1333         uint64_t dom_new, dom_cur;
1334         int fd = -1;
1335         int fdv = -1;
1336         int rc;
1337
1338         rc = migrate_open_files(name, migration_flags, param, layout,
1339                                 &fd, &fdv);
1340         if (rc < 0)
1341                 goto out;
1342
1343         rc = llapi_layout_dom_size(layout, &dom_new);
1344         if (rc) {
1345                 error_loc = "cannot get new layout DoM size";
1346                 goto out;
1347         }
1348         /* special case for migration to DOM layout*/
1349         existing = llapi_layout_get_by_fd(fd, 0);
1350         if (!existing) {
1351                 error_loc = "cannot get existing layout";
1352                 goto out;
1353         }
1354
1355         rc = llapi_layout_dom_size(existing, &dom_cur);
1356         if (rc) {
1357                 error_loc = "cannot get current layout DoM size";
1358                 goto out;
1359         }
1360
1361         /*
1362          * if file has DoM layout already then migration is possible to
1363          * the new layout with the same DoM component via swap layout,
1364          * if new layout used bigger DOM size, then mirroring is used
1365          */
1366         if (dom_new > dom_cur) {
1367                 rc = lfs_migrate_to_dom(fd, fdv, name, migration_flags, param,
1368                                         layout);
1369                 if (rc)
1370                         error_loc = "cannot migrate to DOM layout";
1371                 goto out_closed;
1372         }
1373
1374         if (!(migration_flags & MIGRATION_NONBLOCK)) {
1375                 /*
1376                  * Blocking mode (forced if servers do not support file lease).
1377                  * It is also the default mode, since we cannot distinguish
1378                  * between a broken lease and a server that does not support
1379                  * atomic swap/close (LU-6785)
1380                  */
1381                 rc = migrate_block(fd, fdv);
1382                 goto out;
1383         }
1384
1385         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1386         if (rc < 0) {
1387                 error_loc = "cannot get lease";
1388                 goto out;
1389         }
1390
1391         rc = migrate_nonblock(fd, fdv);
1392         if (rc < 0) {
1393                 llapi_lease_release(fd);
1394                 goto out;
1395         }
1396
1397         /*
1398          * Atomically put lease, swap layouts and close.
1399          * for a migration we need to check data version on file did
1400          * not change.
1401          */
1402         rc = llapi_fswap_layouts(fd, fdv, 0, 0, SWAP_LAYOUTS_CLOSE);
1403         if (rc < 0) {
1404                 error_loc = "cannot swap layout";
1405                 goto out;
1406         }
1407
1408 out:
1409         if (fd >= 0)
1410                 close(fd);
1411
1412         if (fdv >= 0)
1413                 close(fdv);
1414 out_closed:
1415         if (rc < 0)
1416                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1417                         progname, name, error_loc, strerror(-rc));
1418         else if (migration_flags & MIGRATION_VERBOSE)
1419                 printf("%s\n", name);
1420
1421         return rc;
1422 }
1423
1424 static int comp_str2flags(char *string, __u32 *flags, __u32 *neg_flags)
1425 {
1426         char *name;
1427         char *dup_string = NULL;
1428         int rc = 0;
1429
1430         *flags = 0;
1431         *neg_flags = 0;
1432
1433         if (!string || !string[0])
1434                 return -EINVAL;
1435
1436         dup_string = strdup(string);
1437         if (!dup_string) {
1438                 llapi_printf(LLAPI_MSG_ERROR,
1439                              "%s: insufficient memory\n",
1440                              progname);
1441                 return -ENOMEM;
1442         }
1443
1444         for (name = strtok(dup_string, ","); name; name = strtok(NULL, ",")) {
1445                 bool found = false;
1446                 int i;
1447
1448                 for (i = 0; i < ARRAY_SIZE(comp_flags_table); i++) {
1449                         __u32 comp_flag = comp_flags_table[i].cfn_flag;
1450                         const char *comp_name = comp_flags_table[i].cfn_name;
1451
1452                         if (strcmp(name, comp_name) == 0) {
1453                                 *flags |= comp_flag;
1454                                 found = true;
1455                         } else if (strncmp(name, "^", 1) == 0 &&
1456                                    strcmp(name + 1, comp_name) == 0) {
1457                                 *neg_flags |= comp_flag;
1458                                 found = true;
1459                         }
1460                 }
1461                 if (!found) {
1462                         llapi_printf(LLAPI_MSG_ERROR,
1463                                      "%s: component flag '%s' not supported\n",
1464                                      progname, name);
1465                         rc = -EINVAL;
1466                         goto out_free;
1467                 }
1468         }
1469
1470         if (!*flags && !*neg_flags)
1471                 rc = -EINVAL;
1472
1473         /* don't allow to set and exclude the same flag */
1474         if (*flags & *neg_flags)
1475                 rc = -EINVAL;
1476
1477 out_free:
1478         free(dup_string);
1479         return rc;
1480 }
1481
1482 static int mdthash_input(char *string, __u32 *inflags,
1483                          __u32 *exflags, __u32 *type)
1484 {
1485         char *name;
1486         struct mhf_list {
1487                 char *name;
1488                 __u32 flag;
1489         } mhflist[] = {
1490                 {"migrating", LMV_HASH_FLAG_MIGRATION},
1491                 {"badtype", LMV_HASH_FLAG_BAD_TYPE},
1492                 {"lostlmv", LMV_HASH_FLAG_LOST_LMV},
1493         };
1494
1495         if (string == NULL)
1496                 return -EINVAL;
1497
1498         *inflags = 0;
1499         *exflags = 0;
1500         *type = 0;
1501         for (name = strtok(string, ","); name; name = strtok(NULL, ",")) {
1502                 bool found = false;
1503                 int i;
1504
1505                 for (i = 0; i < ARRAY_SIZE(mhflist); i++) {
1506                         if (strcmp(name, mhflist[i].name) == 0 ||
1507                             name[0] == mhflist[i].name[0]) {
1508                                 *inflags |= mhflist[i].flag;
1509                                 found = true;
1510                         } else if (name[0] == '^' &&
1511                                    (strcmp(name + 1, mhflist[i].name) == 0 ||
1512                                     name[1] == mhflist[i].name[0])) {
1513                                 *exflags |= mhflist[i].flag;
1514                                 found = true;
1515                         }
1516                 }
1517                 if (!found) {
1518                         i = check_hashtype(name);
1519                         if (i > 0) {
1520                                 *type |= 1 << i;
1521                                 continue;
1522                         }
1523                         llapi_printf(LLAPI_MSG_ERROR,
1524                                      "%s: invalid mdt_hash value '%s'\n",
1525                                      progname, name);
1526                         return -EINVAL;
1527                 }
1528         }
1529
1530         /* don't allow to include and exclude the same flag */
1531         if (*inflags & *exflags) {
1532                 llapi_printf(LLAPI_MSG_ERROR,
1533                              "%s: include and exclude same flag '%s'\n",
1534                              progname, string);
1535                 return -EINVAL;
1536         }
1537
1538         return 0;
1539 }
1540
1541 static int mirror_str2state(char *string, __u16 *state, __u16 *neg_state)
1542 {
1543         if (!string)
1544                 return -EINVAL;
1545
1546         *state = 0;
1547         *neg_state = 0;
1548
1549         if (strncmp(string, "^", 1) == 0) {
1550                 *neg_state = llapi_layout_string_flags(string + 1);
1551                 if (*neg_state != 0)
1552                         return 0;
1553         } else {
1554                 *state = llapi_layout_string_flags(string);
1555                 if (*state != 0)
1556                         return 0;
1557         }
1558
1559         llapi_printf(LLAPI_MSG_ERROR,
1560                      "%s: mirrored file state '%s' not supported\n",
1561                      progname, string);
1562         return -EINVAL;
1563 }
1564
1565 /**
1566  * struct mirror_args - Command-line arguments for mirror(s).
1567  * @m_count:  Number of mirrors to be created with this layout.
1568  * @m_flags:  Mirror level flags, only 'prefer' is supported.
1569  * @m_layout: Mirror layout.
1570  * @m_file:   A victim file. Its layout will be split and used as a mirror.
1571  * @m_next:   Point to the next node of the list.
1572  *
1573  * Command-line arguments for mirror(s) will be parsed and stored in
1574  * a linked list that consists of this structure.
1575  */
1576 struct mirror_args {
1577         __u32                   m_count;
1578         __u32                   m_flags;
1579         struct llapi_layout     *m_layout;
1580         const char              *m_file;
1581         struct mirror_args      *m_next;
1582         bool                    m_inherit;
1583 };
1584
1585 /**
1586  * enum mirror_flags - Flags for extending a mirrored file.
1587  * @MF_NO_VERIFY: Indicates not to verify the mirror(s) from victim file(s)
1588  *             in case the victim file(s) contains the same data as the
1589  *             original mirrored file.
1590  * @MF_DESTROY: Indicates to delete the mirror from the mirrored file.
1591  * @MF_COMP_ID: specified component id instead of mirror id
1592  *
1593  * Flags for extending a mirrored file.
1594  */
1595 enum mirror_flags {
1596         MF_NO_VERIFY    = 0x1,
1597         MF_DESTROY      = 0x2,
1598         MF_COMP_ID      = 0x4,
1599         MF_COMP_POOL    = 0x8,
1600 };
1601
1602 /**
1603  * mirror_create_sanity_check() - Check mirror list.
1604  * @list:  A linked list that stores the mirror arguments.
1605  *
1606  * This function does a sanity check on @list for creating
1607  * a mirrored file.
1608  *
1609  * Return: 0 on success or a negative error code on failure.
1610  */
1611 static int mirror_create_sanity_check(const char *fname,
1612                                       struct mirror_args *list,
1613                                       bool check_fname)
1614 {
1615         int rc = 0;
1616         bool has_m_file = false;
1617         bool has_m_layout = false;
1618
1619         if (!list)
1620                 return -EINVAL;
1621
1622         if (fname && check_fname) {
1623                 struct llapi_layout *layout;
1624
1625                 layout = llapi_layout_get_by_path(fname, 0);
1626                 if (!layout) {
1627                         fprintf(stderr,
1628                                 "error: %s: file '%s' couldn't get layout\n",
1629                                 progname, fname);
1630                         return -ENODATA;
1631                 }
1632
1633                 rc = llapi_layout_sanity(layout, fname, false, true);
1634
1635                 llapi_layout_free(layout);
1636
1637                 if (rc) {
1638                         llapi_layout_sanity_perror(rc);
1639                         return rc;
1640                 }
1641         }
1642
1643         while (list) {
1644                 if (list->m_file) {
1645                         has_m_file = true;
1646                         llapi_layout_free(list->m_layout);
1647
1648                         list->m_layout =
1649                                 llapi_layout_get_by_path(list->m_file, 0);
1650                         if (!list->m_layout) {
1651                                 fprintf(stderr,
1652                                         "error: %s: file '%s' has no layout\n",
1653                                         progname, list->m_file);
1654                                 return -ENODATA;
1655                         }
1656                 } else {
1657                         has_m_layout = true;
1658                         if (!list->m_layout) {
1659                                 fprintf(stderr, "error: %s: no mirror layout\n",
1660                                         progname);
1661                                 return -EINVAL;
1662                         }
1663                 }
1664
1665                 rc = llapi_layout_sanity(list->m_layout, fname, false, true);
1666                 if (rc) {
1667                         llapi_layout_sanity_perror(rc);
1668                         return rc;
1669                 }
1670
1671                 list = list->m_next;
1672         }
1673
1674         if (has_m_file && has_m_layout) {
1675                 fprintf(stderr,
1676                         "error: %s: -f <victim_file> option should not be specified with setstripe options\n",
1677                         progname);
1678                 return -EINVAL;
1679         }
1680
1681         return 0;
1682 }
1683
1684 static int mirror_set_flags(struct llapi_layout *layout, void *cbdata)
1685 {
1686         __u32 mirror_flags = *(__u32 *)cbdata;
1687         uint32_t flags;
1688         int rc;
1689
1690         rc = llapi_layout_comp_flags_get(layout, &flags);
1691         if (rc < 0)
1692                 return rc;
1693
1694         if (!flags) {
1695                 rc = llapi_layout_comp_flags_set(layout, mirror_flags);
1696                 if (rc)
1697                         return rc;
1698         }
1699
1700         return LLAPI_LAYOUT_ITER_CONT;
1701 }
1702
1703 /**
1704  * mirror_create() - Create a mirrored file.
1705  * @fname:        The file to be created.
1706  * @mirror_list:  A linked list that stores the mirror arguments.
1707  *
1708  * This function creates a mirrored file @fname with the mirror(s)
1709  * from @mirror_list.
1710  *
1711  * Return: 0 on success or a negative error code on failure.
1712  */
1713 static int mirror_create(char *fname, struct mirror_args *mirror_list)
1714 {
1715         struct llapi_layout *layout = NULL;
1716         struct mirror_args *cur_mirror = NULL;
1717         uint16_t mirror_count = 0;
1718         int i = 0;
1719         int rc = 0;
1720
1721         rc = mirror_create_sanity_check(fname, mirror_list, false);
1722         if (rc)
1723                 return rc;
1724
1725         cur_mirror = mirror_list;
1726         while (cur_mirror) {
1727                 rc = llapi_layout_comp_iterate(cur_mirror->m_layout,
1728                                                mirror_set_flags,
1729                                                &cur_mirror->m_flags);
1730                 if (rc) {
1731                         rc = -errno;
1732                         fprintf(stderr, "%s: failed to set mirror flags\n",
1733                                 progname);
1734                         goto error;
1735                 }
1736
1737                 for (i = 0; i < cur_mirror->m_count; i++) {
1738                         rc = llapi_layout_merge(&layout, cur_mirror->m_layout);
1739                         if (rc) {
1740                                 rc = -errno;
1741                                 fprintf(stderr,
1742                                         "error: %s: merge layout failed: %s\n",
1743                                         progname, strerror(errno));
1744                                 goto error;
1745                         }
1746                 }
1747                 mirror_count += cur_mirror->m_count;
1748                 cur_mirror = cur_mirror->m_next;
1749         }
1750
1751         if (!layout) {
1752                 fprintf(stderr, "error: %s: layout is NULL\n", progname);
1753                 return -EINVAL;
1754         }
1755
1756         rc = llapi_layout_mirror_count_set(layout, mirror_count);
1757         if (rc) {
1758                 rc = -errno;
1759                 fprintf(stderr, "error: %s: set mirror count failed: %s\n",
1760                         progname, strerror(errno));
1761                 goto error;
1762         }
1763
1764         rc = lfs_component_create(fname, O_CREAT | O_WRONLY, 0666,
1765                                   layout);
1766         if (rc >= 0) {
1767                 close(rc);
1768                 rc = 0;
1769         }
1770
1771 error:
1772         llapi_layout_free(layout);
1773         return rc;
1774 }
1775
1776 /**
1777  * Compare files and check lease on @fd.
1778  *
1779  * \retval bytes number of bytes are the same
1780  */
1781 static ssize_t mirror_file_compare(int fd, int fdv)
1782 {
1783         const size_t buflen = 4 * 1024 * 1024; /* 4M */
1784         void *buf;
1785         ssize_t bytes_done = 0;
1786         ssize_t bytes_read = 0;
1787
1788         buf = malloc(buflen * 2);
1789         if (!buf)
1790                 return -ENOMEM;
1791
1792         while (1) {
1793                 if (!llapi_lease_check(fd)) {
1794                         bytes_done = -EBUSY;
1795                         break;
1796                 }
1797
1798                 bytes_read = read(fd, buf, buflen);
1799                 if (bytes_read <= 0)
1800                         break;
1801
1802                 if (bytes_read != read(fdv, buf + buflen, buflen))
1803                         break;
1804
1805                 /*
1806                  * XXX: should compute the checksum on each buffer and then
1807                  * compare checksum to avoid cache collision
1808                  */
1809                 if (memcmp(buf, buf + buflen, bytes_read))
1810                         break;
1811
1812                 bytes_done += bytes_read;
1813         }
1814
1815         free(buf);
1816
1817         return bytes_done;
1818 }
1819
1820 static int mirror_extend_file(const char *fname, const char *victim_file,
1821                               enum mirror_flags mirror_flags)
1822 {
1823         int fd = -1;
1824         int fdv = -1;
1825         struct stat stbuf;
1826         struct stat stbuf_v;
1827         struct ll_ioc_lease *data = NULL;
1828         int rc;
1829
1830         fd = open(fname, O_RDWR);
1831         if (fd < 0) {
1832                 error_loc = "open source file";
1833                 rc = -errno;
1834                 goto out;
1835         }
1836
1837         fdv = open(victim_file, O_RDWR);
1838         if (fdv < 0) {
1839                 error_loc = "open target file";
1840                 rc = -errno;
1841                 goto out;
1842         }
1843
1844         if (fstat(fd, &stbuf) || fstat(fdv, &stbuf_v)) {
1845                 error_loc = "stat source or target file";
1846                 rc = -errno;
1847                 goto out;
1848         }
1849
1850         if (stbuf.st_dev != stbuf_v.st_dev) {
1851                 error_loc = "stat source and target file";
1852                 rc = -EXDEV;
1853                 goto out;
1854         }
1855
1856         /* mirrors should be of the same size */
1857         if (stbuf.st_size != stbuf_v.st_size) {
1858                 error_loc = "file sizes don't match";
1859                 rc = -EINVAL;
1860                 goto out;
1861         }
1862
1863         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1864         if (rc < 0) {
1865                 error_loc = "cannot get lease";
1866                 goto out;
1867         }
1868
1869         if (!(mirror_flags & MF_NO_VERIFY)) {
1870                 ssize_t ret;
1871                 /* mirrors should have the same contents */
1872                 ret = mirror_file_compare(fd, fdv);
1873                 if (ret != stbuf.st_size) {
1874                         error_loc = "file busy or contents don't match";
1875                         rc = ret < 0 ? ret : -EINVAL;
1876                         goto out;
1877                 }
1878         }
1879
1880         /* Get rid of caching pages from clients */
1881         rc = llapi_file_flush(fd);
1882         if (rc < 0) {
1883                 error_loc = "cannot get data version";
1884                 goto out;
1885         }
1886
1887         rc = llapi_file_flush(fdv);
1888         if (rc < 0) {
1889                 error_loc = "cannot get data version";
1890                 goto out;
1891         }
1892
1893         /* Make sure we keep original atime/mtime values */
1894         rc = migrate_copy_timestamps(fd, fdv);
1895         if (rc < 0) {
1896                 error_loc = "cannot copy timestamp";
1897                 goto out;
1898         }
1899
1900         /* Atomically put lease, merge layouts and close. */
1901         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1902         if (!data) {
1903                 error_loc = "memory allocation";
1904                 goto out;
1905         }
1906         data->lil_mode = LL_LEASE_UNLCK;
1907         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1908         data->lil_count = 1;
1909         data->lil_ids[0] = fdv;
1910         rc = llapi_lease_set(fd, data);
1911         if (rc < 0) {
1912                 error_loc = "cannot merge layout";
1913                 goto out;
1914         } else if (rc == 0) {
1915                 rc = -EBUSY;
1916                 error_loc = "lost lease lock";
1917                 goto out;
1918         }
1919         rc = 0;
1920
1921 out:
1922         if (data)
1923                 free(data);
1924         if (fd >= 0)
1925                 close(fd);
1926         if (fdv >= 0)
1927                 close(fdv);
1928         if (!rc)
1929                 (void) unlink(victim_file);
1930         if (rc < 0)
1931                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1932                         progname, fname, error_loc, strerror(-rc));
1933         return rc;
1934 }
1935
1936 static int mirror_extend_layout(char *name, struct llapi_layout *m_layout,
1937                                 bool inherit, uint32_t flags)
1938 {
1939         struct llapi_layout *f_layout = NULL;
1940         struct ll_ioc_lease *data = NULL;
1941         int fd = -1;
1942         int fdv = -1;
1943         int rc = 0;
1944
1945         if (inherit) {
1946                 f_layout = llapi_layout_get_by_path(name, 0);
1947                 if (!f_layout) {
1948                         fprintf(stderr, "%s: cannot get layout\n", progname);
1949                         goto out;
1950                 }
1951                 rc = llapi_layout_get_last_init_comp(f_layout);
1952                 if (rc) {
1953                         fprintf(stderr, "%s: cannot get the last init comp\n",
1954                                 progname);
1955                         goto out;
1956                 }
1957                 rc = llapi_layout_mirror_inherit(f_layout, m_layout);
1958                 if (rc) {
1959                         fprintf(stderr,
1960                                 "%s: cannot inherit from the last init comp\n",
1961                                 progname);
1962                         goto out;
1963                 }
1964         }
1965         llapi_layout_comp_flags_set(m_layout, flags);
1966         rc = migrate_open_files(name, MIGRATION_NONDIRECT, NULL, m_layout, &fd,
1967                                 &fdv);
1968         if (rc < 0)
1969                 goto out;
1970
1971         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1972         if (rc < 0) {
1973                 error_loc = "cannot get lease";
1974                 goto out;
1975         }
1976
1977         rc = migrate_nonblock(fd, fdv);
1978         if (rc < 0) {
1979                 llapi_lease_release(fd);
1980                 goto out;
1981         }
1982
1983         /* Atomically put lease, merge layouts and close. */
1984         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1985         if (!data) {
1986                 error_loc = "memory allocation";
1987                 goto out;
1988         }
1989         data->lil_mode = LL_LEASE_UNLCK;
1990         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1991         data->lil_count = 1;
1992         data->lil_ids[0] = fdv;
1993         rc = llapi_lease_set(fd, data);
1994         if (rc < 0) {
1995                 error_loc = "cannot merge layout";
1996                 goto out;
1997         } else if (rc == 0) {
1998                 rc = -EBUSY;
1999                 error_loc = "lost lease lock";
2000                 goto out;
2001         }
2002         rc = 0;
2003
2004 out:
2005         if (data)
2006                 free(data);
2007         if (fd >= 0)
2008                 close(fd);
2009         if (fdv >= 0)
2010                 close(fdv);
2011         if (rc < 0)
2012                 fprintf(stderr, "error: %s: %s: %s: %s\n",
2013                         progname, name, error_loc, strerror(-rc));
2014         return rc;
2015 }
2016
2017 static int mirror_extend(char *fname, struct mirror_args *mirror_list,
2018                          enum mirror_flags mirror_flags)
2019 {
2020         int rc;
2021
2022         rc = mirror_create_sanity_check(fname, mirror_list, true);
2023         if (rc)
2024                 return rc;
2025
2026         while (mirror_list) {
2027                 if (mirror_list->m_file) {
2028                         rc = mirror_extend_file(fname, mirror_list->m_file,
2029                                                 mirror_flags);
2030                 } else {
2031                         __u32 mirror_count = mirror_list->m_count;
2032
2033                         while (mirror_count > 0) {
2034                                 rc = mirror_extend_layout(fname,
2035                                                         mirror_list->m_layout,
2036                                                         mirror_list->m_inherit,
2037                                                         mirror_list->m_flags);
2038                                 if (rc)
2039                                         break;
2040
2041                                 --mirror_count;
2042                         }
2043                 }
2044                 if (rc)
2045                         break;
2046
2047                 mirror_list = mirror_list->m_next;
2048         }
2049
2050         return rc;
2051 }
2052
2053 static int find_mirror_id(struct llapi_layout *layout, void *cbdata)
2054 {
2055         uint32_t id;
2056         int rc;
2057
2058         rc = llapi_layout_mirror_id_get(layout, &id);
2059         if (rc < 0)
2060                 return rc;
2061
2062         if ((__u16)id == *(__u16 *)cbdata)
2063                 return LLAPI_LAYOUT_ITER_STOP;
2064
2065         return LLAPI_LAYOUT_ITER_CONT;
2066 }
2067
2068 static int find_comp_id(struct llapi_layout *layout, void *cbdata)
2069 {
2070         uint32_t id;
2071         int rc;
2072
2073         rc = llapi_layout_comp_id_get(layout, &id);
2074         if (rc < 0)
2075                 return rc;
2076
2077         if (id == *(__u32 *)cbdata)
2078                 return LLAPI_LAYOUT_ITER_STOP;
2079
2080         return LLAPI_LAYOUT_ITER_CONT;
2081 }
2082
2083 static int find_mirror_id_by_pool(struct llapi_layout *layout, void *cbdata)
2084 {
2085         char buf[LOV_MAXPOOLNAME + 1];
2086         struct pool_to_id_cbdata *d = (void *)cbdata;
2087         uint32_t id;
2088         int rc;
2089
2090         rc = llapi_layout_pool_name_get(layout, buf, sizeof(buf));
2091         if (rc < 0)
2092                 return rc;
2093         if (strcmp(d->pool, buf))
2094                 return LLAPI_LAYOUT_ITER_CONT;
2095
2096         rc = llapi_layout_mirror_id_get(layout, &id);
2097         if (rc < 0)
2098                 return rc;
2099         d->id = id;
2100
2101         return LLAPI_LAYOUT_ITER_STOP;
2102 }
2103
2104 static int find_comp_id_by_pool(struct llapi_layout *layout, void *cbdata)
2105 {
2106         char buf[LOV_MAXPOOLNAME + 1];
2107         struct pool_to_id_cbdata *d = (void *)cbdata;
2108         uint32_t id;
2109         int rc;
2110
2111         rc = llapi_layout_pool_name_get(layout, buf, sizeof(buf));
2112         if (rc < 0)
2113                 return rc;
2114         if (strcmp(d->pool, buf))
2115                 return LLAPI_LAYOUT_ITER_CONT;
2116
2117         rc = llapi_layout_comp_id_get(layout, &id);
2118         if (rc < 0)
2119                 return rc;
2120         d->id = id;
2121
2122         return LLAPI_LAYOUT_ITER_STOP;
2123 }
2124
2125 struct collect_ids_data {
2126         __u16   *cid_ids;
2127         int     cid_count;
2128         __u16   cid_exclude;
2129 };
2130
2131 static int collect_mirror_id(struct llapi_layout *layout, void *cbdata)
2132 {
2133         struct collect_ids_data *cid = cbdata;
2134         uint32_t id;
2135         int rc;
2136
2137         rc = llapi_layout_mirror_id_get(layout, &id);
2138         if (rc < 0)
2139                 return rc;
2140
2141         if ((__u16)id != cid->cid_exclude) {
2142                 int i;
2143
2144                 for (i = 0; i < cid->cid_count; i++) {
2145                         /* already collected the mirror id */
2146                         if (id == cid->cid_ids[i])
2147                                 return LLAPI_LAYOUT_ITER_CONT;
2148                 }
2149                 cid->cid_ids[cid->cid_count] = id;
2150                 cid->cid_count++;
2151         }
2152
2153         return LLAPI_LAYOUT_ITER_CONT;
2154 }
2155
2156 /**
2157  * last_non_stale_mirror() - Check if a mirror is the last non-stale mirror.
2158  * @mirror_id: Mirror id to be checked.
2159  * @layout:    Mirror component list.
2160  *
2161  * This function checks if a mirror with specified @mirror_id is the last
2162  * non-stale mirror of a layout @layout.
2163  *
2164  * Return: true or false.
2165  */
2166 static inline
2167 bool last_non_stale_mirror(__u16 mirror_id, struct llapi_layout *layout)
2168 {
2169         __u16 mirror_ids[128] = { 0 };
2170         struct collect_ids_data cid = { .cid_ids = mirror_ids,
2171                                         .cid_count = 0,
2172                                         .cid_exclude = mirror_id, };
2173         int i;
2174
2175         llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
2176
2177         for (i = 0; i < cid.cid_count; i++) {
2178                 struct llapi_resync_comp comp_array[1024] = { { 0 } };
2179                 int comp_size = 0;
2180
2181                 comp_size = llapi_mirror_find_stale(layout, comp_array,
2182                                                     ARRAY_SIZE(comp_array),
2183                                                     &mirror_ids[i], 1);
2184                 if (comp_size == 0)
2185                         return false;
2186         }
2187
2188         return true;
2189 }
2190
2191 static int mirror_split(const char *fname, __u32 id, const char *pool,
2192                         enum mirror_flags mflags, const char *victim_file)
2193 {
2194         struct llapi_layout *layout;
2195         char parent[PATH_MAX];
2196         char victim[PATH_MAX];
2197         int flags = O_CREAT | O_EXCL | O_LOV_DELAY_CREATE | O_NOFOLLOW;
2198         char *ptr;
2199         struct ll_ioc_lease *data;
2200         uint16_t mirror_count;
2201         __u32 mirror_id;
2202         int mdt_index;
2203         int fd, fdv;
2204         bool purge = true; /* delete mirror by setting fdv=fd */
2205         int rc;
2206
2207         if (victim_file && (strcmp(fname, victim_file) == 0)) {
2208                 fprintf(stderr,
2209                         "error %s: the source file '%s' and -f file are the same\n",
2210                         progname, fname);
2211                 return -EINVAL;
2212         }
2213
2214         /* check fname contains mirror with mirror_id/comp_id */
2215         layout = llapi_layout_get_by_path(fname, 0);
2216         if (!layout) {
2217                 fprintf(stderr,
2218                         "error %s: file '%s' couldn't get layout\n",
2219                         progname, fname);
2220                 return -EINVAL;
2221         }
2222
2223         rc = llapi_layout_sanity(layout, fname, false, true);
2224         if (rc) {
2225                 llapi_layout_sanity_perror(rc);
2226                 goto free_layout;
2227         }
2228
2229         rc = llapi_layout_mirror_count_get(layout, &mirror_count);
2230         if (rc) {
2231                 fprintf(stderr,
2232                         "error %s: file '%s' couldn't get mirror count\n",
2233                         progname, fname);
2234                 goto free_layout;
2235         }
2236         if (mirror_count < 2) {
2237                 fprintf(stderr,
2238                         "error %s: file '%s' has %d component, cannot split\n",
2239                         progname, fname, mirror_count);
2240                 goto free_layout;
2241         }
2242
2243         if (mflags & MF_COMP_POOL) {
2244                 struct pool_to_id_cbdata data = { .pool = pool };
2245
2246                 rc = llapi_layout_comp_iterate(layout, find_mirror_id_by_pool,
2247                                                &data);
2248                 mirror_id = data.id;
2249         } else if (mflags & MF_COMP_ID) {
2250                 rc = llapi_layout_comp_iterate(layout, find_comp_id, &id);
2251                 mirror_id = mirror_id_of(id);
2252         } else {
2253                 rc = llapi_layout_comp_iterate(layout, find_mirror_id, &id);
2254                 mirror_id = id;
2255         }
2256         if (rc < 0) {
2257                 fprintf(stderr, "error %s: failed to iterate layout of '%s'\n",
2258                         progname, fname);
2259                 goto free_layout;
2260         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
2261                 if (mflags & MF_COMP_POOL) {
2262                         fprintf(stderr,
2263                                 "error %s: file '%s' does not contain mirror with pool '%s'\n",
2264                                 progname, fname, pool);
2265                         goto free_layout;
2266                 } else if (mflags & MF_COMP_ID) {
2267                         fprintf(stderr,
2268                                 "error %s: file '%s' does not contain mirror with comp-id %u\n",
2269                                 progname, fname, id);
2270                         goto free_layout;
2271                 } else {
2272                         fprintf(stderr,
2273                                 "error %s: file '%s' does not contain mirror with id %u\n",
2274                                 progname, fname, id);
2275                         goto free_layout;
2276                 }
2277         }
2278
2279         fd = open(fname, O_RDWR);
2280         if (fd < 0) {
2281                 fprintf(stderr,
2282                         "error %s: open file '%s' failed: %s\n",
2283                         progname, fname, strerror(errno));
2284                 goto free_layout;
2285         }
2286
2287         /* get victim file directory pathname */
2288         if (strlen(fname) > sizeof(parent) - 1) {
2289                 fprintf(stderr, "error %s: file name of '%s' too long\n",
2290                         progname, fname);
2291                 rc = -ERANGE;
2292                 goto close_fd;
2293         }
2294         strncpy(parent, fname, sizeof(parent));
2295         ptr = strrchr(parent, '/');
2296         if (!ptr) {
2297                 if (!getcwd(parent, sizeof(parent))) {
2298                         fprintf(stderr, "error %s: getcwd failed: %s\n",
2299                                 progname, strerror(errno));
2300                         rc = -errno;
2301                         goto close_fd;
2302                 }
2303         } else {
2304                 if (ptr == parent)
2305                         ptr = parent + 1;
2306                 *ptr = '\0';
2307         }
2308
2309         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
2310         if (rc < 0) {
2311                 fprintf(stderr, "%s: cannot get MDT index of '%s'\n",
2312                         progname, fname);
2313                 goto close_fd;
2314         }
2315
2316 again:
2317         if (!victim_file) {
2318                 /* use a temp file to store the splitted layout */
2319                 if (mflags & MF_DESTROY) {
2320                         if (last_non_stale_mirror(mirror_id, layout)) {
2321                                 rc = -EUCLEAN;
2322                                 fprintf(stderr,
2323                                         "%s: cannot destroy the last non-stale mirror of file '%s'\n",
2324                                         progname, fname);
2325                                 goto close_fd;
2326                         }
2327
2328                         if (purge) {
2329                                 /* don't use volatile file for mirror destroy */
2330                                 fdv = fd;
2331                         } else {
2332                                 /**
2333                                  * try the old way to delete mirror using
2334                                  * volatile file.
2335                                  */
2336                                 fdv = llapi_create_volatile_idx(parent,
2337                                                 mdt_index, O_LOV_DELAY_CREATE);
2338                         }
2339                 } else {
2340                         snprintf(victim, sizeof(victim), "%s.mirror~%u",
2341                                  fname, mirror_id);
2342                         fdv = open(victim, flags, S_IRUSR | S_IWUSR);
2343                 }
2344         } else {
2345                 /* user specified victim file */
2346                 fdv = open(victim_file, flags, S_IRUSR | S_IWUSR);
2347         }
2348
2349         if (fdv < 0) {
2350                 fprintf(stderr,
2351                         "error %s: create victim file failed: %s\n",
2352                         progname, strerror(errno));
2353                 goto close_fd;
2354         }
2355
2356         /* get lease lock of fname */
2357         rc = llapi_lease_acquire(fd, LL_LEASE_WRLCK);
2358         if (rc < 0) {
2359                 fprintf(stderr,
2360                         "error %s: cannot get lease of file '%s': %d\n",
2361                         progname, fname, rc);
2362                 goto close_victim;
2363         }
2364
2365         /* Atomatically put lease, split layouts and close. */
2366         data = malloc(offsetof(typeof(*data), lil_ids[2]));
2367         if (!data) {
2368                 rc = -ENOMEM;
2369                 goto close_victim;
2370         }
2371
2372         data->lil_mode = LL_LEASE_UNLCK;
2373         data->lil_flags = LL_LEASE_LAYOUT_SPLIT;
2374         data->lil_count = 2;
2375         data->lil_ids[0] = fdv;
2376         data->lil_ids[1] = mirror_id;
2377         rc = llapi_lease_set(fd, data);
2378         if (rc <= 0) {
2379                 if (rc == -EINVAL && purge) {
2380                         /* could be old MDS which prohibit fd==fdv */
2381                         purge = false;
2382                         goto again;
2383
2384                 }
2385                 if (rc == 0) /* lost lease lock */
2386                         rc = -EBUSY;
2387                 fprintf(stderr,
2388                         "error %s: cannot split '%s': %s\n",
2389                         progname, fname, strerror(-rc));
2390         } else {
2391                 rc = 0;
2392         }
2393         free(data);
2394
2395 close_victim:
2396         if (!purge)
2397                 close(fdv);
2398 close_fd:
2399         close(fd);
2400 free_layout:
2401         llapi_layout_free(layout);
2402         return rc;
2403 }
2404
2405 static inline
2406 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
2407                            __u16 *mirror_ids, int ids_nr);
2408
2409 static int lfs_migrate_to_dom(int fd, int fdv, char *name,
2410                               __u64 migration_flags,
2411                               struct llapi_stripe_param *param,
2412                               struct llapi_layout *layout)
2413 {
2414         struct ll_ioc_lease *data = NULL;
2415         int rc;
2416
2417         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
2418         if (rc < 0) {
2419                 error_loc = "cannot get lease";
2420                 goto out_close;
2421         }
2422
2423         /* Atomically put lease, merge layouts, resync and close. */
2424         data = calloc(1, offsetof(typeof(*data), lil_ids[1024]));
2425         if (!data) {
2426                 error_loc = "memory allocation";
2427                 goto out_close;
2428         }
2429         data->lil_mode = LL_LEASE_UNLCK;
2430         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
2431         data->lil_count = 1;
2432         data->lil_ids[0] = fdv;
2433         rc = llapi_lease_set(fd, data);
2434         if (rc < 0) {
2435                 error_loc = "cannot merge layout";
2436                 goto out_close;
2437         } else if (rc == 0) {
2438                 rc = -EBUSY;
2439                 error_loc = "lost lease lock";
2440                 goto out_close;
2441         }
2442         close(fd);
2443         close(fdv);
2444
2445         rc = lfs_mirror_resync_file(name, data, NULL, 0);
2446         if (rc) {
2447                 error_loc = "cannot resync file";
2448                 goto out;
2449         }
2450
2451         /* delete first mirror now */
2452         rc = mirror_split(name, 1, NULL, MF_DESTROY, NULL);
2453         if (rc < 0)
2454                 error_loc = "cannot delete old layout";
2455         goto out;
2456
2457 out_close:
2458         close(fd);
2459         close(fdv);
2460 out:
2461         if (rc < 0)
2462                 fprintf(stderr, "error: %s: %s: %s: %s\n",
2463                         progname, name, error_loc, strerror(-rc));
2464         else if (migration_flags & MIGRATION_VERBOSE)
2465                 printf("%s\n", name);
2466         if (data)
2467                 free(data);
2468         return rc;
2469 }
2470
2471 /**
2472  * Parse a string containing an target index list into an array of integers.
2473  *
2474  * The input string contains a comma delimited list of individual
2475  * indices and ranges, for example "1,2-4,7". Add the indices into the
2476  * \a tgts array and remove duplicates.
2477  *
2478  * \param[out] tgts             array to store indices in
2479  * \param[in] size              size of \a tgts array
2480  * \param[in] offset            starting index in \a tgts
2481  * \param[in] arg               string containing OST index list
2482  * \param[in/out] overstriping  index list may contain duplicates
2483  *
2484  * \retval positive    number of indices in \a tgts
2485  * \retval -EINVAL     unable to parse \a arg
2486  */
2487 static int parse_targets(__u32 *tgts, int size, int offset, char *arg,
2488                          unsigned long long *pattern)
2489 {
2490         int rc;
2491         int nr = offset;
2492         int slots = size - offset;
2493         char *ptr = NULL;
2494         bool overstriped = false;
2495         bool end_of_loop;
2496
2497         if (!arg)
2498                 return -EINVAL;
2499
2500         end_of_loop = false;
2501         while (!end_of_loop) {
2502                 int start_index = 0;
2503                 int end_index = 0;
2504                 int i;
2505                 char *endptr = NULL;
2506
2507                 rc = -EINVAL;
2508
2509                 ptr = strchrnul(arg, ',');
2510
2511                 end_of_loop = *ptr == '\0';
2512                 *ptr = '\0';
2513
2514                 errno = 0;
2515                 start_index = strtol(arg, &endptr, 0);
2516                 if (endptr == arg) /* no data at all */
2517                         break;
2518                 if (errno != 0 || start_index < -1 ||
2519                     (*endptr != '-' && *endptr != '\0'))
2520                         break;
2521
2522                 end_index = start_index;
2523                 if (*endptr == '-') {
2524                         errno = 0;
2525                         end_index = strtol(endptr + 1, &endptr, 0);
2526                         if (errno != 0 || *endptr != '\0' || end_index < -1)
2527                                 break;
2528                         if (end_index < start_index)
2529                                 break;
2530                 }
2531
2532                 for (i = start_index; i <= end_index && slots > 0; i++) {
2533                         int j;
2534
2535                         /* remove duplicate */
2536                         for (j = 0; j < offset; j++) {
2537                                 if (tgts[j] == i && pattern &&
2538                                     *pattern == LLAPI_LAYOUT_OVERSTRIPING)
2539                                         overstriped = true;
2540                                 else if (tgts[j] == i)
2541                                         return -EINVAL;
2542                         }
2543
2544                         j = offset;
2545
2546                         if (j == offset) { /* check complete */
2547                                 tgts[nr++] = i;
2548                                 --slots;
2549                         }
2550                 }
2551
2552                 if (slots == 0 && i < end_index)
2553                         break;
2554
2555                 *ptr = ',';
2556                 arg = ++ptr;
2557                 offset = nr;
2558                 rc = 0;
2559         }
2560         if (!end_of_loop && ptr)
2561                 *ptr = ',';
2562
2563         if (!overstriped && pattern)
2564                 *pattern = LLAPI_LAYOUT_DEFAULT;
2565
2566         return rc < 0 ? rc : nr;
2567 }
2568
2569 struct lfs_setstripe_args {
2570         unsigned long long       lsa_comp_end;
2571         unsigned long long       lsa_stripe_size;
2572         unsigned long long       lsa_extension_size;
2573         long long                lsa_stripe_count;
2574         long long                lsa_stripe_off;
2575         __u32                    lsa_comp_flags;
2576         __u32                    lsa_comp_neg_flags;
2577         unsigned long long       lsa_pattern;
2578         unsigned int             lsa_mirror_count;
2579         int                      lsa_nr_tgts;
2580         bool                     lsa_first_comp;
2581         bool                     lsa_extension_comp;
2582         __u32                   *lsa_tgts;
2583         char                    *lsa_pool_name;
2584 };
2585
2586 static inline void setstripe_args_init(struct lfs_setstripe_args *lsa)
2587 {
2588         unsigned int mirror_count = lsa->lsa_mirror_count;
2589         bool first_comp = lsa->lsa_first_comp;
2590
2591         memset(lsa, 0, sizeof(*lsa));
2592
2593         lsa->lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
2594         lsa->lsa_stripe_count = LLAPI_LAYOUT_DEFAULT;
2595         lsa->lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2596         lsa->lsa_pattern = LLAPI_LAYOUT_RAID0;
2597         lsa->lsa_pool_name = NULL;
2598
2599         lsa->lsa_mirror_count = mirror_count;
2600         lsa->lsa_first_comp = first_comp;
2601 }
2602
2603 /**
2604  * setstripe_args_init_inherit() - Initialize and inherit stripe options.
2605  * @lsa: Stripe options to be initialized and inherited.
2606  *
2607  * This function initializes stripe options in @lsa and inherit
2608  * stripe_size, stripe_count and OST pool_name options.
2609  *
2610  * Return: void.
2611  */
2612 static inline void setstripe_args_init_inherit(struct lfs_setstripe_args *lsa)
2613 {
2614         unsigned long long stripe_size;
2615         long long stripe_count;
2616         char *pool_name = NULL;
2617
2618         stripe_size = lsa->lsa_stripe_size;
2619         stripe_count = lsa->lsa_stripe_count;
2620         pool_name = lsa->lsa_pool_name;
2621
2622         setstripe_args_init(lsa);
2623
2624         lsa->lsa_stripe_size = stripe_size;
2625         lsa->lsa_stripe_count = stripe_count;
2626         lsa->lsa_pool_name = pool_name;
2627 }
2628
2629 static inline bool setstripe_args_specified(struct lfs_setstripe_args *lsa)
2630 {
2631         return (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT ||
2632                 lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ||
2633                 lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
2634                 lsa->lsa_pattern != LLAPI_LAYOUT_RAID0 ||
2635                 lsa->lsa_comp_end != 0);
2636 }
2637
2638 static int lsa_args_stripe_count_check(struct lfs_setstripe_args *lsa)
2639 {
2640         if (lsa->lsa_nr_tgts) {
2641                 if (lsa->lsa_nr_tgts < 0 ||
2642                     lsa->lsa_nr_tgts >= LOV_MAX_STRIPE_COUNT) {
2643                         fprintf(stderr, "Invalid nr_tgts(%d)\n",
2644                                 lsa->lsa_nr_tgts);
2645                         errno = EINVAL;
2646                         return -1;
2647                 }
2648
2649                 if (lsa->lsa_stripe_count > 0 &&
2650                     lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
2651                     lsa->lsa_stripe_count != LLAPI_LAYOUT_WIDE &&
2652                     lsa->lsa_nr_tgts != lsa->lsa_stripe_count) {
2653                         fprintf(stderr, "stripe_count(%lld) != nr_tgts(%d)\n",
2654                                 lsa->lsa_stripe_count,
2655                                 lsa->lsa_nr_tgts);
2656                         errno = EINVAL;
2657                         return -1;
2658                 }
2659         }
2660
2661         return 0;
2662
2663 }
2664
2665 /**
2666  * comp_args_to_layout() - Create or extend a composite layout.
2667  * @composite:       Pointer to the composite layout.
2668  * @lsa:             Stripe options for the new component.
2669  *
2670  * This function creates or extends a composite layout by adding a new
2671  * component with stripe options from @lsa.
2672  *
2673  * When modified, adjust llapi_stripe_param_verify() if needed as well.
2674  *
2675  * Return: 0 on success or an error code on failure.
2676  */
2677 static int comp_args_to_layout(struct llapi_layout **composite,
2678                                struct lfs_setstripe_args *lsa,
2679                                bool set_extent)
2680 {
2681         struct llapi_layout *layout = *composite;
2682         uint64_t prev_end = 0;
2683         uint64_t size;
2684         int i = 0, rc;
2685
2686 new_comp:
2687         if (!layout) {
2688                 layout = llapi_layout_alloc();
2689                 if (!layout) {
2690                         fprintf(stderr, "Alloc llapi_layout failed. %s\n",
2691                                 strerror(errno));
2692                         errno = ENOMEM;
2693                         return -1;
2694                 }
2695                 *composite = layout;
2696                 lsa->lsa_first_comp = true;
2697         } else {
2698                 uint64_t start;
2699
2700                 /*
2701                  * Get current component extent, current component
2702                  * must be the tail component.
2703                  */
2704                 rc = llapi_layout_comp_extent_get(layout, &start, &prev_end);
2705                 if (rc) {
2706                         fprintf(stderr, "Get comp extent failed. %s\n",
2707                                 strerror(errno));
2708                         return rc;
2709                 }
2710
2711                 if (lsa->lsa_first_comp) {
2712                         prev_end = 0;
2713                         rc = llapi_layout_add_first_comp(layout);
2714                 } else {
2715                         rc = llapi_layout_comp_add(layout);
2716                 }
2717                 if (rc) {
2718                         fprintf(stderr, "Add component failed. %s\n",
2719                                 strerror(errno));
2720                         return rc;
2721                 }
2722         }
2723
2724         rc = llapi_layout_comp_flags_set(layout, lsa->lsa_comp_flags);
2725         if (rc) {
2726                 fprintf(stderr, "Set flags 0x%x failed: %s\n",
2727                         lsa->lsa_comp_flags, strerror(errno));
2728                 return rc;
2729         }
2730
2731         if (set_extent) {
2732                 uint64_t comp_end = lsa->lsa_comp_end;
2733
2734                 /*
2735                  * The extendable component is 0-length, so it can be removed
2736                  * if there is insufficient space to extend it.
2737                  */
2738                 if (lsa->lsa_extension_comp)
2739                         comp_end = prev_end;
2740
2741                 rc = llapi_layout_comp_extent_set(layout, prev_end,
2742                                                   comp_end);
2743                 if (rc) {
2744                         fprintf(stderr, "Set extent [%lu, %lu) failed. %s\n",
2745                                 prev_end, comp_end, strerror(errno));
2746                         return rc;
2747                 }
2748         }
2749         /* reset lsa_first_comp */
2750         lsa->lsa_first_comp = false;
2751
2752         /* Data-on-MDT component setting */
2753         if (lsa->lsa_pattern == LLAPI_LAYOUT_MDT) {
2754                 /*
2755                  * In case of Data-on-MDT patterns the only extra option
2756                  * applicable is stripe size option.
2757                  */
2758                 if (lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
2759                         fprintf(stderr,
2760                                 "Option 'stripe-count' can't be specified with Data-on-MDT component: %lld\n",
2761                                 lsa->lsa_stripe_count);
2762                         errno = EINVAL;
2763                         return -1;
2764                 }
2765                 if (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT) {
2766                         fprintf(stderr,
2767                                 "Option 'stripe-size' can't be specified with Data-on-MDT component: %llu\n",
2768                                 lsa->lsa_stripe_size);
2769                         errno = EINVAL;
2770                         return -1;
2771                 }
2772                 if (lsa->lsa_nr_tgts != 0) {
2773                         fprintf(stderr,
2774                                 "Option 'ost-list' can't be specified with Data-on-MDT component: '%i'\n",
2775                                 lsa->lsa_nr_tgts);
2776                         errno = EINVAL;
2777                         return -1;
2778                 }
2779                 if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT) {
2780                         fprintf(stderr,
2781                                 "Option 'stripe-offset' can't be specified with Data-on-MDT component: %lld\n",
2782                                 lsa->lsa_stripe_off);
2783                         errno = EINVAL;
2784                         return -1;
2785                 }
2786                 if (lsa->lsa_pool_name != 0) {
2787                         fprintf(stderr,
2788                                 "Option 'pool' can't be specified with Data-on-MDT component: '%s'\n",
2789                                 lsa->lsa_pool_name);
2790                         errno = EINVAL;
2791                         return -1;
2792                 }
2793
2794                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2795                 if (rc) {
2796                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2797                                 lsa->lsa_pattern,
2798                                 strerror(errno));
2799                         return rc;
2800                 }
2801                 /* Data-on-MDT component has always single stripe up to end */
2802                 lsa->lsa_stripe_size = lsa->lsa_comp_end;
2803         } else if (lsa->lsa_pattern == LLAPI_LAYOUT_OVERSTRIPING) {
2804                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2805                 if (rc) {
2806                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2807                                 lsa->lsa_pattern,
2808                                 strerror(errno));
2809                         return rc;
2810                 }
2811         }
2812
2813         size = lsa->lsa_comp_flags & LCME_FL_EXTENSION ?
2814                 lsa->lsa_extension_size : lsa->lsa_stripe_size;
2815
2816         if (lsa->lsa_comp_flags & LCME_FL_EXTENSION)
2817                 rc = llapi_layout_extension_size_set(layout, size);
2818         else
2819                 rc = llapi_layout_stripe_size_set(layout, size);
2820
2821         if (rc) {
2822                 fprintf(stderr, "Set stripe size %lu failed: %s\n",
2823                         size, strerror(errno));
2824                 return rc;
2825         }
2826
2827         rc = llapi_layout_stripe_count_set(layout, lsa->lsa_stripe_count);
2828         if (rc) {
2829                 fprintf(stderr, "Set stripe count %lld failed: %s\n",
2830                         lsa->lsa_stripe_count, strerror(errno));
2831                 return rc;
2832         }
2833
2834         if (lsa->lsa_pool_name) {
2835                 rc = llapi_layout_pool_name_set(layout, lsa->lsa_pool_name);
2836                 if (rc) {
2837                         fprintf(stderr, "Set pool name: %s failed. %s\n",
2838                                 lsa->lsa_pool_name, strerror(errno));
2839                         return rc;
2840                 }
2841         } else {
2842                 rc = llapi_layout_pool_name_set(layout, "");
2843                 if (rc) {
2844                         fprintf(stderr, "Clear pool name failed: %s\n",
2845                                 strerror(errno));
2846                         return rc;
2847                 }
2848         }
2849
2850         rc = lsa_args_stripe_count_check(lsa);
2851         if (rc)
2852                 return rc;
2853
2854         if (lsa->lsa_nr_tgts > 0) {
2855                 bool found = false;
2856
2857                 for (i = 0; i < lsa->lsa_nr_tgts; i++) {
2858                         rc = llapi_layout_ost_index_set(layout, i,
2859                                                         lsa->lsa_tgts[i]);
2860                         if (rc)
2861                                 break;
2862
2863                         /* Make sure stripe offset is in OST list. */
2864                         if (lsa->lsa_tgts[i] == lsa->lsa_stripe_off)
2865                                 found = true;
2866                 }
2867                 if (!found) {
2868                         fprintf(stderr, "Invalid stripe offset '%lld', not in the target list",
2869                                 lsa->lsa_stripe_off);
2870                         errno = EINVAL;
2871                         return -1;
2872                 }
2873         } else if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT &&
2874                    lsa->lsa_stripe_off != -1) {
2875                 rc = llapi_layout_ost_index_set(layout, 0, lsa->lsa_stripe_off);
2876         }
2877         if (rc) {
2878                 fprintf(stderr, "Set ost index %d failed. %s\n",
2879                         i, strerror(errno));
2880                 return rc;
2881         }
2882
2883         /* Create the second, virtual component of extension space */
2884         if (lsa->lsa_extension_comp) {
2885                 lsa->lsa_comp_flags |= LCME_FL_EXTENSION;
2886                 lsa->lsa_extension_comp = false;
2887                 goto new_comp;
2888         }
2889
2890         return rc;
2891 }
2892
2893 static int build_component(struct llapi_layout **layout,
2894                            struct lfs_setstripe_args *lsa, bool set_extent)
2895 {
2896         int rc;
2897
2898         rc = comp_args_to_layout(layout, lsa, set_extent);
2899         if (rc)
2900                 return rc;
2901
2902         if (lsa->lsa_mirror_count > 0) {
2903                 rc = llapi_layout_mirror_count_set(*layout,
2904                                                    lsa->lsa_mirror_count);
2905                 if (rc)
2906                         return rc;
2907
2908                 rc = llapi_layout_flags_set(*layout, LCM_FL_RDONLY);
2909                 if (rc)
2910                         return rc;
2911                 lsa->lsa_mirror_count = 0;
2912         }
2913
2914         return rc;
2915 }
2916
2917 static int build_prev_component(struct llapi_layout **layout,
2918                                 struct lfs_setstripe_args *prev,
2919                                 struct lfs_setstripe_args *lsa,
2920                                 bool set_extent)
2921 {
2922         int extension = lsa->lsa_comp_flags & LCME_FL_EXTENSION;
2923         int rc;
2924
2925         if (prev->lsa_stripe_size) {
2926                 if (extension) {
2927                         prev->lsa_comp_end = lsa->lsa_comp_end;
2928                         prev->lsa_extension_size = lsa->lsa_extension_size;
2929                         prev->lsa_extension_comp = true;
2930                 }
2931
2932                 rc = build_component(layout, prev, true);
2933                 if (rc)
2934                         return rc;
2935         }
2936
2937         /*
2938          * Copy lsa to previous lsa;
2939          * if this is an extension component, make the previous invalid;
2940          */
2941         if (extension)
2942                 prev->lsa_stripe_size = 0;
2943         else
2944                 *prev = *lsa;
2945
2946         return 0;
2947 }
2948
2949 static int build_layout_from_yaml_node(struct cYAML *node,
2950                                        struct llapi_layout **layout,
2951                                        struct lfs_setstripe_args *lsa,
2952                                        struct lfs_setstripe_args *prevp)
2953 {
2954         struct lfs_setstripe_args prev = { 0 };
2955         __u32 *osts = lsa->lsa_tgts;
2956         char *string;
2957         int rc = 0;
2958
2959         if (!prevp)
2960                 prevp = &prev;
2961
2962         while (node) {
2963                 string = node->cy_string;
2964
2965                 if (node->cy_type == CYAML_TYPE_OBJECT) {
2966                         /* go deep to sub blocks */
2967                         if (string && !strncmp(string, "component", 9) &&
2968                             strncmp(string, "component0", 10) &&
2969                             strncmp(string, "components", 10)) {
2970                                 rc = build_prev_component(layout, prevp, lsa,
2971                                                           true);
2972                                 if (rc)
2973                                         return rc;
2974
2975                                 /* initialize lsa. */
2976                                 setstripe_args_init(lsa);
2977                                 lsa->lsa_first_comp = false;
2978                                 lsa->lsa_tgts = osts;
2979                         }
2980
2981                         rc = build_layout_from_yaml_node(node->cy_child, layout,
2982                                                          lsa, prevp);
2983                         if (rc)
2984                                 return rc;
2985                 } else {
2986                         if (!node->cy_string)
2987                                 return -EINVAL;
2988
2989                         /* skip leading lmm_ if present, to simplify parsing */
2990                         if (strncmp(string, "lmm_", 4) == 0)
2991                                 string += 4;
2992
2993                         if (node->cy_type == CYAML_TYPE_STRING) {
2994                                 if (!strcmp(string, "lcme_extent.e_end")) {
2995                                         if (!strcmp(node->cy_valuestring, "EOF") ||
2996                                             !strcmp(node->cy_valuestring, "eof"))
2997                                                 lsa->lsa_comp_end = LUSTRE_EOF;
2998                                 } else if (!strcmp(string, "pool")) {
2999                                         lsa->lsa_pool_name = node->cy_valuestring;
3000                                 } else if (!strcmp(string, "pattern")) {
3001                                         if (!strcmp(node->cy_valuestring, "mdt"))
3002                                                 lsa->lsa_pattern = LLAPI_LAYOUT_MDT;
3003                                         if (!strcmp(node->cy_valuestring,
3004                                                     "raid0,overstriped"))
3005                                                 lsa->lsa_pattern =
3006                                                         LLAPI_LAYOUT_OVERSTRIPING;
3007                                 } else if (!strcmp(string, "lcme_flags")) {
3008                                         rc = comp_str2flags(node->cy_valuestring,
3009                                                             &lsa->lsa_comp_flags,
3010                                                             &lsa->lsa_comp_neg_flags);
3011                                         if (rc)
3012                                                 return rc;
3013                                         /*
3014                                          * Only template flags have meaning in
3015                                          * the layout for a new file
3016                                          */
3017                                         lsa->lsa_comp_flags &= LCME_TEMPLATE_FLAGS;
3018                                 }
3019                         } else if (node->cy_type == CYAML_TYPE_NUMBER) {
3020                                 if (!strcmp(string, "lcm_mirror_count")) {
3021                                         lsa->lsa_mirror_count = node->cy_valueint;
3022                                 } else if (!strcmp(string, "lcme_extent.e_start")) {
3023                                         if (node->cy_valueint == 0)
3024                                                 lsa->lsa_first_comp = true;
3025                                 } else if (!strcmp(string, "lcme_extent.e_end")) {
3026                                         if (node->cy_valueint == -1)
3027                                                 lsa->lsa_comp_end = LUSTRE_EOF;
3028                                         else
3029                                                 lsa->lsa_comp_end = node->cy_valueint;
3030                                 } else if (!strcmp(string, "stripe_count")) {
3031                                         lsa->lsa_stripe_count = node->cy_valueint;
3032                                 } else if (!strcmp(string, "stripe_size")) {
3033                                         lsa->lsa_stripe_size = node->cy_valueint;
3034                                 } else if (!strcmp(string, "extension_size")) {
3035                                         lsa->lsa_extension_size = node->cy_valueint;
3036                                         lsa->lsa_extension_comp = true;
3037                                 } else if (!strcmp(string, "stripe_offset")) {
3038                                         lsa->lsa_stripe_off = node->cy_valueint;
3039                                 } else if (!strcmp(string, "l_ost_idx")) {
3040                                         osts[lsa->lsa_nr_tgts] = node->cy_valueint;
3041                                         lsa->lsa_nr_tgts++;
3042                                 }
3043                         }
3044                 }
3045                 node = node->cy_next;
3046         }
3047
3048         if (prevp == &prev) {
3049                 rc = build_prev_component(layout, prevp, lsa, true);
3050                 if (rc)
3051                         return rc;
3052
3053                 if (!(lsa->lsa_comp_flags & LCME_FL_EXTENSION))
3054                         rc = build_component(layout, lsa, *layout != NULL);
3055         }
3056
3057         return rc;
3058 }
3059
3060 static int lfs_comp_create_from_yaml(char *template,
3061                                      struct llapi_layout **layout,
3062                                      struct lfs_setstripe_args *lsa,
3063                                      __u32 *osts)
3064 {
3065         struct cYAML *tree = NULL, *err_rc = NULL;
3066         int rc = 0;
3067
3068         tree = cYAML_build_tree(template, NULL, 0, &err_rc, false);
3069         if (!tree) {
3070                 fprintf(stderr, "%s: cannot parse YAML file %s\n",
3071                         progname, template);
3072                 cYAML_build_error(-EINVAL, -1, "yaml", "from comp yaml",
3073                                   "can't parse", &err_rc);
3074                 cYAML_print_tree2file(stderr, err_rc);
3075                 cYAML_free_tree(err_rc);
3076                 rc = -EINVAL;
3077                 goto err;
3078         }
3079
3080         /* initialize lsa for plain file */
3081         setstripe_args_init(lsa);
3082         lsa->lsa_tgts = osts;
3083
3084         rc = build_layout_from_yaml_node(tree, layout, lsa, NULL);
3085         if (rc) {
3086                 fprintf(stderr, "%s: cannot build layout from YAML file %s.\n",
3087                         progname, template);
3088                 goto err;
3089         }
3090         /* clean clean lsa */
3091         setstripe_args_init(lsa);
3092
3093 err:
3094         if (tree)
3095                 cYAML_free_tree(tree);
3096         return rc;
3097 }
3098
3099 /**
3100  * Get the extension size from the next (SEL) component and extend the
3101  * current component on it. The start of the next component is to be
3102  * adjusted as well.
3103  *
3104  * \param[in] layout    the current layout
3105  * \param[in] start     the start of the current component
3106  * \param[in,out] end   the end of the current component
3107  * \param[in] offset    the offset to adjust the end position to instead of
3108  *                      extension size
3109  *
3110  * \retval 0            - extended successfully
3111  * \retval < 0          - error
3112  */
3113 static int layout_extend_comp(struct llapi_layout *layout,
3114                               uint64_t start, uint64_t *end,
3115                               uint64_t offset)
3116 {
3117         uint64_t size, next_start, next_end;
3118         int rc;
3119
3120         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_NEXT);
3121         if (rc < 0) {
3122                 fprintf(stderr,
3123                         "%s setstripe: cannot move component cursor: %s\n",
3124                         progname, strerror(errno));
3125                 return rc;
3126         }
3127
3128         /*
3129          * Even if the @size will not be used below, this will fail if
3130          * this is not a SEL component - a good confirmation we are
3131          * working on right components.
3132          */
3133         rc = llapi_layout_extension_size_get(layout, &size);
3134         if (rc < 0) {
3135                 fprintf(stderr,
3136                         "%s setstripe: cannot get component ext size: %s\n",
3137                         progname, strerror(errno));
3138                 return rc;
3139         }
3140
3141         rc = llapi_layout_comp_extent_get(layout, &next_start, &next_end);
3142         if (rc) {
3143                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
3144                         progname, strerror(errno));
3145                 return rc;
3146         }
3147
3148         next_start += offset ?: size;
3149         rc = llapi_layout_comp_extent_set(layout, next_start, next_end);
3150         if (rc) {
3151                 fprintf(stderr, "%s setstripe: cannot set extent: %s\n",
3152                         progname, strerror(errno));
3153                 return rc;
3154         }
3155
3156         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_PREV);
3157         if (rc < 0) {
3158                 fprintf(stderr,
3159                         "%s setstripe: cannot move component cursor: %s\n",
3160                         progname, strerror(errno));
3161                 return rc;
3162         }
3163
3164         *end += offset ?: size;
3165         rc = llapi_layout_comp_extent_set(layout, start, *end);
3166         if (rc) {
3167                 fprintf(stderr, "%s setstripe: cannot set extent: %s\n",
3168                         progname, strerror(errno));
3169                 return rc;
3170         }
3171
3172         return 0;
3173 }
3174
3175 /**
3176  * In 'lfs setstripe --component-add' mode, we need to fetch the extent
3177  * end of the last component in the existing file, and adjust the
3178  * first extent start of the components to be added accordingly.
3179  *
3180  * In the create mode, we need to check if the first component is an extendable
3181  * SEL component and extend its length to the extension size (first component
3182  * of the PFL file is initialised at the create time, cannot be 0-lenght.
3183  */
3184 static int layout_adjust_first_extent(char *fname, struct llapi_layout *layout,
3185                                       bool comp_add)
3186 {
3187         struct llapi_layout *head;
3188         uint64_t start = 0, prev_end = 0;
3189         uint64_t end;
3190         int rc, ret = 0;
3191
3192         if (!layout || !(comp_add || llapi_layout_is_composite(layout)))
3193                 return 0;
3194
3195         errno = 0;
3196         while (comp_add) {
3197                 head = llapi_layout_get_by_path(fname, 0);
3198                 if (!head) {
3199                         fprintf(stderr,
3200                                 "%s setstripe: cannot read layout from '%s': %s\n",
3201                                 progname, fname, strerror(errno));
3202                         return -EINVAL;
3203                 } else if (errno == ENODATA) {
3204                         /*
3205                          * file without LOVEA, this component-add will be turned
3206                          * into a component-create.
3207                          */
3208                         llapi_layout_free(head);
3209                         ret = -ENODATA;
3210
3211                         /*
3212                          * the new layout will be added to an empty one, it
3213                          * still needs to be adjusted below
3214                          */
3215                         comp_add = 0;
3216                         break;
3217                 } else if (!llapi_layout_is_composite(head)) {
3218                         fprintf(stderr,
3219                                 "%s setstripe: '%s' not a composite file\n",
3220                                 progname, fname);
3221                         llapi_layout_free(head);
3222                         return -EINVAL;
3223                 }
3224
3225                 rc = llapi_layout_comp_extent_get(head, &start, &prev_end);
3226                 if (rc) {
3227                         fprintf(stderr,
3228                                 "%s setstripe: cannot get prev extent: %s\n",
3229                                 progname, strerror(errno));
3230                         llapi_layout_free(head);
3231                         return rc;
3232                 }
3233
3234                 llapi_layout_free(head);
3235                 break;
3236         }
3237
3238         /* Make sure we use the first component of the layout to be added. */
3239         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
3240         if (rc < 0) {
3241                 fprintf(stderr,
3242                         "%s setstripe: cannot move component cursor: %s\n",
3243                         progname, strerror(errno));
3244                 return rc;
3245         }
3246
3247         rc = llapi_layout_comp_extent_get(layout, &start, &end);
3248         if (rc) {
3249                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
3250                         progname, strerror(errno));
3251                 return rc;
3252         }
3253
3254         if (start == 0 && end == 0) {
3255                 rc = layout_extend_comp(layout, start, &end,
3256                                         comp_add ? prev_end : 0);
3257                 if (rc)
3258                         return rc;
3259         }
3260
3261         if (start > prev_end || end < prev_end) {
3262                 fprintf(stderr,
3263                         "%s setstripe: first extent [%lu, %lu) not adjacent with extent end %lu\n",
3264                         progname, start, end, prev_end);
3265                 return -EINVAL;
3266         }
3267
3268         rc = llapi_layout_comp_extent_set(layout, prev_end, end);
3269         if (rc) {
3270                 fprintf(stderr,
3271                         "%s setstripe: cannot set component extent [%lu, %lu): %s\n",
3272                         progname, prev_end, end, strerror(errno));
3273                 return rc;
3274         }
3275
3276         return ret;
3277 }
3278
3279 static int mirror_adjust_first_extents(struct mirror_args *list)
3280 {
3281         int rc = 0;
3282
3283         if (!list)
3284                 return 0;
3285
3286         while (list) {
3287                 rc = layout_adjust_first_extent(NULL, list->m_layout, false);
3288                 if (rc)
3289                         break;
3290                 list = list->m_next;
3291         }
3292
3293         return rc;
3294 }
3295
3296 static inline bool arg_is_eof(char *arg)
3297 {
3298         return !strncmp(arg, "-1", strlen("-1")) ||
3299                !strncmp(arg, "EOF", strlen("EOF")) ||
3300                !strncmp(arg, "eof", strlen("eof"));
3301 }
3302
3303 /**
3304  * lfs_mirror_alloc() - Allocate a mirror argument structure.
3305  *
3306  * Return: Valid mirror_args pointer on success and
3307  *         NULL if memory allocation fails.
3308  */
3309 static struct mirror_args *lfs_mirror_alloc(void)
3310 {
3311         struct mirror_args *mirror = NULL;
3312
3313         while (1) {
3314                 mirror = calloc(1, sizeof(*mirror));
3315                 if (mirror) {
3316                         mirror->m_inherit = false;
3317                         break;
3318                 }
3319
3320                 sleep(1);
3321         }
3322
3323         return mirror;
3324 }
3325
3326 /**
3327  * lfs_mirror_free() - Free memory allocated for a mirror argument
3328  *                     structure.
3329  * @mirror: Previously allocated mirror argument structure by
3330  *          lfs_mirror_alloc().
3331  *
3332  * Free memory allocated for @mirror.
3333  *
3334  * Return: void.
3335  */
3336 static void lfs_mirror_free(struct mirror_args *mirror)
3337 {
3338         if (mirror->m_layout)
3339                 llapi_layout_free(mirror->m_layout);
3340         free(mirror);
3341 }
3342
3343 /**
3344  * lfs_mirror_list_free() - Free memory allocated for a mirror list.
3345  * @mirror_list: Previously allocated mirror list.
3346  *
3347  * Free memory allocated for @mirror_list.
3348  *
3349  * Return: void.
3350  */
3351 static void lfs_mirror_list_free(struct mirror_args *mirror_list)
3352 {
3353         struct mirror_args *next_mirror = NULL;
3354
3355         while (mirror_list) {
3356                 next_mirror = mirror_list->m_next;
3357                 lfs_mirror_free(mirror_list);
3358                 mirror_list = next_mirror;
3359         }
3360 }
3361
3362 enum {
3363         LFS_POOL_OPT = 3,
3364         LFS_COMP_COUNT_OPT,
3365         LFS_COMP_START_OPT,
3366         LFS_COMP_FLAGS_OPT,
3367         LFS_COMP_DEL_OPT,
3368         LFS_COMP_SET_OPT,
3369         LFS_COMP_ADD_OPT,
3370         LFS_COMP_NO_VERIFY_OPT,
3371         LFS_PROJID_OPT,
3372         LFS_LAYOUT_FLAGS_OPT, /* used for mirror and foreign flags */
3373         LFS_MIRROR_ID_OPT,
3374         LFS_MIRROR_STATE_OPT,
3375         LFS_LAYOUT_COPY,
3376         LFS_MIRROR_INDEX_OPT,
3377         LFS_LAYOUT_FOREIGN_OPT,
3378         LFS_MODE_OPT,
3379         LFS_NEWERXY_OPT,
3380         LFS_INHERIT_RR_OPT,
3381         LFS_FIND_PERM,
3382 };
3383
3384 /* functions */
3385 static int lfs_setstripe_internal(int argc, char **argv,
3386                                   enum setstripe_origin opc)
3387 {
3388         struct lfs_setstripe_args        lsa = { 0 };
3389         struct llapi_stripe_param       *param = NULL;
3390         struct find_param                migrate_mdt_param = {
3391                 .fp_max_depth = -1,
3392                 .fp_mdt_index = -1,
3393         };
3394         char                            *fname;
3395         int                              result = 0;
3396         int                              result2 = 0;
3397         char                            *end;
3398         int                              c;
3399         int                              delete = 0;
3400         unsigned long long               size_units = 1;
3401         bool                             migrate_mode = false;
3402         bool                             migrate_mdt_mode = false;
3403         bool                             setstripe_mode = false;
3404         bool                             migration_block = false;
3405         __u64                            migration_flags = 0;
3406         __u32                            tgts[LOV_MAX_STRIPE_COUNT] = { 0 };
3407         int                              comp_del = 0, comp_set = 0;
3408         int                              comp_add = 0;
3409         __u32                            comp_id = 0;
3410         struct llapi_layout             *layout = NULL;
3411         struct llapi_layout             **lpp = &layout;
3412         bool                             mirror_mode = false;
3413         bool                             has_m_file = false;
3414         __u32                            mirror_count = 0;
3415         enum mirror_flags                mirror_flags = 0;
3416         struct mirror_args              *mirror_list = NULL;
3417         struct mirror_args              *new_mirror = NULL;
3418         struct mirror_args              *last_mirror = NULL;
3419         __u16                            mirror_id = 0;
3420         char                             cmd[PATH_MAX];
3421         bool from_yaml = false;
3422         bool from_copy = false;
3423         char *template = NULL;
3424         bool foreign_mode = false;
3425         char *xattr = NULL;
3426         uint32_t type = LU_FOREIGN_TYPE_NONE, flags = 0;
3427         char *mode_opt = NULL;
3428         mode_t previous_umask = 0;
3429         mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
3430
3431         struct option long_opts[] = {
3432 /* find { .val = '0',   .name = "null",         .has_arg = no_argument }, */
3433 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
3434         /* --block is only valid in migrate mode */
3435         { .val = 'b',   .name = "block",        .has_arg = no_argument },
3436 /* find { .val = 'B',   .name = "btime",        .has_arg = required_argument }*/
3437         { .val = LFS_COMP_ADD_OPT,
3438                         .name = "comp-add",     .has_arg = no_argument },
3439         { .val = LFS_COMP_ADD_OPT,
3440                         .name = "component-add", .has_arg = no_argument },
3441         { .val = LFS_COMP_DEL_OPT,
3442                         .name = "comp-del",     .has_arg = no_argument },
3443         { .val = LFS_COMP_DEL_OPT,
3444                         .name = "component-del", .has_arg = no_argument },
3445         { .val = LFS_COMP_FLAGS_OPT,
3446                         .name = "comp-flags",   .has_arg = required_argument },
3447         { .val = LFS_COMP_FLAGS_OPT,
3448                         .name = "component-flags",
3449                                                 .has_arg = required_argument },
3450         { .val = LFS_COMP_SET_OPT,
3451                         .name = "comp-set",     .has_arg = no_argument },
3452         { .val = LFS_COMP_SET_OPT,
3453                         .name = "component-set",
3454                                                 .has_arg = no_argument},
3455         { .val = LFS_COMP_NO_VERIFY_OPT,
3456                         .name = "no-verify",    .has_arg = no_argument},
3457         { .val = LFS_LAYOUT_FLAGS_OPT,
3458                         .name = "flags",        .has_arg = required_argument},
3459         { .val = LFS_LAYOUT_FOREIGN_OPT,
3460                         .name = "foreign",      .has_arg = optional_argument},
3461         { .val = LFS_MIRROR_ID_OPT,
3462                         .name = "mirror-id",    .has_arg = required_argument},
3463         { .val = LFS_MODE_OPT,
3464                         .name = "mode",         .has_arg = required_argument},
3465         { .val = LFS_LAYOUT_COPY,
3466                         .name = "copy",         .has_arg = required_argument},
3467         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument},
3468         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument},
3469         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument},
3470         { .val = 'C',   .name = "overstripe-count",
3471                                                 .has_arg = required_argument},
3472         { .val = 'd',   .name = "delete",       .has_arg = no_argument},
3473         { .val = 'd',   .name = "destroy",      .has_arg = no_argument},
3474         /* --non-direct is only valid in migrate mode */
3475         { .val = 'D',   .name = "non-direct",   .has_arg = no_argument },
3476         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument},
3477         { .val = 'E',   .name = "component-end",
3478                                                 .has_arg = required_argument},
3479         { .val = 'f',   .name = "file",         .has_arg = required_argument },
3480 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
3481 /* find { .val = 'g',   .name = "gid",          .has_arg = no_argument }, */
3482 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
3483         { .val = 'h',   .name = "help",         .has_arg = no_argument },
3484         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument},
3485         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument},
3486         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument},
3487         { .val = 'I',   .name = "comp-id",      .has_arg = required_argument},
3488         { .val = 'I',   .name = "component-id", .has_arg = required_argument},
3489 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
3490         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
3491         { .val = 'm',   .name = "mdt",          .has_arg = required_argument},
3492         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument},
3493         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument},
3494         /* --non-block is only valid in migrate mode */
3495         { .val = 'n',   .name = "non-block",    .has_arg = no_argument },
3496         { .val = 'N',   .name = "mirror-count", .has_arg = optional_argument},
3497         { .val = 'o',   .name = "ost",          .has_arg = required_argument },
3498 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
3499         { .val = 'o',   .name = "ost-list",     .has_arg = required_argument },
3500         { .val = 'o',   .name = "ost_list",     .has_arg = required_argument },
3501 #endif
3502         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
3503 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
3504 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
3505 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
3506 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
3507         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
3508         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
3509 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
3510 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
3511 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
3512 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
3513         /* --verbose is only valid in migrate mode */
3514         { .val = 'v',   .name = "verbose",      .has_arg = no_argument},
3515         { .val = 'x',   .name = "xattr",        .has_arg = required_argument },
3516 /* dirstripe { .val = 'X',.name = "max-inherit",.has_arg = required_argument }*/
3517         { .val = 'y',   .name = "yaml",         .has_arg = required_argument },
3518         { .val = 'z',   .name = "ext-size",     .has_arg = required_argument},
3519         { .val = 'z',   .name = "extension-size", .has_arg = required_argument},
3520         { .name = NULL } };
3521
3522         setstripe_args_init(&lsa);
3523
3524         migrate_mode = (opc == SO_MIGRATE);
3525         mirror_mode = (opc == SO_MIRROR_CREATE || opc == SO_MIRROR_EXTEND);
3526         setstripe_mode = (opc == SO_SETSTRIPE);
3527         if (opc == SO_MIRROR_DELETE) {
3528                 delete = 1;
3529                 mirror_flags = MF_DESTROY;
3530         }
3531
3532         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
3533         progname = cmd;
3534         while ((c = getopt_long(argc, argv,
3535                                 "bc:C:dDE:f:hH:i:I:m:N::no:p:L:s:S:vx:y:z:",
3536                                 long_opts, NULL)) >= 0) {
3537                 size_units = 1;
3538                 switch (c) {
3539                 case 0:
3540                         /* Long options. */
3541                         break;
3542                 case LFS_COMP_ADD_OPT:
3543                         comp_add = 1;
3544                         break;
3545                 case LFS_COMP_DEL_OPT:
3546                         comp_del = 1;
3547                         break;
3548                 case LFS_COMP_FLAGS_OPT:
3549                         result = comp_str2flags(optarg, &lsa.lsa_comp_flags,
3550                                                 &lsa.lsa_comp_neg_flags);
3551                         if (result != 0)
3552                                 goto usage_error;
3553                         if (mirror_mode && lsa.lsa_comp_neg_flags) {
3554                                 fprintf(stderr,
3555                                         "%s: inverted flags are not supported\n",
3556                                         progname);
3557                                 goto usage_error;
3558                         }
3559                         break;
3560                 case LFS_COMP_SET_OPT:
3561                         comp_set = 1;
3562                         break;
3563                 case LFS_COMP_NO_VERIFY_OPT:
3564                         mirror_flags |= MF_NO_VERIFY;
3565                         break;
3566                 case LFS_MIRROR_ID_OPT: {
3567                         unsigned long int id;
3568
3569                         errno = 0;
3570                         id = strtoul(optarg, &end, 0);
3571                         if (errno != 0 || *end != '\0' || id == 0 ||
3572                             id > UINT16_MAX) {
3573                                 fprintf(stderr,
3574                                         "%s %s: invalid mirror ID '%s'\n",
3575                                         progname, argv[0], optarg);
3576                                 goto usage_error;
3577                         }
3578
3579                         mirror_id = (__u16)id;
3580                         break;
3581                 }
3582                 case LFS_LAYOUT_FLAGS_OPT: {
3583                         uint32_t neg_flags;
3584
3585                         /* check for numeric flags (foreign and mirror cases) */
3586                         if (setstripe_mode && !mirror_mode && !last_mirror) {
3587                                 errno = 0;
3588                                 flags = strtoul(optarg, &end, 16);
3589                                 if (errno != 0 || *end != '\0' ||
3590                                     flags >= UINT32_MAX) {
3591                                         fprintf(stderr,
3592                                                 "%s %s: invalid hex flags '%s'\n",
3593                                                 progname, argv[0], optarg);
3594                                         return CMD_HELP;
3595                                 }
3596                                 if (!foreign_mode) {
3597                                         fprintf(stderr,
3598                                                 "%s %s: hex flags must be specified with --foreign option\n",
3599                                                 progname, argv[0]);
3600                                         return CMD_HELP;
3601                                 }
3602                                 break;
3603                         }
3604
3605                         if (!mirror_mode || !last_mirror) {
3606                                 fprintf(stderr,
3607                                         "error: %s: --flags must be specified with --mirror-count|-N option\n",
3608                                         progname);
3609                                 goto usage_error;
3610                         }
3611
3612                         result = comp_str2flags(optarg, &last_mirror->m_flags,
3613                                                 &neg_flags);
3614                         if (result != 0)
3615                                 goto usage_error;
3616
3617                         if (neg_flags) {
3618                                 fprintf(stderr,
3619                                         "%s: inverted flags are not supported\n",
3620                                         progname);
3621                                 result = -EINVAL;
3622                                 goto usage_error;
3623                         }
3624                         if (last_mirror->m_flags & ~LCME_USER_MIRROR_FLAGS) {
3625                                 fprintf(stderr,
3626                                         "%s: unsupported mirror flags: %s\n",
3627                                         progname, optarg);
3628                                 result = -EINVAL;
3629                                 goto error;
3630                         }
3631                         break;
3632                 }
3633                 case LFS_LAYOUT_FOREIGN_OPT:
3634                         if (optarg) {
3635                                 /* check pure numeric */
3636                                 type = strtoul(optarg, &end, 0);
3637                                 if (*end) {
3638                                         /* check name */
3639                                         type = check_foreign_type_name(optarg);
3640                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
3641                                                 fprintf(stderr,
3642                                                         "%s %s: unrecognized foreign type '%s'\n",
3643                                                         progname, argv[0],
3644                                                         optarg);
3645                                                 return CMD_HELP;
3646                                         }
3647                                 } else if (type >= UINT32_MAX) {
3648                                         fprintf(stderr,
3649                                                 "%s %s: invalid foreign type '%s'\n",
3650                                                 progname, argv[0], optarg);
3651                                         return CMD_HELP;
3652                                 }
3653                         }
3654                         foreign_mode = true;
3655                         break;
3656                 case LFS_MODE_OPT:
3657                         mode_opt = optarg;
3658                         if (mode_opt) {
3659                                 mode = strtoul(mode_opt, &end, 8);
3660                                 if (*end != '\0') {
3661                                         fprintf(stderr,
3662                                                 "%s %s: bad mode '%s'\n",
3663                                                 progname, argv[0], mode_opt);
3664                                         return CMD_HELP;
3665                                 }
3666                                 previous_umask = umask(0);
3667                         }
3668                         break;
3669                 case LFS_LAYOUT_COPY:
3670                         from_copy = true;
3671                         template = optarg;
3672                         break;
3673                 case 'b':
3674                         if (!migrate_mode) {
3675                                 fprintf(stderr,
3676                                         "%s %s: -b|--block valid only for migrate command\n",
3677                                         progname, argv[0]);
3678                                 goto usage_error;
3679                         }
3680                         migration_block = true;
3681                         break;
3682                 case 'C':
3683                         if (lsa.lsa_pattern == LLAPI_LAYOUT_MDT) {
3684                                 fprintf(stderr,
3685                                         "%s %s: -C|--overstripe-count incompatible with DoM layout\n",
3686                                         progname, argv[0]);
3687                                 goto usage_error;
3688                         }
3689                         lsa.lsa_pattern = LLAPI_LAYOUT_OVERSTRIPING;
3690                         /* fall through */
3691                 case 'c':
3692                         errno = 0;
3693                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
3694                         if (errno != 0 || *end != '\0'||
3695                             lsa.lsa_stripe_count < -1 ||
3696                             lsa.lsa_stripe_count > LOV_MAX_STRIPE_COUNT) {
3697                                 fprintf(stderr,
3698                                         "%s %s: invalid stripe count '%s'\n",
3699                                         progname, argv[0], optarg);
3700                                 goto usage_error;
3701                         }
3702
3703                         if (lsa.lsa_stripe_count == -1)
3704                                 lsa.lsa_stripe_count = LLAPI_LAYOUT_WIDE;
3705                         break;
3706                 case 'd':
3707                         /* delete the default striping pattern */
3708                         delete = 1;
3709                         if (opc == SO_MIRROR_SPLIT) {
3710                                 if (has_m_file) {
3711                                         fprintf(stderr,
3712                                               "%s %s: -d cannot used with -f\n",
3713                                                 progname, argv[0]);
3714                                         goto usage_error;
3715                                 }
3716                                 mirror_flags |= MF_DESTROY;
3717                         }
3718                         break;
3719                 case 'D':
3720                         if (!migrate_mode) {
3721                                 fprintf(stderr,
3722                                         "%s %s: -D|--non-direct is valid only for migrate command\n",
3723                                         progname, argv[0]);
3724                                 goto usage_error;
3725                         }
3726                         migration_flags |= MIGRATION_NONDIRECT;
3727                         break;
3728                 case 'E':
3729                         if (lsa.lsa_comp_end != 0) {
3730                                 result = comp_args_to_layout(lpp, &lsa, true);
3731                                 if (result) {
3732                                         fprintf(stderr, "%s: invalid layout\n",
3733                                                 progname);
3734                                         goto usage_error;
3735                                 }
3736
3737                                 setstripe_args_init_inherit(&lsa);
3738                         }
3739
3740                         if (arg_is_eof(optarg)) {
3741                                 lsa.lsa_comp_end = LUSTRE_EOF;
3742                         } else {
3743                                 result = llapi_parse_size(optarg,
3744                                                           &lsa.lsa_comp_end,
3745                                                           &size_units, 0);
3746                                 /* assume units of KB if too small */
3747                                 if (lsa.lsa_comp_end < 4096)
3748                                         lsa.lsa_comp_end *= 1024;
3749                                 if (result ||
3750                                     lsa.lsa_comp_end & (LOV_MIN_STRIPE_SIZE - 1)) {
3751                                         fprintf(stderr,
3752                                                 "%s %s: invalid component end '%s'\n",
3753                                                 progname, argv[0], optarg);
3754                                         goto usage_error;
3755                                 }
3756                         }
3757                         break;
3758                 case 'H':
3759                         if (!migrate_mode) {
3760                                 fprintf(stderr,
3761                                         "--mdt-hash is valid only for migrate command\n");
3762                                 return CMD_HELP;
3763                         }
3764
3765                         lsa.lsa_pattern = check_hashtype(optarg);
3766                         if (lsa.lsa_pattern == 0) {
3767                                 fprintf(stderr,
3768                                         "%s %s: bad stripe hash type '%s'\n",
3769                                         progname, argv[0], optarg);
3770                                 return CMD_HELP;
3771                         }
3772                         break;
3773                 case 'i':
3774                         errno = 0;
3775                         lsa.lsa_stripe_off = strtol(optarg, &end, 0);
3776                         if (errno != 0 || *end != '\0' ||
3777                             lsa.lsa_stripe_off < -1 ||
3778                             lsa.lsa_stripe_off > LOV_V1_INSANE_STRIPE_COUNT) {
3779                                 fprintf(stderr,
3780                                         "%s %s: invalid stripe offset '%s'\n",
3781                                         progname, argv[0], optarg);
3782                                 goto usage_error;
3783                         }
3784                         if (lsa.lsa_stripe_off == -1)
3785                                 lsa.lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
3786                         break;
3787                 case 'I':
3788                         comp_id = strtoul(optarg, &end, 0);
3789                         if (*end != '\0' || comp_id == 0 ||
3790                             comp_id > LCME_ID_MAX) {
3791                                 fprintf(stderr,
3792                                         "%s %s: invalid component ID '%s'\n",
3793                                         progname, argv[0], optarg);
3794                                 goto usage_error;
3795                         }
3796                         break;
3797                 case 'f':
3798                         if (opc != SO_MIRROR_EXTEND && opc != SO_MIRROR_SPLIT) {
3799                                 fprintf(stderr,
3800                                         "error: %s: invalid option: %s\n",
3801                                         progname, argv[optopt + 1]);
3802                                 goto usage_error;
3803                         }
3804                         if (opc == SO_MIRROR_EXTEND) {
3805                                 if (!last_mirror) {
3806                                         fprintf(stderr,
3807                                 "error: %s: '-N' must exist in front of '%s'\n",
3808                                                 progname, argv[optopt + 1]);
3809                                         goto usage_error;
3810                                 }
3811                                 last_mirror->m_file = optarg;
3812                                 last_mirror->m_count = 1;
3813                         } else {
3814                                 /* mirror split */
3815                                 if (!mirror_list)
3816                                         mirror_list = lfs_mirror_alloc();
3817                                 mirror_list->m_file = optarg;
3818                         }
3819                         has_m_file = true;
3820                         break;
3821                 case 'L':
3822                         if (strcmp(argv[optind - 1], "mdt") == 0) {
3823                                 /* Can be only the first component */
3824                                 if (layout) {
3825                                         result = -EINVAL;
3826                                         fprintf(stderr,
3827                                                 "error: 'mdt' layout can be only the first one\n");
3828                                         goto error;
3829                                 }
3830                                 if (lsa.lsa_comp_end > (1ULL << 30)) { /* 1Gb */
3831                                         result = -EFBIG;
3832                                         fprintf(stderr,
3833                                                 "error: 'mdt' layout size is too big\n");
3834                                         goto error;
3835                                 }
3836                                 lsa.lsa_pattern = LLAPI_LAYOUT_MDT;
3837                         } else if (strcmp(argv[optind - 1], "raid0") != 0) {
3838                                 result = -EINVAL;
3839                                 fprintf(stderr,
3840                                         "error: layout '%s' is unknown, supported layouts are: 'mdt', 'raid0'\n",
3841                                         argv[optind]);
3842                                 goto error;
3843                         }
3844                         break;
3845                 case 'm':
3846                         if (!migrate_mode) {
3847                                 fprintf(stderr,
3848                                         "%s %s: -m|--mdt-index is valid only for migrate command\n",
3849                                         progname, argv[0]);
3850                                 goto usage_error;
3851                         }
3852                         migrate_mdt_mode = true;
3853                         lsa.lsa_nr_tgts = parse_targets(tgts,
3854                                                 sizeof(tgts) / sizeof(__u32),
3855                                                 lsa.lsa_nr_tgts, optarg, NULL);
3856                         if (lsa.lsa_nr_tgts < 0) {
3857                                 fprintf(stderr,
3858                                         "%s: invalid MDT target(s) '%s'\n",
3859                                         progname, optarg);
3860                                 goto usage_error;
3861                         }
3862
3863                         lsa.lsa_tgts = tgts;
3864                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
3865                                 lsa.lsa_stripe_off = tgts[0];
3866                         break;
3867                 case 'n':
3868                         if (!migrate_mode) {
3869                                 fprintf(stderr,
3870                                         "%s %s: -n|--non-block valid only for migrate command\n",
3871                                         progname, argv[0]);
3872                                 goto usage_error;
3873                         }
3874                         migration_flags |= MIGRATION_NONBLOCK;
3875                         break;
3876                 case 'N':
3877                         if (opc == SO_SETSTRIPE) {
3878                                 opc = SO_MIRROR_CREATE;
3879                                 mirror_mode = true;
3880                         }
3881                         mirror_count = 1;
3882                         if (optarg) {
3883                                 errno = 0;
3884                                 mirror_count = strtoul(optarg, &end, 0);
3885                                 if (errno != 0 || *end != '\0' ||
3886                                     mirror_count == 0 ||
3887                                     mirror_count > LUSTRE_MIRROR_COUNT_MAX) {
3888                                         fprintf(stderr,
3889                                                 "error: %s: bad mirror count: %s\n",
3890                                                 progname, optarg);
3891                                         result = -EINVAL;
3892                                         goto error;
3893                                 }
3894                         }
3895
3896                         new_mirror = lfs_mirror_alloc();
3897                         new_mirror->m_count = mirror_count;
3898
3899                         if (!mirror_list)
3900                                 mirror_list = new_mirror;
3901
3902                         if (last_mirror) {
3903                                 /* wrap up last mirror */
3904                                 if (!setstripe_args_specified(&lsa))
3905                                         last_mirror->m_inherit = true;
3906                                 if (lsa.lsa_comp_end == 0)
3907                                         lsa.lsa_comp_end = LUSTRE_EOF;
3908
3909                                 result = comp_args_to_layout(lpp, &lsa, true);
3910                                 if (result) {
3911                                         lfs_mirror_free(new_mirror);
3912                                         goto error;
3913                                 }
3914
3915                                 setstripe_args_init_inherit(&lsa);
3916
3917                                 last_mirror->m_next = new_mirror;
3918                         }
3919
3920                         last_mirror = new_mirror;
3921                         lpp = &last_mirror->m_layout;
3922                         break;
3923                 case 'o':
3924 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
3925                         if (strcmp(argv[optind - 1], "--ost-list") == 0)
3926                                 fprintf(stderr,
3927                                         "warning: '--ost-list' is deprecated, use '--ost' instead\n");
3928 #endif
3929                         if (lsa.lsa_pattern == LLAPI_LAYOUT_MDT) {
3930                                 fprintf(stderr,
3931                                         "%s %s: -o|--ost incompatible with DoM layout\n",
3932                                         progname, argv[0]);
3933                                 goto usage_error;
3934                         }
3935                         /*
3936                          * -o allows overstriping, and must note it because
3937                          * parse_targets is shared with MDT striping, which
3938                          * does not allow duplicates
3939                          */
3940                         lsa.lsa_pattern = LLAPI_LAYOUT_OVERSTRIPING;
3941                         lsa.lsa_nr_tgts = parse_targets(tgts,
3942                                                 sizeof(tgts) / sizeof(__u32),
3943                                                 lsa.lsa_nr_tgts, optarg,
3944                                                 &lsa.lsa_pattern);
3945                         if (lsa.lsa_nr_tgts < 0) {
3946                                 fprintf(stderr,
3947                                         "%s %s: invalid OST target(s) '%s'\n",
3948                                         progname, argv[0], optarg);
3949                                 goto usage_error;
3950                         }
3951
3952                         lsa.lsa_tgts = tgts;
3953                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
3954                                 lsa.lsa_stripe_off = tgts[0];
3955                         break;
3956                 case 'p':
3957                         if (!optarg)
3958                                 goto usage_error;
3959                         lsa.lsa_pool_name = optarg;
3960
3961                         if (strlen(lsa.lsa_pool_name) == 0 ||
3962                             strncmp(lsa.lsa_pool_name, "none",
3963                                     LOV_MAXPOOLNAME) == 0)
3964                                 lsa.lsa_pool_name = NULL;
3965                         break;
3966                 case 'S':
3967                         result = llapi_parse_size(optarg, &lsa.lsa_stripe_size,
3968                                                   &size_units, 0);
3969                         /* assume units of KB if too small to be valid */
3970                         if (lsa.lsa_stripe_size < 4096)
3971                                 lsa.lsa_stripe_size *= 1024;
3972                         if (result ||
3973                             lsa.lsa_stripe_size & (LOV_MIN_STRIPE_SIZE - 1)) {
3974                                 fprintf(stderr,
3975                                         "%s %s: invalid stripe size '%s'\n",
3976                                         progname, argv[0], optarg);
3977                                 goto usage_error;
3978                         }
3979                         break;
3980                 case 'v':
3981                         if (!migrate_mode) {
3982                                 fprintf(stderr,
3983                                         "%s %s: -v|--verbose valid only for migrate command\n",
3984                                         progname, argv[0]);
3985                                 goto usage_error;
3986                         }
3987                         migrate_mdt_param.fp_verbose = VERBOSE_DETAIL;
3988                         migration_flags = MIGRATION_VERBOSE;
3989                         break;
3990                 case 'x':
3991                         xattr = optarg;
3992                         break;
3993                 case 'y':
3994                         from_yaml = true;
3995                         template = optarg;
3996                         break;
3997                 case 'z':
3998                         result = llapi_parse_size(optarg,
3999                                                   &lsa.lsa_extension_size,
4000                                                   &size_units, 0);
4001                         if (result) {
4002                                 fprintf(stderr,
4003                                         "%s %s: invalid extension size '%s'\n",
4004                                         progname, argv[0], optarg);
4005                                 goto usage_error;
4006                         }
4007
4008                         lsa.lsa_extension_comp = true;
4009                         break;
4010                 default:
4011                         fprintf(stderr, "%s: unrecognized option '%s'\n",
4012                                 progname, argv[optind - 1]);
4013                 case 'h':
4014                         goto usage_error;
4015                 }
4016         }
4017
4018         fname = argv[optind];
4019
4020         if (optind == argc) {
4021                 fprintf(stderr, "%s %s: FILE must be specified\n",
4022                         progname, argv[0]);
4023                 goto usage_error;
4024         }
4025
4026         /* lfs migrate $filename should keep the file's layout by default */
4027         if (migrate_mode && !setstripe_args_specified(&lsa) && !layout &&
4028             !from_yaml)
4029                 from_copy = true;
4030
4031         if (xattr && !foreign_mode) {
4032                 /*
4033                  * only print a warning as this is harmless and will be ignored
4034                  */
4035                 fprintf(stderr,
4036                         "%s %s: xattr has been specified for non-foreign layout\n",
4037                         progname, argv[0]);
4038         } else if (foreign_mode && !xattr) {
4039                 fprintf(stderr,
4040                         "%s %s: xattr must be provided in foreign mode\n",
4041                         progname, argv[0]);
4042                 goto usage_error;
4043         }
4044
4045         if (foreign_mode && (!setstripe_mode || comp_add | comp_del ||
4046             comp_set || comp_id || delete || from_copy ||
4047             setstripe_args_specified(&lsa) || lsa.lsa_nr_tgts ||
4048             lsa.lsa_tgts)) {
4049                 fprintf(stderr,
4050                         "%s %s: only --xattr/--flags/--mode options are valid with --foreign\n",
4051                         progname, argv[0]);
4052                 return CMD_HELP;
4053         }
4054
4055         if (mirror_mode && mirror_count == 0) {
4056                 fprintf(stderr,
4057                         "error: %s: --mirror-count|-N option is required\n",
4058                         progname);
4059                 result = -EINVAL;
4060                 goto error;
4061         }
4062
4063         if (mirror_mode) {
4064                 if (!setstripe_args_specified(&lsa))
4065                         last_mirror->m_inherit = true;
4066                 if (lsa.lsa_comp_end == 0)
4067                         lsa.lsa_comp_end = LUSTRE_EOF;
4068         }
4069
4070         if (lsa.lsa_comp_end != 0) {
4071                 result = comp_args_to_layout(lpp, &lsa, true);
4072                 if (result) {
4073                         fprintf(stderr, "error: %s: invalid layout\n",
4074                                 progname);
4075                         result = -EINVAL;
4076                         goto error;
4077                 }
4078         }
4079
4080         if (mirror_flags & MF_NO_VERIFY) {
4081                 if (opc != SO_MIRROR_EXTEND) {
4082                         fprintf(stderr,
4083                                 "error: %s: --no-verify is valid only for lfs mirror extend command\n",
4084                                 progname);
4085                         result = -EINVAL;
4086                         goto error;
4087                 } else if (!has_m_file) {
4088                         fprintf(stderr,
4089                                 "error: %s: --no-verify must be specified with -f <victim_file> option\n",
4090                                 progname);
4091                         result = -EINVAL;
4092                         goto error;
4093                 }
4094         }
4095
4096         if (comp_set && !comp_id && !lsa.lsa_pool_name) {
4097                 fprintf(stderr,
4098                         "%s %s: --component-set doesn't have component-id set\n",
4099                         progname, argv[0]);
4100                 goto usage_error;
4101         }
4102
4103         if ((delete + comp_set + comp_del + comp_add) > 1) {
4104                 fprintf(stderr,
4105                         "%s %s: options --component-set, --component-del, --component-add and -d are mutually exclusive\n",
4106                         progname, argv[0]);
4107                 goto usage_error;
4108         }
4109
4110         if (delete && (setstripe_args_specified(&lsa) || comp_id != 0 ||
4111                        lsa.lsa_comp_flags != 0 || layout != NULL)) {
4112                 fprintf(stderr,
4113                         "%s %s: option -d is mutually exclusive with -s, -c, -o, -p, -I, -F and -E options\n",
4114                         progname, argv[0]);
4115                 goto usage_error;
4116         }
4117
4118         if ((comp_set || comp_del) &&
4119             (setstripe_args_specified(&lsa) || layout != NULL)) {
4120                 fprintf(stderr,
4121                         "%s %s: options --component-del and --component-set are mutually exclusive when used with -c, -E, -o, -p, or -s\n",
4122                         progname, argv[0]);
4123                 goto usage_error;
4124         }
4125
4126         if (comp_del && comp_id != 0 && lsa.lsa_comp_flags != 0) {
4127                 fprintf(stderr,
4128                         "%s %s: options -I and -F are mutually exclusive when used with --component-del\n",
4129                         progname, argv[0]);
4130                 goto usage_error;
4131         }
4132
4133         if (comp_add || comp_del) {
4134                 struct stat st;
4135
4136                 result = lstat(fname, &st);
4137                 if (result == 0 && S_ISDIR(st.st_mode)) {
4138                         fprintf(stderr,
4139                                 "%s setstripe: cannot use --component-add or --component-del for directory\n",
4140                                 progname);
4141                         goto usage_error;
4142                 }
4143
4144                 if (mirror_mode) {
4145                         fprintf(stderr,
4146                                 "error: %s: can't use --component-add or --component-del for mirror operation\n",
4147                                 progname);
4148                         goto usage_error;
4149                 }
4150         }
4151
4152         if (comp_add) {
4153                 if (!layout) {
4154                         fprintf(stderr,
4155                                 "%s %s: option -E must be specified with --component-add\n",
4156                                 progname, argv[0]);
4157                         goto usage_error;
4158                 }
4159         }
4160
4161         if (from_yaml && from_copy) {
4162                 fprintf(stderr,
4163                         "%s: can't specify --yaml and --copy together\n",
4164                         progname);
4165                 goto error;
4166         }
4167
4168         if ((from_yaml || from_copy) &&
4169             (setstripe_args_specified(&lsa) || layout != NULL)) {
4170                 fprintf(stderr,
4171                         "error: %s: can't specify --yaml or --copy with -c, -S, -i, -o, -p or -E options.\n",
4172                         argv[0]);
4173                 goto error;
4174         }
4175
4176         if ((migration_flags & MIGRATION_NONBLOCK) && migration_block) {
4177                 fprintf(stderr,
4178                         "%s %s: options --non-block and --block are mutually exclusive\n",
4179                         progname, argv[0]);
4180                 goto usage_error;
4181         }
4182
4183         if (!comp_del && !comp_set && opc != SO_MIRROR_SPLIT &&
4184             opc != SO_MIRROR_DELETE && comp_id != 0) {
4185                 fprintf(stderr,
4186                         "%s: option -I can only be used with --component-del or --component-set or lfs mirror split\n",
4187                         progname);
4188                 goto usage_error;
4189         }
4190
4191         if (migrate_mdt_mode) {
4192                 struct lmv_user_md *lmu;
4193
4194                 /* initialize migrate mdt parameters */
4195                 lmu = calloc(1, lmv_user_md_size(lsa.lsa_nr_tgts,
4196                                                  LMV_USER_MAGIC_SPECIFIC));
4197                 if (!lmu) {
4198                         fprintf(stderr,
4199                                 "%s %s: cannot allocate memory for lmv_user_md: %s\n",
4200                                 progname, argv[0], strerror(ENOMEM));
4201                         result = -ENOMEM;
4202                         goto error;
4203                 }
4204                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
4205                         lmu->lum_stripe_count = lsa.lsa_stripe_count;
4206                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT) {
4207                         fprintf(stderr,
4208                                 "%s %s: migrate should specify MDT index\n",
4209                                 progname, argv[0]);
4210                         free(lmu);
4211                         goto usage_error;
4212                 }
4213                 lmu->lum_stripe_offset = lsa.lsa_stripe_off;
4214                 if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
4215                         lmu->lum_hash_type = lsa.lsa_pattern;
4216                 else
4217                         lmu->lum_hash_type = LMV_HASH_TYPE_UNKNOWN;
4218                 if (lsa.lsa_pool_name) {
4219                         strncpy(lmu->lum_pool_name, lsa.lsa_pool_name,
4220                                 sizeof(lmu->lum_pool_name) - 1);
4221                         lmu->lum_pool_name[sizeof(lmu->lum_pool_name) - 1] = 0;
4222                 }
4223                 if (lsa.lsa_nr_tgts > 1) {
4224                         int i;
4225
4226                         if (lsa.lsa_stripe_count > 0 &&
4227                             lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
4228                             lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
4229                                 fprintf(stderr,
4230                                         "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
4231                                         progname, lsa.lsa_stripe_count,
4232                                         lsa.lsa_nr_tgts);
4233                                 free(lmu);
4234                                 goto usage_error;
4235                         }
4236
4237                         lmu->lum_magic = LMV_USER_MAGIC_SPECIFIC;
4238                         lmu->lum_stripe_count = lsa.lsa_nr_tgts;
4239                         for (i = 0; i < lsa.lsa_nr_tgts; i++)
4240                                 lmu->lum_objects[i].lum_mds = lsa.lsa_tgts[i];
4241                 } else {
4242                         lmu->lum_magic = LMV_USER_MAGIC;
4243                 }
4244
4245                 migrate_mdt_param.fp_lmv_md = lmu;
4246                 migrate_mdt_param.fp_migrate = 1;
4247         } else if (!layout) {
4248                 if (lsa_args_stripe_count_check(&lsa))
4249                         goto usage_error;
4250
4251                 /* initialize stripe parameters */
4252                 param = calloc(1, offsetof(typeof(*param),
4253                                lsp_osts[lsa.lsa_nr_tgts]));
4254                 if (!param) {
4255                         fprintf(stderr,
4256                                 "%s %s: cannot allocate memory for parameters: %s\n",
4257                                 progname, argv[0], strerror(ENOMEM));
4258                         result = -ENOMEM;
4259                         goto error;
4260                 }
4261
4262                 if (lsa.lsa_stripe_size != LLAPI_LAYOUT_DEFAULT)
4263                         param->lsp_stripe_size = lsa.lsa_stripe_size;
4264                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
4265                         if (lsa.lsa_stripe_count == LLAPI_LAYOUT_WIDE)
4266                                 param->lsp_stripe_count = -1;
4267                         else
4268                                 param->lsp_stripe_count = lsa.lsa_stripe_count;
4269                 }
4270                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
4271                         param->lsp_stripe_offset = -1;
4272                 else
4273                         param->lsp_stripe_offset = lsa.lsa_stripe_off;
4274                 param->lsp_stripe_pattern =
4275                                 llapi_pattern_to_lov(lsa.lsa_pattern);
4276                 if (param->lsp_stripe_pattern == EINVAL) {
4277                         fprintf(stderr, "error: %s: invalid stripe pattern\n",
4278                                 argv[0]);
4279                         free(param);
4280                         goto usage_error;
4281                 }
4282                 param->lsp_pool = lsa.lsa_pool_name;
4283                 param->lsp_is_specific = false;
4284
4285                 if (lsa.lsa_nr_tgts > 0) {
4286                         param->lsp_is_specific = true;
4287                         param->lsp_stripe_count = lsa.lsa_nr_tgts;
4288                         memcpy(param->lsp_osts, tgts,
4289                                sizeof(*tgts) * lsa.lsa_nr_tgts);
4290                 }
4291         }
4292
4293         if (from_yaml) {
4294                 /* generate a layout from a YAML template */
4295                 result = lfs_comp_create_from_yaml(template, &layout,
4296                                                    &lsa, tgts);
4297                 if (result) {
4298                         fprintf(stderr,
4299                                 "error: %s: can't create composite layout from template file %s\n",
4300                                 argv[0], template);
4301                         goto error;
4302                 }
4303         }
4304
4305         if (layout != NULL || mirror_list != NULL) {
4306                 if (mirror_list)
4307                         result = mirror_adjust_first_extents(mirror_list);
4308                 else
4309                         result = layout_adjust_first_extent(fname, layout,
4310                                                             comp_add);
4311                 if (result == -ENODATA)
4312                         comp_add = 0;
4313                 else if (result != 0) {
4314                         fprintf(stderr, "error: %s: invalid layout\n",
4315                                 progname);
4316                         goto error;
4317                 }
4318         }
4319
4320         for (fname = argv[optind]; fname != NULL; fname = argv[++optind]) {
4321                 if (from_copy) {
4322                         layout = llapi_layout_get_by_path(template ?: fname, 0);
4323                         if (!layout) {
4324                                 fprintf(stderr,
4325                                         "%s: can't create composite layout from file %s: %s\n",
4326                                         progname, template ?: fname,
4327                                         strerror(errno));
4328                                 result = -errno;
4329                                 goto error;
4330                         }
4331                 }
4332
4333                 if (migrate_mdt_mode) {
4334                         result = llapi_migrate_mdt(fname, &migrate_mdt_param);
4335                 } else if (migrate_mode) {
4336                         result = lfs_migrate(fname, migration_flags, param,
4337                                              layout);
4338                 } else if (comp_set != 0) {
4339                         result = lfs_component_set(fname, comp_id,
4340                                                    lsa.lsa_pool_name,
4341                                                    lsa.lsa_comp_flags,
4342                                                    lsa.lsa_comp_neg_flags);
4343                 } else if (comp_del != 0) {
4344                         result = lfs_component_del(fname, comp_id,
4345                                                    lsa.lsa_comp_flags,
4346                                                    lsa.lsa_comp_neg_flags);
4347                 } else if (comp_add != 0) {
4348                         result = lfs_component_add(fname, layout);
4349                 } else if (opc == SO_MIRROR_CREATE) {
4350                         result = mirror_create(fname, mirror_list);
4351                 } else if (opc == SO_MIRROR_EXTEND) {
4352                         result = mirror_extend(fname, mirror_list,
4353                                                mirror_flags);
4354                 } else if (opc == SO_MIRROR_SPLIT || opc == SO_MIRROR_DELETE) {
4355                         if (!mirror_id && !comp_id && !lsa.lsa_pool_name) {
4356                                 fprintf(stderr,
4357                                         "%s: no mirror id, component id, or pool name specified to delete from '%s'\n",
4358                                         progname, fname);
4359                                 goto usage_error;
4360                         }
4361                         if (lsa.lsa_pool_name)
4362                                 mirror_flags |= MF_COMP_POOL;
4363                         else if (mirror_id != 0)
4364                                 comp_id = mirror_id;
4365                         else
4366                                 mirror_flags |= MF_COMP_ID;
4367                         if (has_m_file && !strcmp(fname, mirror_list->m_file)) {
4368                                 fprintf(stderr,
4369                                         "%s: the file specified by -f cannot be same as the source file '%s'\n",
4370                                         progname, fname);
4371                                 goto usage_error;
4372                         }
4373                         result = mirror_split(fname, comp_id, lsa.lsa_pool_name,
4374                                               mirror_flags,
4375                                               has_m_file ? mirror_list->m_file :
4376                                               NULL);
4377                 } else if (layout) {
4378                         result = lfs_component_create(fname, O_CREAT | O_WRONLY,
4379                                                       mode, layout);
4380                         if (result >= 0) {
4381                                 close(result);
4382                                 result = 0;
4383                         }
4384                 } else if (foreign_mode) {
4385                         result = llapi_file_create_foreign(fname, mode, type,
4386                                                            flags, xattr);
4387                         if (result >= 0) {
4388                                 close(result);
4389                                 result = 0;
4390                         }
4391                 } else {
4392                         result = llapi_file_open_param(fname,
4393                                                        O_CREAT | O_WRONLY,
4394                                                        mode, param);
4395                         if (result >= 0) {
4396                                 close(result);
4397                                 result = 0;
4398                         }
4399                 }
4400                 if (result) {
4401                         /* Save the first error encountered. */
4402                         if (result2 == 0)
4403                                 result2 = result;
4404                         continue;
4405                 }
4406         }
4407
4408         if (mode_opt)
4409                 umask(previous_umask);
4410
4411         free(param);
4412         free(migrate_mdt_param.fp_lmv_md);
4413         llapi_layout_free(layout);
4414         lfs_mirror_list_free(mirror_list);
4415         return result2;
4416 usage_error:
4417         result = CMD_HELP;
4418 error:
4419         llapi_layout_free(layout);
4420         lfs_mirror_list_free(mirror_list);
4421         return result;
4422 }
4423
4424 static int lfs_poollist(int argc, char **argv)
4425 {
4426         if (argc != 2)
4427                 return CMD_HELP;
4428
4429         return llapi_poollist(argv[1]);
4430 }
4431
4432 #define FP_DEFAULT_TIME_MARGIN (24 * 60 * 60)
4433 static time_t set_time(struct find_param *param, time_t *time, time_t *set,
4434                        char *str)
4435 {
4436         long long t = 0;
4437         int sign = 0;
4438         char *endptr = "AD";
4439         char *timebuf;
4440
4441         if (str[0] == '+')
4442                 sign = 1;
4443         else if (str[0] == '-')
4444                 sign = -1;
4445
4446         if (sign)
4447                 str++;
4448
4449         for (timebuf = str; *endptr && *(endptr + 1); timebuf = endptr + 1) {
4450                 long long val = strtoll(timebuf, &endptr, 0);
4451                 int unit = 1;
4452
4453                 switch (*endptr) {
4454                 case  'y':
4455                         unit *= 52; /* 52 weeks + 1 day below */
4456                 case  'w':      /* fallthrough */
4457                         unit *= 7;
4458                         if (param->fp_time_margin == FP_DEFAULT_TIME_MARGIN)
4459                                 param->fp_time_margin *= (1 + unit / 52);
4460                         unit += (*endptr == 'y'); /* +1 day for 365 days/year */
4461                 case '\0': /* days are default unit if none used */
4462                 case  'd':      /* fallthrough */
4463                         unit *= 24;
4464                 case  'h':      /* fallthrough */
4465                         unit *= 60;
4466                 case  'm':      /* fallthrough */
4467                         unit *= 60;
4468                 case  's':      /* fallthrough */
4469                         break;
4470                         /* don't need to multiply by 1 for seconds */
4471                 default:
4472                         fprintf(stderr,
4473                                 "%s find: bad time string '%s': %s\n",
4474                                 progname, timebuf, strerror(EINVAL));
4475                         return LONG_MAX;
4476                 }
4477
4478                 if (param->fp_time_margin == 0 ||
4479                     (*endptr && unit < param->fp_time_margin))
4480                         param->fp_time_margin = unit;
4481
4482                 t += val * unit;
4483         }
4484         if (*time < t) {
4485                 if (sign != 0)
4486                         str--;
4487                 fprintf(stderr, "%s find: bad time '%s': too large\n",
4488                         progname, str);
4489                 return LONG_MAX;
4490         }
4491
4492         *set = *time - t;
4493
4494         return sign;
4495 }
4496
4497 static int str2quotaid(__u32 *id, const char *arg)
4498 {
4499         unsigned long int projid_tmp = 0;
4500         char *endptr = NULL;
4501
4502         projid_tmp = strtoul(arg, &endptr, 10);
4503         if (*endptr != '\0')
4504                 return -EINVAL;
4505         if (projid_tmp >= UINT32_MAX)
4506                 return -ERANGE;
4507
4508         *id = projid_tmp;
4509         return 0;
4510 }
4511
4512 static int name2uid(unsigned int *id, const char *name)
4513 {
4514         struct passwd *passwd;
4515
4516         passwd = getpwnam(name);
4517         if (!passwd)
4518                 return -ENOENT;
4519         *id = passwd->pw_uid;
4520
4521         return 0;
4522 }
4523
4524 static int name2gid(unsigned int *id, const char *name)
4525 {
4526         struct group *group;
4527
4528         group = getgrnam(name);
4529         if (!group)
4530                 return -ENOENT;
4531         *id = group->gr_gid;
4532
4533         return 0;
4534 }
4535
4536 static inline int name2projid(unsigned int *id, const char *name)
4537 {
4538         return -ENOTSUP;
4539 }
4540
4541 static int uid2name(char **name, unsigned int id)
4542 {
4543         struct passwd *passwd;
4544
4545         passwd = getpwuid(id);
4546         if (!passwd)
4547                 return -ENOENT;
4548         *name = passwd->pw_name;
4549
4550         return 0;
4551 }
4552
4553 static inline int gid2name(char **name, unsigned int id)
4554 {
4555         struct group *group;
4556
4557         group = getgrgid(id);
4558         if (!group)
4559                 return -ENOENT;
4560         *name = group->gr_name;
4561
4562         return 0;
4563 }
4564
4565 static int name2layout(__u32 *layout, char *name)
4566 {
4567         char *ptr, *layout_name;
4568
4569         *layout = 0;
4570         for (ptr = name; ; ptr = NULL) {
4571                 layout_name = strtok(ptr, ",");
4572                 if (!layout_name)
4573                         break;
4574                 if (strcmp(layout_name, "released") == 0)
4575                         *layout |= LOV_PATTERN_F_RELEASED;
4576                 else if (strcmp(layout_name, "raid0") == 0)
4577                         *layout |= LOV_PATTERN_RAID0;
4578                 else if (strcmp(layout_name, "mdt") == 0)
4579                         *layout |= LOV_PATTERN_MDT;
4580                 else if (strcmp(layout_name, "overstriping") == 0)
4581                         *layout |= LOV_PATTERN_OVERSTRIPING;
4582                 else
4583                         return -1;
4584         }
4585         return 0;
4586 }
4587
4588 static int parse_symbolic(const char *input, mode_t *outmode, const char **end)
4589 {
4590         int loop;
4591         int user, group, other;
4592         int who, all;
4593         char c, op;
4594         mode_t perm;
4595         mode_t usermask;
4596         mode_t previous_flags;
4597
4598         user = group = other = 0;
4599         all = 0;
4600         loop = 1;
4601         perm = 0;
4602         previous_flags = 0;
4603         *end = input;
4604         usermask = 0;
4605
4606         while (loop) {
4607                 switch (*input) {
4608                 case 'u':
4609                         user = 1;
4610                         break;
4611                 case 'g':
4612                         group = 1;
4613                         break;
4614                 case 'o':
4615                         other = 1;
4616                         break;
4617                 case 'a':
4618                         user = group = other = 1;
4619                         all = 1;
4620                         break;
4621                 default:
4622                         loop = 0;
4623                 }
4624
4625                 if (loop)
4626                         input++;
4627         }
4628
4629         who = user || group || other;
4630         if (!who) {
4631                 /* get the umask */
4632                 usermask = umask(0022);
4633                 umask(usermask);
4634                 usermask &= 07777;
4635         }
4636
4637         if (*input == '-' || *input == '+' || *input == '=')
4638                 op = *input++;
4639         else
4640                 /* operation is required */
4641                 return -1;
4642
4643         /* get the flags in *outmode */
4644         switch (*input) {
4645         case 'u':
4646                 previous_flags = (*outmode & 0700);
4647                 perm |= user  ? previous_flags : 0;
4648                 perm |= group ? (previous_flags >> 3) : 0;
4649                 perm |= other ? (previous_flags >> 6) : 0;
4650                 input++;
4651                 goto write_perm;
4652         case 'g':
4653                 previous_flags = (*outmode & 0070);
4654                 perm |= user  ? (previous_flags << 3) : 0;
4655                 perm |= group ? previous_flags : 0;
4656                 perm |= other ? (previous_flags >> 3) : 0;
4657                 input++;
4658                 goto write_perm;
4659         case 'o':
4660                 previous_flags = (*outmode & 0007);
4661                 perm |= user  ? (previous_flags << 6) : 0;
4662                 perm |= group ? (previous_flags << 3) : 0;
4663                 perm |= other ? previous_flags : 0;
4664                 input++;
4665                 goto write_perm;
4666         default:
4667                 break;
4668         }
4669
4670         /* this part is optional,
4671          * if empty perm = 0 and *outmode is not modified
4672          */
4673         loop = 1;
4674         while (loop) {
4675                 c = *input;
4676                 switch (c) {
4677                 case 'r':
4678                         perm |= user  ? 0400 : 0;
4679                         perm |= group ? 0040 : 0;
4680                         perm |= other ? 0004 : 0;
4681                         /* set read permission for uog except for umask's
4682                          * permissions
4683                          */
4684                         perm |= who   ? 0 : (0444 & ~usermask);
4685                         break;
4686                 case 'w':
4687                         perm |= user  ? 0200 : 0;
4688                         perm |= group ? 0020 : 0;
4689                         perm |= other ? 0002 : 0;
4690                         /* set write permission for uog except for umask'
4691                          * permissions
4692                          */
4693                         perm |= who   ? 0 : (0222 & ~usermask);
4694                         break;
4695                 case 'x':
4696                         perm |= user  ? 0100 : 0;
4697                         perm |= group ? 0010 : 0;
4698                         perm |= other ? 0001 : 0;
4699                         /* set execute permission for uog except for umask'
4700                          * permissions
4701                          */
4702                         perm |= who   ? 0 : (0111 & ~usermask);
4703                         break;
4704                 case 'X':
4705                         /*
4706                          * Adds execute permission to 'u', 'g' and/or 'g' if
4707                          * specified and either 'u', 'g' or 'o' already has
4708                          * execute permissions.
4709                          */
4710                         if ((*outmode & 0111) != 0) {
4711                                 perm |= user  ? 0100 : 0;
4712                                 perm |= group ? 0010 : 0;
4713                                 perm |= other ? 0001 : 0;
4714                                 perm |= !who  ? 0111 : 0;
4715                         }
4716                         break;
4717                 case 's':
4718                         /* s is ignored if o is given, but it's not an error */
4719                         if (other && !group && !user)
4720                                 break;
4721                         perm |= user  ? S_ISUID : 0;
4722                         perm |= group ? S_ISGID : 0;
4723                         break;
4724                 case 't':
4725                         /* 't' should be used when 'a' is given
4726                          * or who is empty
4727                          */
4728                         perm |= (!who || all) ? S_ISVTX : 0;
4729                         /* using ugo with t is not an error */
4730                         break;
4731                 default:
4732                         loop = 0;
4733                         break;
4734                 }
4735                 if (loop)
4736                         input++;
4737         }
4738
4739 write_perm:
4740         /* uog flags should be only one character long */
4741         if (previous_flags && (*input != '\0' && *input != ','))
4742                 return -1;
4743
4744         switch (op) {
4745         case '-':
4746                 /* remove the flags from outmode */
4747                 *outmode &= ~perm;
4748                 break;
4749         case '+':
4750                 /* add the flags to outmode */
4751                 *outmode |= perm;
4752                 break;
4753         case '=':
4754                 /* set the flags of outmode to perm */
4755                 if (perm != 0)
4756                         *outmode = perm;
4757                 break;
4758         }
4759
4760         *end = input;
4761         return 0;
4762 }
4763
4764 static int str2mode_t(const char *input, mode_t *outmode)
4765 {
4766         int ret;
4767         const char *iter;
4768
4769         ret = 0;
4770
4771         if (*input >= '0' && *input <= '7') {
4772                 /* parse octal representation */
4773                 char *end;
4774
4775                 iter = input;
4776
4777                 /* look for invalid digits in octal representation */
4778                 while (isdigit(*iter))
4779                         if (*iter++ > '7')
4780                                 return -1;
4781
4782                 errno = 0;
4783                 *outmode = strtoul(input, &end, 8);
4784
4785                 if (errno != 0 || *outmode > 07777) {
4786                         *outmode = 0;
4787                         ret = -1;
4788                 }
4789
4790         } else if (*input == '8' || *input == '9') {
4791                 /* error: invalid octal number */
4792                 ret = -1;
4793         } else {
4794                 /* parse coma seperated list of symbolic representation */
4795                 int rc;
4796                 const char *end;
4797
4798                 *outmode = 0;
4799                 rc = 0;
4800                 end = NULL;
4801
4802                 do {
4803                         rc = parse_symbolic(input, outmode, &end);
4804                         if (rc)
4805                                 return -1;
4806
4807                         input = end+1;
4808                 } while (*end == ',');
4809
4810                 if (*end != '\0')
4811                         ret = -1;
4812         }
4813         return ret;
4814 }
4815
4816 static int lfs_find(int argc, char **argv)
4817 {
4818         int c, rc;
4819         int ret = 0;
4820         time_t t;
4821         struct find_param param = {
4822                 .fp_max_depth = -1,
4823                 .fp_quiet = 1,
4824                 .fp_time_margin = FP_DEFAULT_TIME_MARGIN,
4825         };
4826         struct option long_opts[] = {
4827         { .val = 'A',   .name = "atime",        .has_arg = required_argument },
4828         { .val = 'b',   .name = "blocks",       .has_arg = required_argument },
4829         { .val = 'B',   .name = "btime",        .has_arg = required_argument },
4830         { .val = 'B',   .name = "Btime",        .has_arg = required_argument },
4831         { .val = LFS_COMP_COUNT_OPT,
4832                         .name = "comp-count",   .has_arg = required_argument },
4833         { .val = LFS_COMP_COUNT_OPT,
4834                         .name = "component-count",
4835                                                 .has_arg = required_argument },
4836         { .val = LFS_COMP_FLAGS_OPT,
4837                         .name = "comp-flags",   .has_arg = required_argument },
4838         { .val = LFS_COMP_FLAGS_OPT,
4839                         .name = "component-flags",
4840                                                 .has_arg = required_argument },
4841         { .val = LFS_COMP_START_OPT,
4842                         .name = "comp-start",   .has_arg = required_argument },
4843         { .val = LFS_COMP_START_OPT,
4844                         .name = "component-start",
4845                                                 .has_arg = required_argument },
4846         { .val = LFS_MIRROR_STATE_OPT,
4847                         .name = "mirror-state", .has_arg = required_argument },
4848         { .val = LFS_NEWERXY_OPT,
4849                         .name = "newer",        .has_arg = required_argument},
4850         { .val = LFS_NEWERXY_OPT,
4851                         .name = "neweraa",      .has_arg = required_argument},
4852         { .val = LFS_NEWERXY_OPT,
4853                         .name = "neweram",      .has_arg = required_argument},
4854         { .val = LFS_NEWERXY_OPT,
4855                         .name = "newerac",      .has_arg = required_argument},
4856         { .val = LFS_NEWERXY_OPT,
4857                         .name = "newerab",      .has_arg = required_argument},
4858         { .val = LFS_NEWERXY_OPT,
4859                         .name = "newerma",      .has_arg = required_argument},
4860         { .val = LFS_NEWERXY_OPT,
4861                         .name = "newermm",      .has_arg = required_argument},
4862         { .val = LFS_NEWERXY_OPT,
4863                         .name = "newermc",      .has_arg = required_argument},
4864         { .val = LFS_NEWERXY_OPT,
4865                         .name = "newermb",      .has_arg = required_argument},
4866         { .val = LFS_NEWERXY_OPT,
4867                         .name = "newerca",      .has_arg = required_argument},
4868         { .val = LFS_NEWERXY_OPT,
4869                         .name = "newercm",      .has_arg = required_argument},
4870         { .val = LFS_NEWERXY_OPT,
4871                         .name = "newercc",      .has_arg = required_argument},
4872         { .val = LFS_NEWERXY_OPT,
4873                         .name = "newercb",      .has_arg = required_argument},
4874         { .val = LFS_NEWERXY_OPT,
4875                         .name = "newerba",      .has_arg = required_argument},
4876         { .val = LFS_NEWERXY_OPT,
4877                         .name = "newerbm",      .has_arg = required_argument},
4878         { .val = LFS_NEWERXY_OPT,
4879                         .name = "newerbc",      .has_arg = required_argument},
4880         { .val = LFS_NEWERXY_OPT,
4881                         .name = "newerbb",      .has_arg = required_argument},
4882         { .val = LFS_NEWERXY_OPT,
4883                         .name = "newerBa",      .has_arg = required_argument},
4884         { .val = LFS_NEWERXY_OPT,
4885                         .name = "newerBm",      .has_arg = required_argument},
4886         { .val = LFS_NEWERXY_OPT,
4887                         .name = "newerBc",      .has_arg = required_argument},
4888         { .val = LFS_NEWERXY_OPT,
4889                         .name = "newerBB",      .has_arg = required_argument},
4890         { .val = LFS_NEWERXY_OPT,
4891                         .name = "newerat",      .has_arg = required_argument},
4892         { .val = LFS_NEWERXY_OPT,
4893                         .name = "newermt",      .has_arg = required_argument},
4894         { .val = LFS_NEWERXY_OPT,
4895                         .name = "newerct",      .has_arg = required_argument},
4896         { .val = LFS_NEWERXY_OPT,
4897                         .name = "newerbt",      .has_arg = required_argument},
4898         { .val = LFS_NEWERXY_OPT,
4899                         .name = "newerBt",      .has_arg = required_argument},
4900         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument },
4901         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument },
4902         { .val = 'C',   .name = "ctime",        .has_arg = required_argument },
4903 /* getstripe { .val = 'd', .name = "directory", .has_arg = no_argument }, */
4904         { .val = 'D',   .name = "maxdepth",     .has_arg = required_argument },
4905         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument },
4906         { .val = 'E',   .name = "component-end",
4907                                                 .has_arg = required_argument },
4908 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
4909         { .val = LFS_LAYOUT_FOREIGN_OPT,
4910                         .name = "foreign",      .has_arg = optional_argument},
4911         { .val = 'g',   .name = "gid",          .has_arg = required_argument },
4912         { .val = 'G',   .name = "group",        .has_arg = required_argument },
4913         { .val = 'h',   .name = "help",         .has_arg = no_argument },
4914         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
4915         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument },
4916         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument },
4917 /* getstripe { .val = 'I', .name = "comp-id",   .has_arg = required_argument }*/
4918         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
4919         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
4920         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
4921         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
4922         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument },
4923         { .val = 'M',   .name = "mtime",        .has_arg = required_argument },
4924         { .val = 'n',   .name = "name",         .has_arg = required_argument },
4925         { .val = 'N',   .name = "mirror-count", .has_arg = required_argument },
4926 /* find { .val = 'o'    .name = "or", .has_arg = no_argument }, like find(1) */
4927         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
4928         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
4929         /* no short option for pool yet, can be 'p' after 2.18 */
4930         { .val = LFS_POOL_OPT,
4931                         .name = "pool",         .has_arg = required_argument },
4932         { .val = '0',   .name = "print0",       .has_arg = no_argument },
4933         { .val = 'P',   .name = "print",        .has_arg = no_argument },
4934         { .val = LFS_PROJID_OPT,
4935                         .name = "projid",       .has_arg = required_argument },
4936 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
4937 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
4938 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
4939         { .val = 's',   .name = "size",         .has_arg = required_argument },
4940         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
4941         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
4942         { .val = 't',   .name = "type",         .has_arg = required_argument },
4943         { .val = LFS_FIND_PERM,
4944                         .name = "perm",         .has_arg = required_argument },
4945         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
4946         { .val = 'u',   .name = "uid",          .has_arg = required_argument },
4947         { .val = 'U',   .name = "user",         .has_arg = required_argument },
4948         { .val = 'z',   .name = "extension-size",
4949                                                 .has_arg = required_argument },
4950         { .val = 'z',   .name = "ext-size",     .has_arg = required_argument },
4951 /* getstripe { .val = 'v', .name = "verbose",   .has_arg = no_argument }, */
4952 /* getstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
4953         { .name = NULL } };
4954         int optidx = 0;
4955         int pathstart = -1;
4956         int pathend = -1;
4957         int pathbad = -1;
4958         int neg_opt = 0;
4959         time_t *xtime;
4960         int *xsign;
4961         int isoption;
4962         char *endptr;
4963
4964         time(&t);
4965
4966         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
4967         while ((c = getopt_long_only(argc, argv,
4968                 "-0A:b:B:c:C:D:E:g:G:hH:i:L:m:M:n:N:O:Ppqrs:S:t:T:u:U:vz:",
4969                 long_opts, &optidx)) >= 0) {
4970                 xtime = NULL;
4971                 xsign = NULL;
4972                 if (neg_opt)
4973                         --neg_opt;
4974                 /* '!' is part of option */
4975                 /*
4976                  * when getopt_long_only() finds a string which is not
4977                  * an option nor a known option argument it returns 1
4978                  * in that case if we already have found pathstart and pathend
4979                  * (i.e. we have the list of pathnames),
4980                  * the only supported value is "!"
4981                  */
4982                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
4983                 if (!isoption && pathend != -1) {
4984                         fprintf(stderr,
4985                                 "err: %s: filename|dirname must either precede options or follow options\n",
4986                                 argv[0]);
4987                         ret = CMD_HELP;
4988                         goto err;
4989                 }
4990                 if (!isoption && pathstart == -1)
4991                         pathstart = optind - 1;
4992                 if (isoption && pathstart != -1 && pathend == -1)
4993                         pathend = optind - 2;
4994                 switch (c) {
4995                 case 0:
4996                         /* Long options. */
4997                         break;
4998                 case 1:
4999                         /*
5000                          * unknown; opt is "!" or path component,
5001                          * checking done above.
5002                          */
5003                         if (strcmp(optarg, "!") == 0)
5004                                 neg_opt = 2;
5005                         break;
5006                 case 'A':
5007                         xtime = &param.fp_atime;
5008                         xsign = &param.fp_asign;
5009                         param.fp_exclude_atime = !!neg_opt;
5010                         /* no break, this falls through to 'B' for btime */
5011                 case 'B':
5012                         if (c == 'B') {
5013                                 xtime = &param.fp_btime;
5014                                 xsign = &param.fp_bsign;
5015                                 param.fp_exclude_btime = !!neg_opt;
5016                         }
5017                         /* no break, this falls through to 'C' for ctime */
5018                 case 'C':
5019                         if (c == 'C') {
5020                                 xtime = &param.fp_ctime;
5021                                 xsign = &param.fp_csign;
5022                                 param.fp_exclude_ctime = !!neg_opt;
5023                         }
5024                         /* no break, this falls through to 'M' for mtime */
5025                 case 'M':
5026                         if (c == 'M') {
5027                                 xtime = &param.fp_mtime;
5028                                 xsign = &param.fp_msign;
5029                                 param.fp_exclude_mtime = !!neg_opt;
5030                         }
5031                         rc = set_time(&param, &t, xtime, optarg);
5032                         if (rc == LONG_MAX) {
5033                                 ret = -1;
5034                                 goto err;
5035                         }
5036                         if (rc)
5037                                 *xsign = rc;
5038                         break;
5039                 case 'b':
5040                         if (optarg[0] == '+') {
5041                                 param.fp_blocks_sign = -1;
5042                                 optarg++;
5043                         } else if (optarg[0] == '-') {
5044                                 param.fp_blocks_sign =  1;
5045                                 optarg++;
5046                         }
5047
5048                         param.fp_blocks_units = 1024;
5049                         ret = llapi_parse_size(optarg, &param.fp_blocks,
5050                                                &param.fp_blocks_units, 0);
5051                         if (ret) {
5052                                 fprintf(stderr, "error: bad blocks '%s'\n",
5053                                         optarg);
5054                                 goto err;
5055                         }
5056                         param.fp_check_blocks = 1;
5057                         param.fp_exclude_blocks = !!neg_opt;
5058                         break;
5059                 case LFS_COMP_COUNT_OPT:
5060                         if (optarg[0] == '+') {
5061                                 param.fp_comp_count_sign = -1;
5062                                 optarg++;
5063                         } else if (optarg[0] == '-') {
5064                                 param.fp_comp_count_sign =  1;
5065                                 optarg++;
5066                         }
5067
5068                         errno = 0;
5069                         param.fp_comp_count = strtoul(optarg, &endptr, 0);
5070                         if (errno != 0 || *endptr != '\0' ||
5071                             param.fp_comp_count > UINT32_MAX) {
5072                                 fprintf(stderr,
5073                                         "error: bad component count '%s'\n",
5074                                         optarg);
5075                                 goto err;
5076                         }
5077                         param.fp_check_comp_count = 1;
5078                         param.fp_exclude_comp_count = !!neg_opt;
5079                         break;
5080                 case LFS_COMP_FLAGS_OPT:
5081                         rc = comp_str2flags(optarg, &param.fp_comp_flags,
5082                                             &param.fp_comp_neg_flags);
5083                         if (rc) {
5084                                 fprintf(stderr,
5085                                         "error: bad component flags '%s'\n",
5086                                         optarg);
5087                                 goto err;
5088                         }
5089                         param.fp_check_comp_flags = 1;
5090                         if (neg_opt) {
5091                                 __u32 flags = param.fp_comp_neg_flags;
5092
5093                                 param.fp_comp_neg_flags = param.fp_comp_flags;
5094                                 param.fp_comp_flags = flags;
5095                         }
5096                         break;
5097                 case LFS_COMP_START_OPT:
5098                         if (optarg[0] == '+') {
5099                                 param.fp_comp_start_sign = -1;
5100                                 optarg++;
5101                         } else if (optarg[0] == '-') {
5102                                 param.fp_comp_start_sign =  1;
5103                                 optarg++;
5104                         }
5105
5106                         rc = llapi_parse_size(optarg, &param.fp_comp_start,
5107                                               &param.fp_comp_start_units, 0);
5108                         if (rc) {
5109                                 fprintf(stderr,
5110                                         "error: bad component start '%s'\n",
5111                                         optarg);
5112                                 goto err;
5113                         }
5114                         param.fp_check_comp_start = 1;
5115                         param.fp_exclude_comp_start = !!neg_opt;
5116                         break;
5117                 case LFS_MIRROR_STATE_OPT:
5118                         rc = mirror_str2state(optarg, &param.fp_mirror_state,
5119                                               &param.fp_mirror_neg_state);
5120                         if (rc) {
5121                                 fprintf(stderr,
5122                                         "error: bad mirrored file state '%s'\n",
5123                                         optarg);
5124                                 goto err;
5125                         }
5126                         param.fp_check_mirror_state = 1;
5127                         if (neg_opt) {
5128                                 __u16 state = param.fp_mirror_neg_state;
5129
5130                                 param.fp_mirror_neg_state =
5131                                         param.fp_mirror_state;
5132                                 param.fp_mirror_state = state;
5133                         }
5134                         break;
5135                 case 'c':
5136                         if (optarg[0] == '+') {
5137                                 param.fp_stripe_count_sign = -1;
5138                                 optarg++;
5139                         } else if (optarg[0] == '-') {
5140                                 param.fp_stripe_count_sign =  1;
5141                                 optarg++;
5142                         }
5143
5144                         errno = 0;
5145                         param.fp_stripe_count = strtoul(optarg, &endptr, 0);
5146                         if (errno != 0 || *endptr != '\0' ||
5147                             param.fp_stripe_count > LOV_MAX_STRIPE_COUNT) {
5148                                 fprintf(stderr,
5149                                         "error: bad stripe_count '%s'\n",
5150                                         optarg);
5151                                 ret = -1;
5152                                 goto err;
5153                         }
5154                         param.fp_check_stripe_count = 1;
5155                         param.fp_exclude_stripe_count = !!neg_opt;
5156                         break;
5157                 case 'D':
5158                         errno = 0;
5159                         param.fp_max_depth = strtol(optarg, 0, 0);
5160                         if (errno != 0 || param.fp_max_depth < 0) {
5161                                 fprintf(stderr,
5162                                         "error: bad maxdepth '%s'\n",
5163                                         optarg);
5164                                 ret = -1;
5165                                 goto err;
5166                         }
5167                         break;
5168                 case 'E':
5169                         if (optarg[0] == '+') {
5170                                 param.fp_comp_end_sign = -1;
5171                                 optarg++;
5172                         } else if (optarg[0] == '-') {
5173                                 param.fp_comp_end_sign =  1;
5174                                 optarg++;
5175                         }
5176
5177                         if (arg_is_eof(optarg)) {
5178                                 param.fp_comp_end = LUSTRE_EOF;
5179                                 param.fp_comp_end_units = 1;
5180                                 rc = 0;
5181                         } else {
5182                                 rc = llapi_parse_size(optarg,
5183                                                 &param.fp_comp_end,
5184                                                 &param.fp_comp_end_units, 0);
5185                                 /* assume units of KB if too small */
5186                                 if (param.fp_comp_end < 4096)
5187                                         param.fp_comp_end *= 1024;
5188                         }
5189                         if (rc) {
5190                                 fprintf(stderr,
5191                                         "error: bad component end '%s'\n",
5192                                         optarg);
5193                                 goto err;
5194                         }
5195                         param.fp_check_comp_end = 1;
5196                         param.fp_exclude_comp_end = !!neg_opt;
5197                         break;
5198                 case LFS_LAYOUT_FOREIGN_OPT: {
5199                         /* all types by default */
5200                         uint32_t type = LU_FOREIGN_TYPE_UNKNOWN;
5201
5202                         if (optarg) {
5203                                 /* check pure numeric */
5204                                 type = strtoul(optarg, &endptr, 0);
5205                                 if (*endptr) {
5206                                         /* check name */
5207                                         type = check_foreign_type_name(optarg);
5208                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
5209                                                 fprintf(stderr,
5210                                                         "%s %s: unknown foreign type '%s'\n",
5211                                                         progname, argv[0],
5212                                                         optarg);
5213                                                 return CMD_HELP;
5214                                         }
5215                                 } else if (type >= UINT32_MAX) {
5216                                         fprintf(stderr,
5217                                                 "%s %s: invalid foreign type '%s'\n",
5218                                                 progname, argv[0], optarg);
5219                                         return CMD_HELP;
5220                                 }
5221                         }
5222                         param.fp_foreign_type = type;
5223                         param.fp_check_foreign = 1;
5224                         param.fp_exclude_foreign = !!neg_opt;
5225                         break;
5226                 }
5227                 case LFS_NEWERXY_OPT: {
5228                         char x = 'm';
5229                         char y = 'm';
5230                         int xidx;
5231                         int negidx;
5232                         time_t *newery;
5233                         time_t ref = time(NULL);
5234
5235                         /* no need to check bad options, they won't get here */
5236                         if (strlen(long_opts[optidx].name) == 7) {
5237                                 x = long_opts[optidx].name[5];
5238                                 y = long_opts[optidx].name[6];
5239                         }
5240
5241                         if (y == 't') {
5242                                 static const char *const fmts[] = {
5243                                         "%Y-%m-%d %H:%M:%S",
5244                                         "%Y-%m-%d %H:%M",
5245                                         "%Y-%m-%d",
5246                                         "%H:%M:%S", /* sometime today */
5247                                         "%H:%M",
5248                                         "@%s",
5249                                         "%s",
5250                                         NULL };
5251                                 struct tm tm;
5252                                 bool found = false;
5253                                 int i;
5254
5255                                 for (i = 0; fmts[i] != NULL; i++) {
5256                                         char *ptr;
5257
5258                                         /* Init for times relative to today */
5259                                         if (strncmp(fmts[i], "%H", 2) == 0)
5260                                                 localtime_r(&ref, &tm);
5261                                         else
5262                                                 memset(&tm, 0, sizeof(tm));
5263                                         ptr = strptime(optarg, fmts[i], &tm);
5264                                         /* Skip spaces */
5265                                         while (ptr && isspace(*ptr))
5266                                                 ptr++;
5267                                         if (ptr == optarg + strlen(optarg)) {
5268                                                 found = true;
5269                                                 break;
5270                                         }
5271                                 }
5272
5273                                 if (!found) {
5274                                         fprintf(stderr,
5275                                                 "%s: invalid time '%s'\n",
5276                                                 progname, optarg);
5277                                         fprintf(stderr,
5278                                                 "supported formats are:\n  ");
5279                                         for (i = 0; fmts[i] != NULL; i++)
5280                                                 fprintf(stderr, "'%s', ",
5281                                                         fmts[i]);
5282                                         fprintf(stderr, "\n");
5283                                         ret = -EINVAL;
5284                                         goto err;
5285                                 }
5286
5287                                 ref = mktime(&tm);
5288                         } else if (y == 'b' || y == 'B') {
5289                                 lstatx_t stx;
5290
5291                                 rc = llapi_get_lum_file(optarg, NULL, &stx,
5292                                                         NULL, 0);
5293                                 if (rc || !(stx.stx_mask & STATX_BTIME)) {
5294                                         if (!(stx.stx_mask & STATX_BTIME))
5295                                                 ret = -EOPNOTSUPP;
5296                                         else
5297                                                 ret = -errno;
5298                                         fprintf(stderr,
5299                                                 "%s: get btime failed '%s': %s\n",
5300                                                 progname, optarg,
5301                                                 strerror(-ret));
5302                                         goto err;
5303                                 }
5304
5305                                 ref = stx.stx_btime.tv_sec;
5306                         } else {
5307                                 struct stat statbuf;
5308
5309                                 if (stat(optarg, &statbuf) < 0) {
5310                                         fprintf(stderr,
5311                                                 "%s: cannot stat file '%s': %s\n",
5312                                                 progname, optarg,
5313                                                 strerror(errno));
5314                                         ret = -errno;
5315                                         goto err;
5316                                 }
5317
5318                                 switch (y) {
5319                                 case 'a':
5320                                         ref = statbuf.st_atime;
5321                                         break;
5322                                 case 'm':
5323                                         ref = statbuf.st_mtime;
5324                                         break;
5325                                 case 'c':
5326                                         ref = statbuf.st_ctime;
5327                                         break;
5328                                 default:
5329                                         fprintf(stderr,
5330                                                 "%s: invalid Y argument: '%c'\n",
5331                                                 progname, x);
5332                                         ret = -EINVAL;
5333                                         goto err;
5334                                 }
5335                         }
5336
5337                         switch (x) {
5338                         case 'a':
5339                                 xidx = NEWERXY_ATIME;
5340                                 break;
5341                         case 'm':
5342                                 xidx = NEWERXY_MTIME;
5343                                 break;
5344                         case 'c':
5345                                 xidx = NEWERXY_CTIME;
5346                                 break;
5347                         case 'b':
5348                         case 'B':
5349                                 xidx = NEWERXY_BTIME;
5350                                 break;
5351                         default:
5352                                 fprintf(stderr,
5353                                         "%s: invalid X argument: '%c'\n",
5354                                         progname, x);
5355                                 ret = -EINVAL;
5356                                 goto err;
5357                         }
5358
5359                         negidx = !!neg_opt;
5360                         newery = &param.fp_newery[xidx][negidx];
5361
5362                         if (*newery == 0) {
5363                                 *newery = ref;
5364                         } else {
5365                                 if (negidx)
5366                                         *newery = *newery > ref ? ref : *newery;
5367                                 else
5368                                         *newery = *newery > ref ? *newery : ref;
5369                         }
5370                         param.fp_newerxy = 1;
5371                         break;
5372                 }
5373                 case 'g':
5374                 case 'G':
5375                         rc = name2gid(&param.fp_gid, optarg);
5376                         if (rc) {
5377                                 if (str2quotaid(&param.fp_gid, optarg)) {
5378                                         fprintf(stderr,
5379                                                 "Group/GID: %s cannot be found.\n",
5380                                                 optarg);
5381                                         ret = -1;
5382                                         goto err;
5383                                 }
5384                         }
5385                         param.fp_exclude_gid = !!neg_opt;
5386                         param.fp_check_gid = 1;
5387                         break;
5388                 case 'H':
5389                         rc = mdthash_input(optarg, &param.fp_hash_inflags,
5390                                            &param.fp_hash_exflags,
5391                                            &param.fp_hash_type);
5392                         if (rc) {
5393                                 ret = -1;
5394                                 goto err;
5395                         }
5396                         if (param.fp_hash_inflags || param.fp_hash_exflags)
5397                                 param.fp_check_hash_flag = 1;
5398                         param.fp_exclude_hash_type = !!neg_opt;
5399                         break;
5400                 case 'l':
5401                         param.fp_lazy = 1;
5402                         break;
5403                 case 'L':
5404                         ret = name2layout(&param.fp_layout, optarg);
5405                         if (ret)
5406                                 goto err;
5407                         param.fp_exclude_layout = !!neg_opt;
5408                         param.fp_check_layout = 1;
5409                         break;
5410                 case 'u':
5411                 case 'U':
5412                         rc = name2uid(&param.fp_uid, optarg);
5413                         if (rc) {
5414                                 if (str2quotaid(&param.fp_uid, optarg)) {
5415                                         fprintf(stderr,
5416                                                 "User/UID: %s cannot be found.\n",
5417                                                 optarg);
5418                                         ret = -1;
5419                                         goto err;
5420                                 }
5421                         }
5422                         param.fp_exclude_uid = !!neg_opt;
5423                         param.fp_check_uid = 1;
5424                         break;
5425                 case 'n':
5426                         param.fp_pattern = (char *)optarg;
5427                         param.fp_exclude_pattern = !!neg_opt;
5428                         break;
5429                 case 'N':
5430                         if (optarg[0] == '+') {
5431                                 param.fp_mirror_count_sign = -1;
5432                                 optarg++;
5433                         } else if (optarg[0] == '-') {
5434                                 param.fp_mirror_count_sign =  1;
5435                                 optarg++;
5436                         }
5437
5438                         errno = 0;
5439                         param.fp_mirror_count = strtoul(optarg, &endptr, 0);
5440                         if (errno != 0 || *endptr != '\0' ||
5441                             param.fp_mirror_count > LUSTRE_MIRROR_COUNT_MAX) {
5442                                 fprintf(stderr,
5443                                         "error: bad mirror count '%s'\n",
5444                                         optarg);
5445                                 goto err;
5446                         }
5447                         param.fp_check_mirror_count = 1;
5448                         param.fp_exclude_mirror_count = !!neg_opt;
5449                         break;
5450                 case 'm':
5451                 case 'i':
5452                 case 'O': {
5453                         char *buf, *token, *next, *p;
5454                         int len = 1;
5455                         void *tmp;
5456
5457                         buf = strdup(optarg);
5458                         if (!buf) {
5459                                 ret = -ENOMEM;
5460                                 goto err;
5461                         }
5462
5463                         param.fp_exclude_obd = !!neg_opt;
5464
5465                         token = buf;
5466                         while (token && *token) {
5467                                 token = strchr(token, ',');
5468                                 if (token) {
5469                                         len++;
5470                                         token++;
5471                                 }
5472                         }
5473                         if (c == 'm') {
5474                                 param.fp_exclude_mdt = !!neg_opt;
5475                                 param.fp_num_alloc_mdts += len;
5476                                 tmp = realloc(param.fp_mdt_uuid,
5477                                               param.fp_num_alloc_mdts *
5478                                               sizeof(*param.fp_mdt_uuid));
5479                                 if (!tmp) {
5480                                         ret = -ENOMEM;
5481                                         goto err_free;
5482                                 }
5483
5484                                 param.fp_mdt_uuid = tmp;
5485                         } else {
5486                                 param.fp_exclude_obd = !!neg_opt;
5487                                 param.fp_num_alloc_obds += len;
5488                                 tmp = realloc(param.fp_obd_uuid,
5489                                               param.fp_num_alloc_obds *
5490                                               sizeof(*param.fp_obd_uuid));
5491                                 if (!tmp) {
5492                                         ret = -ENOMEM;
5493                                         goto err_free;
5494                                 }
5495
5496                                 param.fp_obd_uuid = tmp;
5497                         }
5498                         for (token = buf; token && *token; token = next) {
5499                                 struct obd_uuid *puuid;
5500
5501                                 if (c == 'm') {
5502                                         puuid =
5503                                         &param.fp_mdt_uuid[param.fp_num_mdts++];
5504                                 } else {
5505                                         puuid =
5506                                         &param.fp_obd_uuid[param.fp_num_obds++];
5507                                 }
5508                                 p = strchr(token, ',');
5509                                 next = 0;
5510                                 if (p) {
5511                                         *p = 0;
5512                                         next = p+1;
5513                                 }
5514
5515                                 if (strlen(token) > sizeof(puuid->uuid) - 1) {
5516                                         ret = -E2BIG;
5517                                         goto err_free;
5518                                 }
5519
5520                                 strncpy(puuid->uuid, token,
5521                                         sizeof(puuid->uuid));
5522                         }
5523 err_free:
5524                         if (buf)
5525                                 free(buf);
5526                         break;
5527                 }
5528 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 18, 53, 0)
5529                 case 'p':
5530 #endif
5531                 case LFS_POOL_OPT:
5532                         if (strlen(optarg) > LOV_MAXPOOLNAME) {
5533                                 fprintf(stderr,
5534                                         "Pool name %s is too long (max %d)\n",
5535                                         optarg, LOV_MAXPOOLNAME);
5536                                 ret = -1;
5537                                 goto err;
5538                         }
5539                         /*
5540                          * We do check for empty pool because empty pool
5541                          * is used to find V1 LOV attributes
5542                          */
5543                         strncpy(param.fp_poolname, optarg, LOV_MAXPOOLNAME);
5544                         param.fp_poolname[LOV_MAXPOOLNAME] = '\0';
5545                         param.fp_exclude_pool = !!neg_opt;
5546                         param.fp_check_pool = 1;
5547                         break;
5548 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 14, 53, 0)
5549                 case 'p': /* want this for --pool, to match getstripe/find */
5550                         fprintf(stderr,
5551                                 "warning: -p deprecated, use --print0 or -0\n");
5552 #endif
5553                 case '0':
5554                         param.fp_zero_end = 1;
5555                         break;
5556                 case 'P': /* we always print, this option is a no-op */
5557                         break;
5558                 case LFS_PROJID_OPT:
5559                         rc = name2projid(&param.fp_projid, optarg);
5560                         if (rc) {
5561                                 if (str2quotaid(&param.fp_projid, optarg)) {
5562                                         fprintf(stderr,
5563                                                 "Invalid project ID: %s\n",
5564                                                 optarg);
5565                                         ret = -1;
5566                                         goto err;
5567                                 }
5568                         }
5569                         param.fp_exclude_projid = !!neg_opt;
5570                         param.fp_check_projid = 1;
5571                         break;
5572                 case 's':
5573                         if (optarg[0] == '+') {
5574                                 param.fp_size_sign = -1;
5575                                 optarg++;
5576                         } else if (optarg[0] == '-') {
5577                                 param.fp_size_sign =  1;
5578                                 optarg++;
5579                         }
5580
5581                         ret = llapi_parse_size(optarg, &param.fp_size,
5582                                                &param.fp_size_units, 0);
5583                         if (ret) {
5584                                 fprintf(stderr, "error: bad file size '%s'\n",
5585                                         optarg);
5586                                 goto err;
5587                         }
5588                         param.fp_check_size = 1;
5589                         param.fp_exclude_size = !!neg_opt;
5590                         break;
5591                 case 'S':
5592                         if (optarg[0] == '+') {
5593                                 param.fp_stripe_size_sign = -1;
5594                                 optarg++;
5595                         } else if (optarg[0] == '-') {
5596                                 param.fp_stripe_size_sign =  1;
5597                                 optarg++;
5598                         }
5599
5600                         ret = llapi_parse_size(optarg, &param.fp_stripe_size,
5601                                                &param.fp_stripe_size_units, 0);
5602                         /* assume units of KB if too small to be valid */
5603                         if (param.fp_stripe_size < 4096)
5604                                 param.fp_stripe_size *= 1024;
5605                         if (ret) {
5606                                 fprintf(stderr, "error: bad stripe_size '%s'\n",
5607                                         optarg);
5608                                 goto err;
5609                         }
5610                         param.fp_check_stripe_size = 1;
5611                         param.fp_exclude_stripe_size = !!neg_opt;
5612                         break;
5613                 case 't':
5614                         param.fp_exclude_type = !!neg_opt;
5615                         switch (optarg[0]) {
5616                         case 'b':
5617                                 param.fp_type = S_IFBLK;
5618                                 break;
5619                         case 'c':
5620                                 param.fp_type = S_IFCHR;
5621                                 break;
5622                         case 'd':
5623                                 param.fp_type = S_IFDIR;
5624                                 break;
5625                         case 'f':
5626                                 param.fp_type = S_IFREG;
5627                                 break;
5628                         case 'l':
5629                                 param.fp_type = S_IFLNK;
5630                                 break;
5631                         case 'p':
5632                                 param.fp_type = S_IFIFO;
5633                                 break;
5634                         case 's':
5635                                 param.fp_type = S_IFSOCK;
5636                                 break;
5637                         default:
5638                                 fprintf(stderr, "%s: bad type '%s'\n",
5639                                         progname, optarg);
5640                                 ret = CMD_HELP;
5641                                 goto err;
5642                         }
5643                         break;
5644                 case LFS_FIND_PERM:
5645                         param.fp_exclude_perm = !!neg_opt;
5646                         param.fp_perm_sign = LFS_FIND_PERM_EXACT;
5647                         if (*optarg == '/') {
5648                                 param.fp_perm_sign = LFS_FIND_PERM_ANY;
5649                                 optarg++;
5650                         } else if (*optarg == '-') {
5651                                 param.fp_perm_sign = LFS_FIND_PERM_ALL;
5652                                 optarg++;
5653                         }
5654
5655                         if (str2mode_t(optarg, &param.fp_perm)) {
5656                                 fprintf(stderr, "error: invalid mode '%s'\n",
5657                                         optarg);
5658                                 ret = -1;
5659                                 goto err;
5660                         }
5661                         break;
5662                 case 'T':
5663                         if (optarg[0] == '+') {
5664                                 param.fp_mdt_count_sign = -1;
5665                                 optarg++;
5666                         } else if (optarg[0] == '-') {
5667                                 param.fp_mdt_count_sign =  1;
5668                                 optarg++;
5669                         }
5670
5671                         errno = 0;
5672                         param.fp_mdt_count = strtoul(optarg, &endptr, 0);
5673                         if (errno != 0 || *endptr != '\0' ||
5674                             param.fp_mdt_count >= UINT32_MAX) {
5675                                 fprintf(stderr, "error: bad mdt_count '%s'\n",
5676                                         optarg);
5677                                 ret = -1;
5678                                 goto err;
5679                         }
5680                         param.fp_check_mdt_count = 1;
5681                         param.fp_exclude_mdt_count = !!neg_opt;
5682                         break;
5683                 case 'z':
5684                         if (optarg[0] == '+') {
5685                                 param.fp_ext_size_sign = -1;
5686                                 optarg++;
5687                         } else if (optarg[0] == '-') {
5688                                 param.fp_ext_size_sign =  1;
5689                                 optarg++;
5690                         }
5691
5692                         ret = llapi_parse_size(optarg, &param.fp_ext_size,
5693                                                &param.fp_ext_size_units, 0);
5694                         if (ret) {
5695                                 fprintf(stderr, "error: bad ext-size '%s'\n",
5696                                         optarg);
5697                                 goto err;
5698                         }
5699                         param.fp_ext_size /= SEL_UNIT_SIZE;
5700                         param.fp_ext_size_units /= SEL_UNIT_SIZE;
5701                         param.fp_check_ext_size = 1;
5702                         param.fp_exclude_ext_size = !!neg_opt;
5703                         break;
5704                 default:
5705                         fprintf(stderr, "%s: unrecognized option '%s'\n",
5706                                 progname, argv[optind - 1]);
5707                 case 'h':
5708                         ret = CMD_HELP;
5709                         goto err;
5710                 }
5711         }
5712
5713         if (pathstart == -1) {
5714                 fprintf(stderr, "error: %s: no filename|pathname\n",
5715                         argv[0]);
5716                 ret = CMD_HELP;
5717                 goto err;
5718         } else if (pathend == -1) {
5719                 /* no options */
5720                 pathend = argc;
5721         }
5722
5723         do {
5724                 rc = llapi_find(argv[pathstart], &param);
5725                 if (rc && !ret) {
5726                         ret = rc;
5727                         pathbad = pathstart;
5728                 }
5729         } while (++pathstart < pathend);
5730
5731         if (ret)
5732                 fprintf(stderr, "%s: failed for '%s': %s\n",
5733                         progname, argv[pathbad], strerror(-rc));
5734
5735 err:
5736         if (param.fp_obd_uuid && param.fp_num_alloc_obds)
5737                 free(param.fp_obd_uuid);
5738
5739         if (param.fp_mdt_uuid && param.fp_num_alloc_mdts)
5740                 free(param.fp_mdt_uuid);
5741
5742         return ret;
5743 }
5744
5745 static int lfs_getstripe_internal(int argc, char **argv,
5746                                   struct find_param *param)
5747 {
5748         struct option long_opts[] = {
5749 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
5750 /* find { .val = 'b',   .name = "blocks",       .has_arg = required_argument }*/
5751 /* find { .val = 'B',   .name = "btime",        .has_arg = required_argument }*/
5752 /* find { .val = 'B',   .name = "Btime",        .has_arg = required_argument }*/
5753         { .val = LFS_COMP_COUNT_OPT,
5754                         .name = "comp-count",   .has_arg = no_argument },
5755         { .val = LFS_COMP_COUNT_OPT,
5756                 .name = "component-count",      .has_arg = no_argument },
5757         { .val = LFS_COMP_FLAGS_OPT,
5758                         .name = "comp-flags",   .has_arg = optional_argument },
5759         { .val = LFS_COMP_FLAGS_OPT,
5760                 .name = "component-flags",      .has_arg = optional_argument },
5761         { .val = LFS_COMP_START_OPT,
5762                         .name = "comp-start",   .has_arg = optional_argument },
5763         { .val = LFS_COMP_START_OPT,
5764                 .name = "component-start",      .has_arg = optional_argument },
5765         { .val = LFS_MIRROR_INDEX_OPT,
5766                 .name = "mirror-index",         .has_arg = required_argument },
5767         { .val = LFS_MIRROR_ID_OPT,
5768                 .name = "mirror-id",            .has_arg = required_argument },
5769         { .val = 'c',   .name = "stripe-count", .has_arg = no_argument },
5770         { .val = 'c',   .name = "stripe_count", .has_arg = no_argument },
5771 /* find { .val = 'C',   .name = "ctime",        .has_arg = required_argument }*/
5772         { .val = 'd',   .name = "directory",    .has_arg = no_argument },
5773         { .val = 'D',   .name = "default",      .has_arg = no_argument },
5774         { .val = 'E',   .name = "comp-end",     .has_arg = optional_argument },
5775         { .val = 'E',   .name = "component-end", .has_arg = optional_argument },
5776         { .val = 'F',   .name = "fid",          .has_arg = no_argument },
5777         { .val = 'g',   .name = "generation",   .has_arg = no_argument },
5778 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
5779         { .val = 'h',   .name = "help",         .has_arg = no_argument },
5780 /* dirstripe { .val = 'H', .name = "mdt-hash",  .has_arg = required_argument }*/
5781         { .val = 'i',   .name = "stripe-index", .has_arg = no_argument },
5782         { .val = 'i',   .name = "stripe_index", .has_arg = no_argument },
5783         { .val = 'I',   .name = "comp-id",      .has_arg = optional_argument },
5784         { .val = 'I',   .name = "component-id", .has_arg = optional_argument },
5785 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
5786         { .val = 'L',   .name = "layout",       .has_arg = no_argument },
5787         { .val = 'm',   .name = "mdt",          .has_arg = no_argument },
5788         { .val = 'm',   .name = "mdt-index",    .has_arg = no_argument },
5789         { .val = 'm',   .name = "mdt_index",    .has_arg = no_argument },
5790 /* find { .val = 'M',   .name = "mtime",        .has_arg = required_argument }*/
5791 /* find { .val = 'n',   .name = "name",         .has_arg = required_argument }*/
5792         { .val = 'N',   .name = "mirror-count", .has_arg = no_argument },
5793         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
5794         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
5795         { .val = 'p',   .name = "pool",         .has_arg = no_argument },
5796 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
5797         { .val = 'q',   .name = "quiet",        .has_arg = no_argument },
5798         { .val = 'r',   .name = "recursive",    .has_arg = no_argument },
5799         { .val = 'R',   .name = "raw",          .has_arg = no_argument },
5800         { .val = 'S',   .name = "stripe-size",  .has_arg = no_argument },
5801         { .val = 'S',   .name = "stripe_size",  .has_arg = no_argument },
5802 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
5803 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
5804 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
5805 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
5806         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
5807 /* dirstripe { .val = 'X',.name = "max-inherit",.has_arg = required_argument }*/
5808         { .val = 'y',   .name = "yaml",         .has_arg = no_argument },
5809         { .val = 'z',   .name = "extension-size", .has_arg = no_argument },
5810         { .val = 'z',   .name = "ext-size",     .has_arg = no_argument },
5811         { .name = NULL } };
5812         int c, rc;
5813         int neg_opt = 0;
5814         int pathstart = -1, pathend = -1;
5815         int isoption;
5816         char *end, *tmp;
5817
5818         while ((c = getopt_long(argc, argv,
5819                         "-cdDE::FghiI::LmMNoO:pqrRsSvyz",
5820                         long_opts, NULL)) != -1) {
5821                 if (neg_opt)
5822                         --neg_opt;
5823
5824                 /* '!' is part of option */
5825                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
5826                 if (!isoption && pathend != -1) {
5827                         fprintf(stderr,
5828                                 "error: %s: filename|dirname must either precede options or follow options\n",
5829                                 argv[0]);
5830                         return CMD_HELP;
5831                 }
5832                 if (!isoption && pathstart == -1)
5833                         pathstart = optind - 1;
5834                 if (isoption && pathstart != -1 && pathend == -1)
5835                         pathend = optind - 2;
5836
5837                 switch (c) {
5838                 case 1:
5839                         /* unknown: opt is "!" */
5840                         if (strcmp(optarg, "!") == 0)
5841                                 neg_opt = 2;
5842                         break;
5843                 case 'c':
5844                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
5845                                 param->fp_verbose |= VERBOSE_COUNT;
5846                                 param->fp_max_depth = 0;
5847                         }
5848                         break;
5849                 case LFS_COMP_COUNT_OPT:
5850                         param->fp_verbose |= VERBOSE_COMP_COUNT;
5851                         param->fp_max_depth = 0;
5852                         break;
5853                 case LFS_COMP_FLAGS_OPT:
5854                         if (optarg) {
5855                                 rc = comp_str2flags(optarg,
5856                                                     &param->fp_comp_flags,
5857                                                     &param->fp_comp_neg_flags);
5858                                 if (rc != 0) {
5859                                         fprintf(stderr,
5860                                                 "error: %s bad component flags '%s'.\n",
5861                                                 argv[0], optarg);
5862                                         return CMD_HELP;
5863                                 }
5864                                 param->fp_check_comp_flags = 1;
5865                         } else {
5866                                 param->fp_verbose |= VERBOSE_COMP_FLAGS;
5867                                 param->fp_max_depth = 0;
5868                         }
5869                         break;
5870                 case LFS_COMP_START_OPT:
5871                         if (optarg) {
5872                                 tmp = optarg;
5873                                 if (tmp[0] == '+') {
5874                                         param->fp_comp_start_sign = -1;
5875                                         tmp++;
5876                                 } else if (tmp[0] == '-') {
5877                                         param->fp_comp_start_sign = 1;
5878                                         tmp++;
5879                                 }
5880                                 rc = llapi_parse_size(tmp,
5881                                                 &param->fp_comp_start,
5882                                                 &param->fp_comp_start_units, 0);
5883                                 if (rc != 0) {
5884                                         fprintf(stderr,
5885                                                 "error: %s bad component start '%s'.\n",
5886                                                 argv[0], tmp);
5887                                         return CMD_HELP;
5888                                 }
5889                                 param->fp_check_comp_start = 1;
5890                         } else {
5891                                 param->fp_verbose |= VERBOSE_COMP_START;
5892                                 param->fp_max_depth = 0;
5893                         }
5894                         break;
5895                 case LFS_MIRROR_INDEX_OPT: {
5896                         unsigned long int mirror_index;
5897
5898                         if (optarg[0] == '+') {
5899                                 param->fp_mirror_index_sign = -1;
5900                                 optarg++;
5901                         } else if (optarg[0] == '-') {
5902                                 param->fp_mirror_index_sign = 1;
5903                                 optarg++;
5904                         }
5905
5906                         errno = 0;
5907                         mirror_index = strtoul(optarg, &end, 0);
5908                         if (errno != 0 || *end != '\0' ||
5909                             mirror_index > UINT16_MAX || (mirror_index == 0 &&
5910                             param->fp_mirror_index_sign == 0 && neg_opt == 0)) {
5911                                 fprintf(stderr,
5912                                         "%s %s: invalid mirror index '%s'\n",
5913                                         progname, argv[0], optarg);
5914                                 return CMD_HELP;
5915                         }
5916
5917                         param->fp_mirror_index = (__u16)mirror_index;
5918
5919                         if (param->fp_mirror_id != 0) {
5920                                 fprintf(stderr,
5921                                         "%s %s: can't specify both mirror index and mirror ID\n",
5922                                         progname, argv[0]);
5923                                 return CMD_HELP;
5924                         }
5925                         param->fp_check_mirror_index = 1;
5926                         param->fp_exclude_mirror_index = !!neg_opt;
5927                         break;
5928                 }
5929                 case LFS_MIRROR_ID_OPT: {
5930                         unsigned long int mirror_id;
5931
5932                         if (optarg[0] == '+') {
5933                                 param->fp_mirror_id_sign = -1;
5934                                 optarg++;
5935                         } else if (optarg[0] == '-') {
5936                                 param->fp_mirror_id_sign = 1;
5937                                 optarg++;
5938                         }
5939
5940                         errno = 0;
5941                         mirror_id = strtoul(optarg, &end, 0);
5942                         if (errno != 0 || *end != '\0' ||
5943                             mirror_id > UINT16_MAX || (mirror_id == 0 &&
5944                             param->fp_mirror_id_sign == 0 && neg_opt == 0)) {
5945                                 fprintf(stderr,
5946                                         "%s %s: invalid mirror ID '%s'\n",
5947                                         progname, argv[0], optarg);
5948                                 return CMD_HELP;
5949                         }
5950
5951                         param->fp_mirror_id = (__u16)mirror_id;
5952
5953                         if (param->fp_mirror_index != 0) {
5954                                 fprintf(stderr,
5955                                         "%s %s: can't specify both mirror index and mirror ID\n",
5956                                         progname, argv[0]);
5957                                 return CMD_HELP;
5958                         }
5959                         param->fp_check_mirror_id = 1;
5960                         param->fp_exclude_mirror_id = !!neg_opt;
5961                         break;
5962                 }
5963                 case 'd':
5964                         param->fp_max_depth = 0;
5965                         break;
5966                 case 'D':
5967                         param->fp_get_default_lmv = 1;
5968                         break;
5969                 case 'E':
5970                         if (optarg) {
5971                                 tmp = optarg;
5972                                 if (tmp[0] == '+') {
5973                                         param->fp_comp_end_sign = -1;
5974                                         tmp++;
5975                                 } else if (tmp[0] == '-') {
5976                                         param->fp_comp_end_sign = 1;
5977                                         tmp++;
5978                                 }
5979
5980                                 if (arg_is_eof(tmp)) {
5981                                         param->fp_comp_end = LUSTRE_EOF;
5982                                         param->fp_comp_end_units = 1;
5983                                         rc = 0;
5984                                 } else {
5985                                         rc = llapi_parse_size(tmp,
5986                                                 &param->fp_comp_end,
5987                                                 &param->fp_comp_end_units, 0);
5988                                         /* assume units of KB if too small */
5989                                         if (param->fp_comp_end < 4096)
5990                                                 param->fp_comp_end *= 1024;
5991                                 }
5992                                 if (rc != 0) {
5993                                         fprintf(stderr,
5994                                                 "error: %s bad component end '%s'.\n",
5995                                                 argv[0], tmp);
5996                                         return CMD_HELP;
5997                                 }
5998                                 param->fp_check_comp_end = 1;
5999                         } else {
6000                                 param->fp_verbose |= VERBOSE_COMP_END;
6001                                 param->fp_max_depth = 0;
6002                         }
6003                         break;
6004                 case 'F':
6005                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6006                                 param->fp_verbose |= VERBOSE_DFID;
6007                                 param->fp_max_depth = 0;
6008                         }
6009                         break;
6010                 case 'g':
6011                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6012                                 param->fp_verbose |= VERBOSE_GENERATION;
6013                                 param->fp_max_depth = 0;
6014                         }
6015                         break;
6016                 case 'i':
6017                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6018                                 param->fp_verbose |= VERBOSE_STRIPE_OFFSET;
6019                                 param->fp_max_depth = 0;
6020                         }
6021                         break;
6022                 case 'I':
6023                         if (optarg) {
6024                                 param->fp_comp_id = strtoul(optarg, &end, 0);
6025                                 if (*end != '\0' || param->fp_comp_id == 0 ||
6026                                     param->fp_comp_id > LCME_ID_MAX) {
6027                                         fprintf(stderr,
6028                                                 "error: %s bad component id '%s'\n",
6029                                                 argv[0], optarg);
6030                                         return CMD_HELP;
6031                                 }
6032                                 param->fp_check_comp_id = 1;
6033                         } else {
6034                                 param->fp_max_depth = 0;
6035                                 param->fp_verbose |= VERBOSE_COMP_ID;
6036                         }
6037                         break;
6038                 case 'L':
6039                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6040                                 param->fp_verbose |= VERBOSE_PATTERN;
6041                                 param->fp_max_depth = 0;
6042                         }
6043                         break;
6044 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6045                 case 'M':
6046                         fprintf(stderr,
6047                                 "warning: '-M' deprecated, use '--mdt-index' or '-m' instead\n");
6048 #endif
6049                 case 'm':
6050                         if (!(param->fp_verbose & VERBOSE_DETAIL))
6051                                 param->fp_max_depth = 0;
6052                         param->fp_verbose |= VERBOSE_MDTINDEX;
6053                         break;
6054                 case 'N':
6055                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6056                                 param->fp_verbose |= VERBOSE_MIRROR_COUNT;
6057                                 param->fp_max_depth = 0;
6058                         }
6059                         break;
6060                 case 'O':
6061                         if (param->fp_obd_uuid) {
6062                                 fprintf(stderr,
6063                                         "error: %s: only one obduuid allowed",
6064                                         argv[0]);
6065                                 return CMD_HELP;
6066                         }
6067                         param->fp_obd_uuid = (struct obd_uuid *)optarg;
6068                         break;
6069                 case 'p':
6070                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6071                                 param->fp_verbose |= VERBOSE_POOL;
6072                                 param->fp_max_depth = 0;
6073                         }
6074                         break;
6075                 case 'q':
6076                         param->fp_quiet++;
6077                         break;
6078                 case 'r':
6079                         param->fp_recursive = 1;
6080                         break;
6081                 case 'R':
6082                         param->fp_raw = 1;
6083                         break;
6084                 case 'S':
6085                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6086                                 param->fp_verbose |= VERBOSE_STRIPE_SIZE;
6087                                 param->fp_max_depth = 0;
6088                         }
6089                         break;
6090                 case 'v':
6091                         param->fp_verbose = VERBOSE_DEFAULT | VERBOSE_DETAIL;
6092                         break;
6093                 case 'y':
6094                         param->fp_yaml = 1;
6095                         break;
6096                 case 'z':
6097                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6098                                 param->fp_verbose |= VERBOSE_EXT_SIZE;
6099                                 param->fp_max_depth = 0;
6100                         }
6101                         break;
6102                 default:
6103                         fprintf(stderr, "%s: unrecognized option '%s'\n",
6104                                 progname, argv[optind - 1]);
6105                 case 'h':
6106                         return CMD_HELP;
6107                 }
6108         }
6109
6110         if (pathstart == -1) {
6111                 fprintf(stderr, "error: %s: no filename|pathname\n",
6112                                 argv[0]);
6113                 return CMD_HELP;
6114         } else if (pathend == -1) {
6115                 /* no options */
6116                 pathend = argc;
6117         }
6118
6119         if (pathend > argc)
6120                 return CMD_HELP;
6121
6122         if (param->fp_recursive)
6123                 param->fp_max_depth = -1;
6124         else if (param->fp_verbose & VERBOSE_DETAIL)
6125                 param->fp_max_depth = 1;
6126
6127         if (!param->fp_verbose)
6128                 param->fp_verbose = VERBOSE_DEFAULT;
6129         if (param->fp_quiet)
6130                 param->fp_verbose = VERBOSE_OBJID;
6131
6132         do {
6133                 rc = llapi_getstripe(argv[pathstart], param);
6134         } while (++pathstart < pathend && !rc);
6135
6136         if (rc)
6137                 fprintf(stderr, "error: %s failed for %s.\n",
6138                         argv[0], argv[optind - 1]);
6139         return rc;
6140 }
6141
6142 static int lfs_tgts(int argc, char **argv)
6143 {
6144         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
6145         struct find_param param;
6146         int index = 0, rc = 0;
6147
6148         if (argc > 2)
6149                 return CMD_HELP;
6150
6151         if (argc == 2 && !realpath(argv[1], path)) {
6152                 rc = -errno;
6153                 fprintf(stderr, "error: invalid path '%s': %s\n",
6154                         argv[1], strerror(-rc));
6155                 return rc;
6156         }
6157
6158         while (!llapi_search_mounts(path, index++, mntdir, NULL)) {
6159                 /* Check if we have a mount point */
6160                 if (mntdir[0] == '\0')
6161                         continue;
6162
6163                 memset(&param, 0, sizeof(param));
6164                 if (!strcmp(argv[0], "mdts"))
6165                         param.fp_get_lmv = 1;
6166
6167                 rc = llapi_ostlist(mntdir, &param);
6168                 if (rc) {
6169                         fprintf(stderr, "error: %s: failed on %s\n",
6170                                 argv[0], mntdir);
6171                 }
6172                 if (path[0] != '\0')
6173                         break;
6174                 memset(mntdir, 0, PATH_MAX);
6175         }
6176
6177         return rc;
6178 }
6179
6180 static int lfs_getstripe(int argc, char **argv)
6181 {
6182         struct find_param param = { 0 };
6183
6184         param.fp_max_depth = 1;
6185         return lfs_getstripe_internal(argc, argv, &param);
6186 }
6187
6188 /* functions */
6189 static int lfs_getdirstripe(int argc, char **argv)
6190 {
6191         struct find_param param = { 0 };
6192         struct option long_opts[] = {
6193         { .val = 'c',   .name = "mdt-count",     .has_arg = no_argument },
6194         { .val = 'D',   .name = "default",       .has_arg = no_argument },
6195         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6196         { .val = 'H',   .name = "mdt-hash",      .has_arg = no_argument },
6197         { .val = 'i',   .name = "mdt-index",     .has_arg = no_argument },
6198         { .val = 'm',   .name = "mdt-index",     .has_arg = no_argument },
6199         { .val = 'O',   .name = "obd",           .has_arg = required_argument },
6200         { .val = 'r',   .name = "recursive",     .has_arg = no_argument },
6201         { .val = 'T',   .name = "mdt-count",     .has_arg = no_argument },
6202         { .val = 'v',   .name = "verbose",       .has_arg = no_argument },
6203         { .val = 'X',   .name = "max-inherit",   .has_arg = no_argument },
6204         { .val = 'y',   .name = "yaml",          .has_arg = no_argument },
6205         { .val = LFS_INHERIT_RR_OPT,
6206                         .name = "max-inherit-rr", .has_arg = no_argument },
6207         { .name = NULL } };
6208         int c, rc;
6209
6210         param.fp_get_lmv = 1;
6211
6212         while ((c = getopt_long(argc, argv,
6213                                 "cDhHimO:rtTvXy", long_opts, NULL)) != -1) {
6214                 switch (c) {
6215                 case 'c':
6216                 case 'T':
6217                         param.fp_verbose |= VERBOSE_COUNT;
6218                         break;
6219                 case 'D':
6220                         param.fp_get_default_lmv = 1;
6221                         break;
6222 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6223                 case 't':
6224                         fprintf(stderr,
6225                                 "warning: '-t' deprecated, use '--mdt-hash' or '-H' instead\n");
6226                         /* fallthrough */
6227 #endif
6228                 case 'H':
6229                         param.fp_verbose |= VERBOSE_HASH_TYPE;
6230                         break;
6231                 case 'i': /* fallthrough */
6232                 case 'm':
6233                         param.fp_verbose |= VERBOSE_STRIPE_OFFSET;
6234                         break;
6235                 case 'O':
6236                         if (param.fp_obd_uuid) {
6237                                 fprintf(stderr,
6238                                         "%s: only one obduuid allowed",
6239                                         progname);
6240                                 return CMD_HELP;
6241                         }
6242                         param.fp_obd_uuid = (struct obd_uuid *)optarg;
6243                         break;
6244                 case 'r':
6245                         param.fp_recursive = 1;
6246                         break;
6247                 case 'v':
6248                         param.fp_verbose |= VERBOSE_DETAIL;
6249                         break;
6250                 case 'X':
6251                         param.fp_verbose |= VERBOSE_INHERIT;
6252                         break;
6253                 case LFS_INHERIT_RR_OPT:
6254                         param.fp_verbose |= VERBOSE_INHERIT_RR;
6255                         break;
6256                 case 'y':
6257                         param.fp_yaml = 1;
6258                         break;
6259                 default:
6260                         fprintf(stderr, "%s: unrecognized option '%s'\n",
6261                                 progname, argv[optind - 1]);
6262                         /* fallthrough */
6263                 case 'h':
6264                         return CMD_HELP;
6265                 }
6266         }
6267
6268         if (optind >= argc)
6269                 return CMD_HELP;
6270
6271         if (param.fp_recursive)
6272                 param.fp_max_depth = -1;
6273
6274         if (!param.fp_verbose)
6275                 param.fp_verbose = VERBOSE_DEFAULT;
6276
6277         do {
6278                 rc = llapi_getstripe(argv[optind], &param);
6279         } while (++optind < argc && !rc);
6280
6281         if (rc)
6282                 fprintf(stderr, "error: %s failed for %s.\n",
6283                         argv[0], argv[optind - 1]);
6284         return rc;
6285 }
6286
6287 enum mntdf_flags {
6288         MNTDF_INODES    = 0x0001,
6289         MNTDF_COOKED    = 0x0002,
6290         MNTDF_LAZY      = 0x0004,
6291         MNTDF_VERBOSE   = 0x0008,
6292         MNTDF_SHOW      = 0x0010,
6293         MNTDF_DECIMAL   = 0x0020,
6294 };
6295
6296 #define COOK(value, base)                                       \
6297 ({                                                              \
6298         int radix = 0;                                          \
6299         while (value > base) {                                  \
6300                 value /= base;                                  \
6301                 radix++;                                        \
6302         }                                                       \
6303         radix;                                                  \
6304 })
6305 #define UUF     "%-20s"
6306 #define CSF     "%11s"
6307 #define CDF     "%11llu"
6308 #define HDF     "%8.1f%c"
6309 #define RSF     "%4s"
6310 #define RDF     "%3d%%"
6311
6312 static inline int obd_statfs_ratio(const struct obd_statfs *st, bool inodes)
6313 {
6314         double avail, used, ratio = 0;
6315
6316         if (inodes) {
6317                 avail = st->os_ffree;
6318                 used = st->os_files - st->os_ffree;
6319         } else {
6320                 avail = st->os_bavail;
6321                 used = st->os_blocks - st->os_bfree;
6322         }
6323         if (avail + used > 0)
6324                 ratio = used / (used + avail) * 100;
6325
6326         /* Round up to match df(1) usage percentage */
6327         return (ratio - (int)ratio) > 0 ? (int)(ratio + 1) : (int)ratio;
6328 }
6329
6330 /*
6331  * This is to identify various problem states for "lfs df" if .osn_err = true,
6332  * so only show flags reflecting those states by default. Informational states
6333  * are only shown with "-v" and use lower-case names to distinguish them.
6334  * UNUSED[12] were for "EROFS = 30" until 1.6 but are now available for use.
6335  */
6336 static struct obd_statfs_state_names {
6337         enum obd_statfs_state   osn_state;
6338         const char              osn_name;
6339         bool                    osn_err;
6340 } oss_names[] = {
6341         { .osn_state = OS_STATFS_DEGRADED,   .osn_name = 'D', .osn_err = true },
6342         { .osn_state = OS_STATFS_READONLY,   .osn_name = 'R', .osn_err = true },
6343         { .osn_state = OS_STATFS_NOPRECREATE,.osn_name = 'N', .osn_err = true },
6344         { .osn_state = OS_STATFS_UNUSED1,    .osn_name = '?', .osn_err = true },
6345         { .osn_state = OS_STATFS_UNUSED2,    .osn_name = '?', .osn_err = true },
6346         { .osn_state = OS_STATFS_ENOSPC,     .osn_name = 'S', .osn_err = true },
6347         { .osn_state = OS_STATFS_ENOINO,     .osn_name = 'I', .osn_err = true },
6348         { .osn_state = OS_STATFS_SUM,        .osn_name = 'a', /* aggregate */ },
6349         { .osn_state = OS_STATFS_NONROT,     .osn_name = 'f', /* flash */     },
6350 };
6351
6352 static int showdf(char *mntdir, struct obd_statfs *stat,
6353                   char *uuid, enum mntdf_flags flags,
6354                   char *type, int index, int rc)
6355 {
6356         long long avail, used, total;
6357         int ratio = 0;
6358         char *suffix = flags & MNTDF_DECIMAL ? "kMGTPEZY" : "KMGTPEZY";
6359         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
6360         char tbuf[3 * sizeof(__u64)];
6361         char ubuf[3 * sizeof(__u64)];
6362         char abuf[3 * sizeof(__u64)];
6363         char rbuf[3 * sizeof(__u64)];
6364
6365         if (!uuid || !stat)
6366                 return -EINVAL;
6367
6368         switch (rc) {
6369         case 0:
6370                 if (flags & MNTDF_INODES) {
6371                         avail = stat->os_ffree;
6372                         used = stat->os_files - stat->os_ffree;
6373                         total = stat->os_files;
6374                 } else {
6375                         int shift = flags & MNTDF_COOKED ? 0 : 10;
6376
6377                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
6378                         used  = ((stat->os_blocks - stat->os_bfree) *
6379                                  stat->os_bsize) >> shift;
6380                         total = (stat->os_blocks * stat->os_bsize) >> shift;
6381                 }
6382
6383                 ratio = obd_statfs_ratio(stat, flags & MNTDF_INODES);
6384
6385                 if (flags & MNTDF_COOKED) {
6386                         int base = flags & MNTDF_DECIMAL ? 1000 : 1024;
6387                         double cook_val;
6388                         int i;
6389
6390                         cook_val = (double)total;
6391                         i = COOK(cook_val, base);
6392                         if (i > 0)
6393                                 snprintf(tbuf, sizeof(tbuf), HDF, cook_val,
6394                                          suffix[i - 1]);
6395                         else
6396                                 snprintf(tbuf, sizeof(tbuf), CDF, total);
6397
6398                         cook_val = (double)used;
6399                         i = COOK(cook_val, base);
6400                         if (i > 0)
6401                                 snprintf(ubuf, sizeof(ubuf), HDF, cook_val,
6402                                          suffix[i - 1]);
6403                         else
6404                                 snprintf(ubuf, sizeof(ubuf), CDF, used);
6405
6406                         cook_val = (double)avail;
6407                         i = COOK(cook_val, base);
6408                         if (i > 0)
6409                                 snprintf(abuf, sizeof(abuf), HDF, cook_val,
6410                                          suffix[i - 1]);
6411                         else
6412                                 snprintf(abuf, sizeof(abuf), CDF, avail);
6413                 } else {
6414                         snprintf(tbuf, sizeof(tbuf), CDF, total);
6415                         snprintf(ubuf, sizeof(tbuf), CDF, used);
6416                         snprintf(abuf, sizeof(tbuf), CDF, avail);
6417                 }
6418
6419                 sprintf(rbuf, RDF, ratio);
6420                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
6421                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
6422                 if (type)
6423                         printf("[%s:%d]", type, index);
6424
6425                 if (stat->os_state) {
6426                         uint32_t i;
6427
6428                         printf(" ");
6429                         for (i = 0; i < ARRAY_SIZE(oss_names); i++) {
6430                                 if (oss_names[i].osn_state & stat->os_state &&
6431                                     (oss_names[i].osn_err ||
6432                                      flags & MNTDF_VERBOSE))
6433                                         printf("%c", oss_names[i].osn_name);
6434                         }
6435                 }
6436
6437                 printf("\n");
6438                 break;
6439         case -ENODATA:
6440                 printf(UUF": inactive device\n", uuid);
6441                 break;
6442         default:
6443                 printf(UUF": %s\n", uuid, strerror(-rc));
6444                 break;
6445         }
6446
6447         return 0;
6448 }
6449
6450 struct ll_stat_type {
6451         int   st_op;
6452         char *st_name;
6453 };
6454
6455 #define LL_STATFS_MAX   LOV_MAX_STRIPE_COUNT
6456
6457 struct ll_statfs_data {
6458         int                     sd_index;
6459         struct obd_statfs       sd_st;
6460 };
6461
6462 struct ll_statfs_buf {
6463         int                     sb_count;
6464         struct ll_statfs_data   sb_buf[LL_STATFS_MAX];
6465 };
6466
6467 static int mntdf(char *mntdir, char *fsname, char *pool, enum mntdf_flags flags,
6468                  int ops, struct ll_statfs_buf *lsb)
6469 {
6470         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
6471         struct obd_uuid uuid_buf;
6472         char *poolname = NULL;
6473         struct ll_stat_type types[] = {
6474                 { .st_op = LL_STATFS_LMV,       .st_name = "MDT" },
6475                 { .st_op = LL_STATFS_LOV,       .st_name = "OST" },
6476                 { .st_name = NULL } };
6477         struct ll_stat_type *tp;
6478         __u64 ost_files = 0;
6479         __u64 ost_ffree = 0;
6480         __u32 index;
6481         __u32 type;
6482         int fd;
6483         int rc = 0;
6484         int rc2;
6485
6486         if (pool) {
6487                 poolname = strchr(pool, '.');
6488                 if (poolname) {
6489                         if (strncmp(fsname, pool, strlen(fsname))) {
6490                                 fprintf(stderr, "filesystem name incorrect\n");
6491                                 return -ENODEV;
6492                         }
6493                         poolname++;
6494                 } else
6495                         poolname = pool;
6496         }
6497
6498         fd = open(mntdir, O_RDONLY);
6499         if (fd < 0) {
6500                 rc = -errno;
6501                 fprintf(stderr, "%s: cannot open '%s': %s\n", progname, mntdir,
6502                         strerror(errno));
6503                 return rc;
6504         }
6505
6506         if (flags & MNTDF_SHOW) {
6507                 if (flags & MNTDF_INODES)
6508                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
6509                                "UUID", "Inodes", "IUsed", "IFree",
6510                                "IUse%", "Mounted on");
6511                 else
6512                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
6513                                "UUID",
6514                                flags & MNTDF_COOKED ? "bytes" : "1K-blocks",
6515                                "Used", "Available", "Use%", "Mounted on");
6516         }
6517
6518         for (tp = types; tp->st_name != NULL; tp++) {
6519                 bool have_ost = false;
6520
6521                 if (!(tp->st_op & ops))
6522                         continue;
6523
6524                 for (index = 0; ; index++) {
6525                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
6526                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
6527                         type = flags & MNTDF_LAZY ?
6528                                 tp->st_op | LL_STATFS_NODELAY : tp->st_op;
6529                         rc2 = llapi_obd_fstatfs(fd, type, index,
6530                                                &stat_buf, &uuid_buf);
6531                         if (rc2 == -ENODEV)
6532                                 break;
6533                         if (rc2 == -EAGAIN)
6534                                 continue;
6535                         if (rc2 == -ENODATA) { /* Inactive device, OK. */
6536                                 if (!(flags & MNTDF_VERBOSE))
6537                                         continue;
6538                         } else if (rc2 < 0 && rc == 0) {
6539                                 rc = rc2;
6540                         }
6541
6542                         /*
6543                          * If we have OSTs then don't report MDT block counts.
6544                          * For MDT-only filesystems the expectation is that all
6545                          * layouts have a DoM component.  For filesystems with
6546                          * OSTs, files are not necessarily going to store data
6547                          * on MDTs, and MDT space is limited to a fraction of
6548                          * OST space, so don't include it in the summary.
6549                          */
6550                         if (tp->st_op == LL_STATFS_LOV && !have_ost) {
6551                                 have_ost = true;
6552                                 sum.os_blocks = 0;
6553                                 sum.os_bfree = 0;
6554                                 sum.os_bavail = 0;
6555                         }
6556
6557                         if (poolname && tp->st_op == LL_STATFS_LOV &&
6558                             llapi_search_ost(fsname, poolname,
6559                                              obd_uuid2str(&uuid_buf)) != 1)
6560                                 continue;
6561
6562                         /*
6563                          * the llapi_obd_fstatfs() call may have returned with
6564                          * an error, but if it filled in uuid_buf we will at
6565                          * lease use that to print out a message for that OBD.
6566                          * If we didn't get anything in the uuid_buf, then fill
6567                          * it in so that we can print an error message.
6568                          */
6569                         if (uuid_buf.uuid[0] == '\0')
6570                                 snprintf(uuid_buf.uuid, sizeof(uuid_buf.uuid),
6571                                          "%s%04x", tp->st_name, index);
6572                         if (!rc && lsb) {
6573                                 lsb->sb_buf[lsb->sb_count].sd_index = index;
6574                                 lsb->sb_buf[lsb->sb_count].sd_st = stat_buf;
6575                                 lsb->sb_count++;
6576                         }
6577                         if (flags & MNTDF_SHOW)
6578                                 showdf(mntdir, &stat_buf,
6579                                        obd_uuid2str(&uuid_buf), flags,
6580                                        tp->st_name, index, rc2);
6581
6582                         if (rc2)
6583                                 continue;
6584
6585                         if (tp->st_op == LL_STATFS_LMV) {
6586                                 sum.os_ffree += stat_buf.os_ffree;
6587                                 sum.os_files += stat_buf.os_files;
6588                         } else /* if (tp->st_op == LL_STATFS_LOV) */ {
6589                                 ost_files += stat_buf.os_files;
6590                                 ost_ffree += stat_buf.os_ffree;
6591                         }
6592                         sum.os_blocks += stat_buf.os_blocks *
6593                                          stat_buf.os_bsize;
6594                         sum.os_bfree  += stat_buf.os_bfree *
6595                                          stat_buf.os_bsize;
6596                         sum.os_bavail += stat_buf.os_bavail *
6597                                          stat_buf.os_bsize;
6598                 }
6599         }
6600
6601         close(fd);
6602
6603         /*
6604          * If we have _some_ OSTs, but don't have as many free objects on the
6605          * OST as inodes on the MDTs, reduce the reported number of inodes
6606          * to compensate, so that the "inodes in use" number is correct.
6607          * This should be kept in sync with ll_statfs_internal().
6608          */
6609         if (ost_files && ost_ffree < sum.os_ffree) {
6610                 sum.os_files = (sum.os_files - sum.os_ffree) + ost_ffree;
6611                 sum.os_ffree = ost_ffree;
6612         }
6613         if (flags & MNTDF_SHOW) {
6614                 printf("\n");
6615                 showdf(mntdir, &sum, "filesystem_summary:", flags, NULL, 0, 0);
6616                 printf("\n");
6617         }
6618
6619         return rc;
6620 }
6621
6622 enum {
6623         LAYOUT_INHERIT_UNSET    = -2,
6624 };
6625
6626 /* functions */
6627 static int lfs_setdirstripe(int argc, char **argv)
6628 {
6629         char *dname;
6630         struct lfs_setstripe_args lsa = { 0 };
6631         struct llapi_stripe_param *param = NULL;
6632         __u32 mdts[LMV_MAX_STRIPE_COUNT] = { 0 };
6633         char *end;
6634         int c;
6635         char *mode_opt = NULL;
6636         bool default_stripe = false;
6637         bool delete = false;
6638         bool foreign_mode = false;
6639         mode_t mode = S_IRWXU | S_IRWXG | S_IRWXO;
6640         mode_t previous_mode = 0;
6641         char *xattr = NULL;
6642         __u32 type = LU_FOREIGN_TYPE_SYMLINK, flags = 0;
6643         int max_inherit = LAYOUT_INHERIT_UNSET;
6644         int max_inherit_rr = LAYOUT_INHERIT_UNSET;
6645         struct option long_opts[] = {
6646         { .val = 'c',   .name = "count",        .has_arg = required_argument },
6647         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument },
6648         { .val = 'd',   .name = "delete",       .has_arg = no_argument },
6649         { .val = 'D',   .name = "default",      .has_arg = no_argument },
6650         { .val = 'D',   .name = "default_stripe", .has_arg = no_argument },
6651         { .val = LFS_LAYOUT_FLAGS_OPT,
6652                         .name = "flags",        .has_arg = required_argument },
6653         { .val = LFS_LAYOUT_FOREIGN_OPT,
6654                         .name = "foreign",      .has_arg = optional_argument},
6655         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6656         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
6657 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 17, 53, 0)
6658         { .val = 'i',   .name = "mdt-index",    .has_arg = required_argument },
6659         { .val = 'i',   .name = "mdt",          .has_arg = required_argument },
6660 #else
6661 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
6662         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
6663         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
6664 #endif
6665 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6666         { .val = 'i',   .name = "index",        .has_arg = required_argument },
6667 #endif
6668         { .val = 'o',   .name = "mode",         .has_arg = required_argument },
6669 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6670         { .val = 't',   .name = "hash-type",    .has_arg = required_argument },
6671 #endif
6672         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
6673         { .val = 'x',   .name = "xattr",        .has_arg = required_argument },
6674         { .val = 'X',   .name = "max-inherit",  .has_arg = required_argument },
6675         { .val = LFS_INHERIT_RR_OPT,
6676                         .name = "max-inherit-rr", .has_arg = required_argument},
6677 /* setstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
6678         { .name = NULL } };
6679         int result = 0;
6680
6681         setstripe_args_init(&lsa);
6682
6683         while ((c = getopt_long(argc, argv, "c:dDi:hH:m:o:t:T:x:X:",
6684                                 long_opts, NULL)) >= 0) {
6685                 switch (c) {
6686                 case 0:
6687                         /* Long options. */
6688                         break;
6689                 case 'c':
6690                 case 'T':
6691                         errno = 0;
6692                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
6693                         if (errno != 0 || *end != '\0' ||
6694                             lsa.lsa_stripe_count < -1 ||
6695                             lsa.lsa_stripe_count > LOV_MAX_STRIPE_COUNT) {
6696                                 fprintf(stderr,
6697                                         "%s: invalid stripe count '%s'\n",
6698                                         progname, optarg);
6699                                 return CMD_HELP;
6700                         }
6701                         break;
6702                 case 'd':
6703                         delete = true;
6704                         default_stripe = true;
6705                         break;
6706                 case 'D':
6707                         default_stripe = true;
6708                         break;
6709                 case LFS_LAYOUT_FOREIGN_OPT:
6710                         if (optarg) {
6711                                 /* check pure numeric */
6712                                 type = strtoul(optarg, &end, 0);
6713                                 if (*end) {
6714                                         /* check name */
6715                                         type = check_foreign_type_name(optarg);
6716                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
6717                                                 fprintf(stderr,
6718                                                         "%s %s: unknown foreign type '%s'\n",
6719                                                         progname, argv[0],
6720                                                         optarg);
6721                                                 return CMD_HELP;
6722                                         }
6723                                 } else if (type >= UINT32_MAX) {
6724                                         fprintf(stderr,
6725                                                 "%s %s: invalid foreign type '%s'\n",
6726                                                 progname, argv[0], optarg);
6727                                         return CMD_HELP;
6728                                 }
6729                         }
6730                         foreign_mode = true;
6731                         break;
6732                 case LFS_LAYOUT_FLAGS_OPT:
6733                         errno = 0;
6734                         flags = strtoul(optarg, &end, 16);
6735                         if (errno != 0 || *end != '\0' ||
6736                             flags >= UINT32_MAX) {
6737                                 fprintf(stderr,
6738                                         "%s %s: invalid hex flags '%s'\n",
6739                                         progname, argv[0], optarg);
6740                                 return CMD_HELP;
6741                         }
6742                         if (!foreign_mode) {
6743                                 fprintf(stderr,
6744                                         "%s %s: hex flags must be specified with --foreign option\n",
6745                                         progname, argv[0]);
6746                                 return CMD_HELP;
6747                         }
6748                         break;
6749 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6750                 case 't':
6751                         fprintf(stderr,
6752                                 "warning: '--hash-type' and '-t' deprecated, use '--mdt-hash' or '-H' instead\n");
6753                         /* fallthrough */
6754 #endif
6755                 case 'H':
6756                         lsa.lsa_pattern = check_hashtype(optarg);
6757                         if (lsa.lsa_pattern == 0) {
6758                                 fprintf(stderr,
6759                                         "%s %s: bad stripe hash type '%s'\n",
6760                                         progname, argv[0], optarg);
6761                                 return CMD_HELP;
6762                         }
6763                         break;
6764                 case 'i':
6765 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 17, 53, 0)
6766                 case 'm':
6767 #endif
6768 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6769                         if (strcmp(argv[optind - 1], "--index") == 0)
6770                                 fprintf(stderr,
6771                                         "%s %s: warning: '--index' deprecated, use '--mdt-index' instead\n",
6772                                         progname, argv[0]);
6773 #endif
6774                         lsa.lsa_nr_tgts = parse_targets(mdts,
6775                                                 sizeof(mdts) / sizeof(__u32),
6776                                                 lsa.lsa_nr_tgts, optarg, NULL);
6777                         if (lsa.lsa_nr_tgts < 0) {
6778                                 fprintf(stderr,
6779                                         "%s %s: invalid MDT target(s) '%s'\n",
6780                                         progname, argv[0], optarg);
6781                                 return CMD_HELP;
6782                         }
6783
6784                         lsa.lsa_tgts = mdts;
6785                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
6786                                 lsa.lsa_stripe_off = mdts[0];
6787                         break;
6788 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 15, 53, 0)
6789                 case 'm':
6790                         fprintf(stderr,
6791                                 "warning: '-m' is deprecated, use '--mode' or '-o' instead\n");
6792 #endif
6793                 case 'o':
6794                         mode_opt = optarg;
6795                         break;
6796                 case 'x':
6797                         xattr = optarg;
6798                         break;
6799                 case 'X':
6800                         if (!default_stripe) {
6801                                 fprintf(stderr,
6802                                         "%s %s: '--max-inherit' must be specified with '-D'\n",
6803                                         progname, argv[0]);
6804                                 return CMD_HELP;
6805                         }
6806                         errno = 0;
6807                         max_inherit = strtol(optarg, &end, 10);
6808                         if (errno != 0 || *end != '\0' || max_inherit < -2) {
6809                                 fprintf(stderr,
6810                                         "%s %s: invalid max-inherit '%s'\n",
6811                                         progname, argv[0], optarg);
6812                                 return CMD_HELP;
6813                         }
6814                         if (max_inherit == 0) {
6815                                 max_inherit = LMV_INHERIT_NONE;
6816                         } else if (max_inherit == -1) {
6817                                 max_inherit = LMV_INHERIT_UNLIMITED;
6818                         } else if (max_inherit > LMV_INHERIT_MAX) {
6819                                 fprintf(stderr,
6820                                         "%s %s: max-inherit %d exceeds maximum %u\n",
6821                                         progname, argv[0], max_inherit,
6822                                         LMV_INHERIT_MAX);
6823                                 return CMD_HELP;
6824                         }
6825                         break;
6826                 case LFS_INHERIT_RR_OPT:
6827                         if (!default_stripe) {
6828                                 fprintf(stderr,
6829                                         "%s %s: '--max-inherit-rr' must be specified with '-D'\n",
6830                                         progname, argv[0]);
6831                                 return CMD_HELP;
6832                         }
6833                         errno = 0;
6834                         max_inherit_rr = strtol(optarg, &end, 10);
6835                         if (errno != 0 || *end != '\0' || max_inherit_rr < -2) {
6836                                 fprintf(stderr,
6837                                         "%s %s: invalid max-inherit-rr '%s'\n",
6838                                         progname, argv[0], optarg);
6839                                 return CMD_HELP;
6840                         }
6841                         if (max_inherit_rr == 0) {
6842                                 max_inherit_rr = LMV_INHERIT_RR_NONE;
6843                         } else if (max_inherit_rr == -1) {
6844                                 max_inherit_rr = LMV_INHERIT_RR_UNLIMITED;
6845                         } else if (max_inherit_rr > LMV_INHERIT_RR_MAX) {
6846                                 fprintf(stderr,
6847                                         "%s %s: max-inherit-rr %d exceeds maximum %u\n",
6848                                         progname, argv[0], max_inherit_rr,
6849                                         LMV_INHERIT_RR_MAX);
6850                                 return CMD_HELP;
6851                         }
6852                         break;
6853                 default:
6854                         fprintf(stderr, "%s: unrecognized option '%s'\n",
6855                                 progname, argv[optind - 1]);
6856                         /* fallthrough */
6857                 case 'h':
6858                         return CMD_HELP;
6859                 }
6860         }
6861
6862         if (optind == argc) {
6863                 fprintf(stderr, "%s %s: DIR must be specified\n",
6864                         progname, argv[0]);
6865                 return CMD_HELP;
6866         }
6867
6868         if (xattr && !foreign_mode) {
6869                 /*
6870                  * only print a warning as this is armless and will be
6871                  * ignored
6872                  */
6873                 fprintf(stderr,
6874                         "%s %s: xattr has been specified for non-foreign layout\n",
6875                         progname, argv[0]);
6876         } else if (foreign_mode && !xattr) {
6877                 fprintf(stderr,
6878                         "%s %s: xattr must be provided in foreign mode\n",
6879                         progname, argv[0]);
6880                 return CMD_HELP;
6881         }
6882
6883         if (foreign_mode && (delete || default_stripe || lsa.lsa_nr_tgts ||
6884             lsa.lsa_tgts || setstripe_args_specified(&lsa))) {
6885                 fprintf(stderr,
6886                         "%s %s: only --xattr/--flags/--mode options are valid with --foreign\n",
6887                         progname, argv[0]);
6888                 return CMD_HELP;
6889         }
6890
6891         if (!delete && lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT &&
6892             lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT && !foreign_mode) {
6893                 /* if no parameters set, create directory on least-used MDTs */
6894                 lsa.lsa_stripe_off = -1;
6895                 lsa.lsa_stripe_count = 1;
6896         }
6897
6898         if (delete &&
6899             (lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
6900              lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)) {
6901                 fprintf(stderr,
6902                         "%s %s: cannot specify -d with -c or -i options\n",
6903                         progname, argv[0]);
6904                 return CMD_HELP;
6905         }
6906
6907         if (mode_opt) {
6908                 mode = strtoul(mode_opt, &end, 8);
6909                 if (*end != '\0') {
6910                         fprintf(stderr,
6911                                 "%s %s: bad MODE '%s'\n",
6912                                 progname, argv[0], mode_opt);
6913                         return CMD_HELP;
6914                 }
6915                 previous_mode = umask(0);
6916         }
6917
6918         if (max_inherit_rr != LAYOUT_INHERIT_UNSET &&
6919             lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT &&
6920             lsa.lsa_stripe_off != -1) {
6921                 fprintf(stderr,
6922                         "%s %s: max-inherit-rr is meaningless if stripe offset != -1\n",
6923                         progname, argv[0]);
6924                 return CMD_HELP;
6925         }
6926
6927         /* foreign LMV/dir case */
6928         if (foreign_mode) {
6929                 if (argc > optind + 1) {
6930                         fprintf(stderr,
6931                                 "%s %s: cannot specify multiple foreign dirs\n",
6932                                 progname, argv[0]);
6933                         return CMD_HELP;
6934                 }
6935
6936                 dname = argv[optind];
6937                 result = llapi_dir_create_foreign(dname, mode, type, flags,
6938                                                   xattr);
6939                 if (result != 0)
6940                         fprintf(stderr,
6941                                 "%s mkdir: can't create foreign dir '%s': %s\n",
6942                                 progname, dname, strerror(-result));
6943                 return result;
6944         }
6945
6946         /*
6947          * initialize stripe parameters, in case param is converted to specific,
6948          * i.e, 'lfs mkdir -i -1 -c N', always allocate space for lsp_tgts.
6949          */
6950         param = calloc(1, offsetof(typeof(*param),
6951                        lsp_tgts[lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ?
6952                                 lsa.lsa_stripe_count : lsa.lsa_nr_tgts]));
6953         if (!param) {
6954                 fprintf(stderr,
6955                         "%s %s: cannot allocate memory for parameters: %s\n",
6956                         progname, argv[0], strerror(ENOMEM));
6957                 return CMD_HELP;
6958         }
6959
6960         /* if "lfs setdirstripe -D -i -1" is used, assume 1-stripe directory */
6961         if (default_stripe && lsa.lsa_stripe_off == -1 &&
6962             (lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT ||
6963              lsa.lsa_stripe_count == 0))
6964                 lsa.lsa_stripe_count = 1;
6965         if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
6966                 param->lsp_stripe_count = lsa.lsa_stripe_count;
6967         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
6968                 param->lsp_stripe_offset = -1;
6969         else
6970                 param->lsp_stripe_offset = lsa.lsa_stripe_off;
6971         if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
6972                 param->lsp_stripe_pattern = lsa.lsa_pattern;
6973         else
6974                 param->lsp_stripe_pattern = LMV_HASH_TYPE_UNKNOWN;
6975         param->lsp_pool = lsa.lsa_pool_name;
6976         param->lsp_is_specific = false;
6977         if (default_stripe) {
6978                 if (max_inherit == LAYOUT_INHERIT_UNSET)
6979                         max_inherit = LMV_INHERIT_DEFAULT;
6980                 if (max_inherit_rr == LAYOUT_INHERIT_UNSET)
6981                         max_inherit_rr = LMV_INHERIT_RR_DEFAULT;
6982                 param->lsp_max_inherit = max_inherit;
6983                 param->lsp_max_inherit_rr = max_inherit_rr;
6984         }
6985         if (strcmp(argv[0], "mkdir") == 0)
6986                 param->lsp_is_create = true;
6987         if (lsa.lsa_nr_tgts > 1) {
6988                 if (lsa.lsa_stripe_count > 0 &&
6989                     lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
6990                     lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
6991                         fprintf(stderr,
6992                                 "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
6993                                 argv[0], lsa.lsa_stripe_count,
6994                                 lsa.lsa_nr_tgts);
6995                         free(param);
6996                         return CMD_HELP;
6997                 }
6998
6999                 param->lsp_is_specific = true;
7000                 param->lsp_stripe_count = lsa.lsa_nr_tgts;
7001                 memcpy(param->lsp_tgts, mdts, sizeof(*mdts) * lsa.lsa_nr_tgts);
7002         }
7003
7004         dname = argv[optind];
7005         do {
7006                 if (default_stripe) {
7007                         result = llapi_dir_set_default_lmv(dname, param);
7008                         if (result)
7009                                 fprintf(stderr,
7010                                         "%s setdirstripe: cannot set default stripe on dir '%s': %s\n",
7011                                         progname, dname, strerror(-result));
7012                         continue;
7013                 }
7014
7015                 result = llapi_dir_create(dname, mode, param);
7016                 if (result)
7017                         fprintf(stderr,
7018                                 "%s setdirstripe: cannot create dir '%s': %s\n",
7019                                 progname, dname, strerror(-result));
7020         } while (!result && (dname = argv[++optind]));
7021
7022         if (mode_opt)
7023                 umask(previous_mode);
7024
7025         free(param);
7026         return result;
7027 }
7028
7029 /* functions */
7030 static int lfs_rmentry(int argc, char **argv)
7031 {
7032         char *dname;
7033         int   index;
7034         int   result = 0;
7035
7036         if (argc <= 1) {
7037                 fprintf(stderr, "error: %s: missing dirname\n",
7038                         argv[0]);
7039                 return CMD_HELP;
7040         }
7041
7042         index = 1;
7043         dname = argv[index];
7044         while (dname) {
7045                 result = llapi_direntry_remove(dname);
7046                 if (result) {
7047                         fprintf(stderr,
7048                                 "error: %s: remove dir entry '%s' failed\n",
7049                                 argv[0], dname);
7050                         break;
7051                 }
7052                 dname = argv[++index];
7053         }
7054         return result;
7055 }
7056
7057 static int lfs_unlink_foreign(int argc, char **argv)
7058 {
7059         char *name;
7060         int   index;
7061         int   result = 0;
7062
7063         if (argc <= 1) {
7064                 fprintf(stderr, "error: %s: missing pathname\n",
7065                         argv[0]);
7066                 return CMD_HELP;
7067         }
7068
7069         index = 1;
7070         name = argv[index];
7071         while (name != NULL) {
7072                 result = llapi_unlink_foreign(name);
7073                 if (result) {
7074                         fprintf(stderr,
7075                                 "error: %s: unlink foreign entry '%s' failed\n",
7076                                 argv[0], name);
7077                         break;
7078                 }
7079                 name = argv[++index];
7080         }
7081         return result;
7082 }
7083
7084 static int lfs_mv(int argc, char **argv)
7085 {
7086         struct lmv_user_md lmu = { LMV_USER_MAGIC };
7087         struct find_param param = {
7088                 .fp_max_depth = -1,
7089                 .fp_mdt_index = -1,
7090         };
7091         char *end;
7092         int c;
7093         int rc = 0;
7094         struct option long_opts[] = {
7095         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
7096         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
7097         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
7098         { .name = NULL } };
7099
7100         while ((c = getopt_long(argc, argv, "m:M:v", long_opts, NULL)) != -1) {
7101                 switch (c) {
7102 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
7103                 case 'M':
7104                         fprintf(stderr,
7105                                 "warning: '-M' deprecated, use '--mdt-index' or '-m' instead\n");
7106 #endif
7107                 case 'm':
7108                         errno = 0;
7109                         lmu.lum_stripe_offset = strtoul(optarg, &end, 0);
7110                         if (errno != 0 || *end != '\0' ||
7111                             lmu.lum_stripe_offset >= UINT32_MAX) {
7112                                 fprintf(stderr, "%s mv: bad MDT index '%s'\n",
7113                                         progname, optarg);
7114                                 return CMD_HELP;
7115                         }
7116                         break;
7117                 case 'v':
7118                         param.fp_verbose = VERBOSE_DETAIL;
7119                         break;
7120                 default:
7121                         fprintf(stderr, "%s mv: unrecognized option '%s'\n",
7122                                 progname, argv[optind - 1]);
7123                         return CMD_HELP;
7124                 }
7125         }
7126
7127         if (lmu.lum_stripe_offset == LMV_OFFSET_DEFAULT) {
7128                 fprintf(stderr, "%s mv: MDT index must be specified\n",
7129                         progname);
7130                 return CMD_HELP;
7131         }
7132
7133         if (optind >= argc) {
7134                 fprintf(stderr, "%s mv: DIR must be specified\n", progname);
7135                 return CMD_HELP;
7136         }
7137
7138         lmu.lum_hash_type = LMV_HASH_TYPE_UNKNOWN;
7139
7140         /* initialize migrate mdt parameters */
7141         param.fp_lmv_md = &lmu;
7142         param.fp_migrate = 1;
7143         rc = llapi_migrate_mdt(argv[optind], &param);
7144         if (rc != 0)
7145                 fprintf(stderr, "%s mv: cannot migrate '%s' to MDT%04x: %s\n",
7146                         progname, argv[optind], lmu.lum_stripe_offset,
7147                         strerror(-rc));
7148         return rc;
7149 }
7150
7151 static int lfs_osts(int argc, char **argv)
7152 {
7153         return lfs_tgts(argc, argv);
7154 }
7155
7156 static int lfs_mdts(int argc, char **argv)
7157 {
7158         return lfs_tgts(argc, argv);
7159 }
7160
7161 static int lfs_df(int argc, char **argv)
7162 {
7163         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
7164         enum mntdf_flags flags = MNTDF_SHOW;
7165         int ops = LL_STATFS_LMV | LL_STATFS_LOV;
7166         int c, rc = 0, index = 0;
7167         char fsname[PATH_MAX] = "", *pool_name = NULL;
7168         struct option long_opts[] = {
7169         { .val = 'h',   .name = "human-readable", .has_arg = no_argument },
7170         { .val = 'H',   .name = "si",           .has_arg = no_argument },
7171         { .val = 'i',   .name = "inodes",       .has_arg = no_argument },
7172         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
7173         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
7174         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
7175         { .name = NULL} };
7176
7177         while ((c = getopt_long(argc, argv, "hHilp:v", long_opts, NULL)) != -1) {
7178                 switch (c) {
7179                 case 'h':
7180                         flags = (flags & ~MNTDF_DECIMAL) | MNTDF_COOKED;
7181                         break;
7182                 case 'H':
7183                         flags |= MNTDF_COOKED | MNTDF_DECIMAL;
7184                         break;
7185                 case 'i':
7186                         flags |= MNTDF_INODES;
7187                         break;
7188                 case 'l':
7189                         flags |= MNTDF_LAZY;
7190                         break;
7191                 case 'p':
7192                         pool_name = optarg;
7193                         break;
7194                 case 'v':
7195                         flags |= MNTDF_VERBOSE;
7196                         break;
7197                 default:
7198                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7199                                 progname, argv[optind - 1]);
7200                         return CMD_HELP;
7201                 }
7202         }
7203         if (optind < argc && !realpath(argv[optind], path)) {
7204                 rc = -errno;
7205                 fprintf(stderr, "%s: invalid path '%s': %s\n",
7206                         progname, argv[optind], strerror(-rc));
7207                 return rc;
7208         }
7209
7210         while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7211                 /* Check if we have a mount point */
7212                 if (mntdir[0] == '\0')
7213                         continue;
7214
7215                 rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
7216                 if (rc || path[0] != '\0')
7217                         break;
7218                 fsname[0] = '\0'; /* avoid matching in next loop */
7219                 mntdir[0] = '\0'; /* avoid matching in next loop */
7220         }
7221
7222         return rc;
7223 }
7224
7225 static int print_instance(const char *mntdir, char *buf, size_t buflen,
7226                           bool opt_instance, bool opt_fsname, bool opt_mntdir)
7227 {
7228         int rc = 0;
7229
7230         if (opt_fsname == opt_instance) { /* both true or both false */
7231                 rc = llapi_getname(mntdir, buf, buflen);
7232         } else if (opt_fsname) {
7233                 /*
7234                  * llapi_search_mounts() fills @buf with fsname, but that is not
7235                  * called if explicit paths are specified on the command-line
7236                  */
7237                 if (buf[0] == '\0')
7238                         rc = llapi_get_fsname(mntdir, buf, buflen);
7239         } else /* if (opt_instance) */ {
7240                 rc = llapi_get_instance(mntdir, buf, buflen);
7241         }
7242
7243         if (rc < 0) {
7244                 fprintf(stderr, "cannot get instance for '%s': %s\n",
7245                         mntdir, strerror(-rc));
7246                 return rc;
7247         }
7248
7249         if (opt_mntdir)
7250                 printf("%s %s\n", buf, mntdir);
7251         else
7252                 printf("%s\n", buf);
7253
7254         return 0;
7255 }
7256
7257 static int lfs_getname(int argc, char **argv)
7258 {
7259         struct option long_opts[] = {
7260         { .val = 'h',   .name = "help",         .has_arg = no_argument },
7261         { .val = 'i',   .name = "instance",     .has_arg = no_argument },
7262         { .val = 'n',   .name = "fsname",       .has_arg = no_argument },
7263         { .name = NULL} };
7264         bool opt_instance = false, opt_fsname = false;
7265         char fsname[PATH_MAX] = "";
7266         int rc = 0, rc2, c;
7267
7268         while ((c = getopt_long(argc, argv, "hin", long_opts, NULL)) != -1) {
7269                 switch (c) {
7270                 case 'i':
7271                         opt_instance = true;
7272                         break;
7273                 case 'n':
7274                         opt_fsname = true;
7275                         break;
7276                 default:
7277                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7278                                 progname, argv[optind - 1]);
7279                         /* fallthrough */
7280                 case 'h':
7281                         return CMD_HELP;
7282                 }
7283         }
7284
7285         if (optind == argc) { /* no paths specified, get all paths. */
7286                 char mntdir[PATH_MAX] = "", path[PATH_MAX] = "";
7287                 int index = 0;
7288
7289                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7290                         rc2 = print_instance(mntdir, fsname, sizeof(fsname),
7291                                              opt_instance, opt_fsname, true);
7292                         if (!rc)
7293                                 rc = rc2;
7294                         path[0] = fsname[0] = mntdir[0] = '\0';
7295                 }
7296         } else { /* paths specified, only attempt to search these. */
7297                 bool opt_mntdir;
7298
7299                 /* if only one path is given, print only requested info */
7300                 opt_mntdir = argc - optind > 1 || (opt_instance == opt_fsname);
7301
7302                 for (; optind < argc; optind++) {
7303                         rc2 = print_instance(argv[optind], fsname,
7304                                              sizeof(fsname), opt_instance,
7305                                              opt_fsname, opt_mntdir);
7306                         if (!rc)
7307                                 rc = rc2;
7308                         fsname[0] = '\0';
7309                 }
7310         }
7311
7312         return rc;
7313 }
7314
7315 static int lfs_check(int argc, char **argv)
7316 {
7317         char mntdir[PATH_MAX] = {'\0'};
7318         int num_types = 1;
7319         char *obd_types[3];
7320         char obd_type1[4];
7321         char obd_type2[4];
7322         char obd_type3[4];
7323         int rc;
7324
7325         if (argc != 2) {
7326                 fprintf(stderr, "%s check: server type must be specified\n",
7327                         progname);
7328                 return CMD_HELP;
7329         }
7330
7331         obd_types[0] = obd_type1;
7332         obd_types[1] = obd_type2;
7333         obd_types[2] = obd_type3;
7334
7335         if (strcmp(argv[1], "osts") == 0) {
7336                 strcpy(obd_types[0], "osc");
7337         } else if (strcmp(argv[1], "mdts") == 0 ||
7338                    strcmp(argv[1], "mds") == 0) {
7339                 strcpy(obd_types[0], "mdc");
7340         } else if (strcmp(argv[1], "mgts") == 0) {
7341                 strcpy(obd_types[0], "mgc");
7342         } else if (strcmp(argv[1], "all") == 0 ||
7343                    strcmp(argv[1], "servers") == 0) {
7344                 num_types = 3;
7345                 strcpy(obd_types[0], "osc");
7346                 strcpy(obd_types[1], "mdc");
7347                 strcpy(obd_types[2], "mgc");
7348         } else {
7349                 fprintf(stderr, "%s check: unrecognized option '%s'\n",
7350                         progname, argv[1]);
7351                 return CMD_HELP;
7352         }
7353
7354         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
7355         if (rc < 0 || mntdir[0] == '\0') {
7356                 fprintf(stderr,
7357                         "%s check: cannot find mounted Lustre filesystem: %s\n",
7358                         progname, (rc < 0) ? strerror(-rc) : strerror(ENODEV));
7359                 return rc;
7360         }
7361
7362         rc = llapi_target_check(num_types, obd_types, mntdir);
7363         if (rc)
7364                 fprintf(stderr, "%s check: cannot check target '%s': %s\n",
7365                         progname, argv[1], strerror(-rc));
7366
7367         return rc;
7368 }
7369
7370 #ifdef HAVE_SYS_QUOTA_H
7371 #define ADD_OVERFLOW(a, b) \
7372                      ((((a) + (b)) < (a)) ? \
7373                       ((a) = ULONG_MAX) : ((a) = (a) + (b)))
7374
7375 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
7376  * returns the value or ULONG_MAX on integer overflow or incorrect format
7377  * Notes:
7378  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
7379  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
7380  *        3. empty integer value is interpreted as 0
7381  */
7382 static unsigned long str2sec(const char *timestr)
7383 {
7384         const char spec[] = "smhdw";
7385         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
7386         unsigned long val = 0;
7387         char *tail;
7388
7389         if (strpbrk(timestr, spec) == NULL) {
7390                 /*
7391                  * no specifiers inside the time string,
7392                  * should treat it as an integer value
7393                  */
7394                 val = strtoul(timestr, &tail, 10);
7395                 return *tail ? ULONG_MAX : val;
7396         }
7397
7398         /* format string is XXwXXdXXhXXmXXs */
7399         while (*timestr) {
7400                 unsigned long v;
7401                 int ind;
7402                 char *ptr;
7403
7404                 v = strtoul(timestr, &tail, 10);
7405                 if (v == ULONG_MAX || *tail == '\0')
7406                         /*
7407                          * value too large (ULONG_MAX or more)
7408                          * or missing specifier
7409                          */
7410                         goto error;
7411
7412                 ptr = strchr(spec, *tail);
7413                 if (!ptr)
7414                         /* unknown specifier */
7415                         goto error;
7416
7417                 ind = ptr - spec;
7418
7419                 /* check if product will overflow the type */
7420                 if (!(v < ULONG_MAX / mult[ind]))
7421                         goto error;
7422
7423                 ADD_OVERFLOW(val, mult[ind] * v);
7424                 if (val == ULONG_MAX)
7425                         goto error;
7426
7427                 timestr = tail + 1;
7428         }
7429
7430         return val;
7431
7432 error:
7433         return ULONG_MAX;
7434 }
7435
7436 #define ARG2ULL(nr, str, def_units)                                     \
7437 do {                                                                    \
7438         unsigned long long limit, units = def_units;                    \
7439         int rc;                                                         \
7440                                                                         \
7441         rc = llapi_parse_size(str, &limit, &units, 1);                  \
7442         if (rc < 0) {                                                   \
7443                 fprintf(stderr, "%s: invalid limit '%s'\n",             \
7444                         progname, str);                                 \
7445                 return CMD_HELP;                                        \
7446         }                                                               \
7447         nr = limit;                                                     \
7448 } while (0)
7449
7450 static inline int has_times_option(int argc, char **argv)
7451 {
7452         int i;
7453
7454         for (i = 1; i < argc; i++)
7455                 if (!strcmp(argv[i], "-t"))
7456                         return 1;
7457
7458         return 0;
7459 }
7460
7461 static inline int lfs_verify_poolarg(char *pool)
7462 {
7463         if (strnlen(optarg, LOV_MAXPOOLNAME + 1) > LOV_MAXPOOLNAME) {
7464                 fprintf(stderr,
7465                         "Pool name '%.*s' is longer than %d\n",
7466                         LOV_MAXPOOLNAME, pool, LOV_MAXPOOLNAME);
7467                 return 1;
7468         }
7469         return 0;
7470 }
7471
7472 int lfs_setquota_times(int argc, char **argv, struct if_quotactl *qctl)
7473 {
7474         int c, rc;
7475         char *mnt, *obd_type = (char *)qctl->obd_type;
7476         struct obd_dqblk *dqb = &qctl->qc_dqblk;
7477         struct obd_dqinfo *dqi = &qctl->qc_dqinfo;
7478         struct option long_opts[] = {
7479         { .val = 'b',   .name = "block-grace",  .has_arg = required_argument },
7480         { .val = 'g',   .name = "group",        .has_arg = no_argument },
7481         { .val = 'h',   .name = "help",         .has_arg = no_argument },
7482         { .val = 'i',   .name = "inode-grace",  .has_arg = required_argument },
7483         { .val = 'p',   .name = "projid",       .has_arg = no_argument },
7484         { .val = 't',   .name = "times",        .has_arg = no_argument },
7485         { .val = 'u',   .name = "user",         .has_arg = no_argument },
7486         { .val = LFS_POOL_OPT,
7487                         .name = "pool",         .has_arg = required_argument },
7488         { .name = NULL } };
7489         int qtype;
7490
7491         qctl->qc_cmd  = LUSTRE_Q_SETINFO;
7492         qctl->qc_type = ALLQUOTA;
7493
7494         while ((c = getopt_long(argc, argv, "b:ghi:ptu",
7495                                 long_opts, NULL)) != -1) {
7496                 switch (c) {
7497                 case 'u':
7498                         qtype = USRQUOTA;
7499                         goto quota_type;
7500                 case 'g':
7501                         qtype = GRPQUOTA;
7502                         goto quota_type;
7503                 case 'p':
7504                         qtype = PRJQUOTA;
7505 quota_type:
7506                         if (qctl->qc_type != ALLQUOTA) {
7507                                 fprintf(stderr,
7508                                         "%s: -u/g/p cannot be used more than once\n",
7509                                         progname);
7510                                 return CMD_HELP;
7511                         }
7512                         qctl->qc_type = qtype;
7513                         break;
7514                 case 'b':
7515                         if (strncmp(optarg, NOTIFY_GRACE,
7516                                     strlen(NOTIFY_GRACE)) == 0) {
7517                                 dqi->dqi_bgrace = NOTIFY_GRACE_TIME;
7518                         } else {
7519                                 dqi->dqi_bgrace = str2sec(optarg);
7520                                 if (dqi->dqi_bgrace >= NOTIFY_GRACE_TIME) {
7521                                         fprintf(stderr,
7522                                                 "%s: bad block-grace: %s\n",
7523                                                 progname, optarg);
7524                                         return CMD_HELP;
7525                                 }
7526                         }
7527                         dqb->dqb_valid |= QIF_BTIME;
7528                         break;
7529                 case 'i':
7530                         if (strncmp(optarg, NOTIFY_GRACE,
7531                                     strlen(NOTIFY_GRACE)) == 0) {
7532                                 dqi->dqi_igrace = NOTIFY_GRACE_TIME;
7533                         } else {
7534                                 dqi->dqi_igrace = str2sec(optarg);
7535                                 if (dqi->dqi_igrace >= NOTIFY_GRACE_TIME) {
7536                                         fprintf(stderr,
7537                                                 "%s: bad inode-grace: %s\n",
7538                                                 progname, optarg);
7539                                         return CMD_HELP;
7540                                 }
7541                         }
7542                         dqb->dqb_valid |= QIF_ITIME;
7543                         break;
7544                 case 't': /* Yes, of course! */
7545                         break;
7546                 case LFS_POOL_OPT:
7547                         if (lfs_verify_poolarg(optarg))
7548                                 return -1;
7549                         strncpy(qctl->qc_poolname, optarg, LOV_MAXPOOLNAME);
7550                         qctl->qc_cmd  = LUSTRE_Q_SETINFOPOOL;
7551                         break;
7552                 /* getopt prints error message for us when opterr != 0 */
7553                 default:
7554                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7555                                 progname, argv[optind - 1]);
7556                         /* fallthrough */
7557                 case 'h':
7558                         return CMD_HELP;
7559                 }
7560         }
7561
7562         if (qctl->qc_type == ALLQUOTA) {
7563                 fprintf(stderr, "%s: neither -u, -g nor -p specified\n",
7564                         progname);
7565                 return CMD_HELP;
7566         }
7567
7568         if (optind != argc - 1) {
7569                 fprintf(stderr, "%s: unexpected parameter '%s'\n",
7570                         progname, argv[optind + 1]);
7571                 return CMD_HELP;
7572         }
7573
7574         mnt = argv[optind];
7575         rc = llapi_quotactl(mnt, qctl);
7576         if (rc) {
7577                 if (*obd_type)
7578                         fprintf(stderr, "%s %s ", obd_type,
7579                                 obd_uuid2str(&qctl->obd_uuid));
7580                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
7581                 return rc;
7582         }
7583
7584         return 0;
7585 }
7586
7587 #define BSLIMIT (1 << 0)
7588 #define BHLIMIT (1 << 1)
7589 #define ISLIMIT (1 << 2)
7590 #define IHLIMIT (1 << 3)
7591
7592 int lfs_setquota(int argc, char **argv)
7593 {
7594         int c, rc = 0;
7595         struct if_quotactl *qctl;
7596         char *mnt, *obd_type;
7597         struct obd_dqblk *dqb;
7598         struct option long_opts[] = {
7599         { .val = 'b',   .name = "block-softlimit",
7600                                                 .has_arg = required_argument },
7601         { .val = 'B',   .name = "block-hardlimit",
7602                                                 .has_arg = required_argument },
7603         { .val = 'd',   .name = "default",      .has_arg = no_argument },
7604         { .val = 'g',   .name = "group",        .has_arg = required_argument },
7605         { .val = 'G',   .name = "default-grp",  .has_arg = no_argument },
7606         { .val = 'h',   .name = "help",         .has_arg = no_argument },
7607         { .val = 'i',   .name = "inode-softlimit",
7608                                                 .has_arg = required_argument },
7609         { .val = 'I',   .name = "inode-hardlimit",
7610                                                 .has_arg = required_argument },
7611         { .val = 'p',   .name = "projid",       .has_arg = required_argument },
7612         { .val = 'P',   .name = "default-prj",  .has_arg = no_argument },
7613         { .val = 'u',   .name = "user",         .has_arg = required_argument },
7614         { .val = 'U',   .name = "default-usr",  .has_arg = no_argument },
7615         { .val = LFS_POOL_OPT,
7616                         .name = "pool",         .has_arg = required_argument },
7617         { .name = NULL } };
7618         unsigned int limit_mask = 0;
7619         bool use_default = false;
7620         int qtype, qctl_len;
7621
7622         qctl_len = sizeof(*qctl) + LOV_MAXPOOLNAME + 1;
7623         qctl = malloc(qctl_len);
7624         if (!qctl)
7625                 return -ENOMEM;
7626
7627         memset(qctl, 0, qctl_len);
7628         obd_type = (char *)qctl->obd_type;
7629         dqb = &qctl->qc_dqblk;
7630
7631         if (has_times_option(argc, argv)) {
7632                 rc = lfs_setquota_times(argc, argv, qctl);
7633                 goto out;
7634         }
7635
7636         qctl->qc_cmd  = LUSTRE_Q_SETQUOTA;
7637         qctl->qc_type = ALLQUOTA; /* ALLQUOTA makes no sense for setquota,
7638                                    * so it can be used as a marker that qc_type
7639                                    * isn't reinitialized from command line
7640                                    */
7641
7642         while ((c = getopt_long(argc, argv, "b:B:dg:Ghi:I:p:Pu:U",
7643                 long_opts, NULL)) != -1) {
7644                 switch (c) {
7645                 case 'U':
7646                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7647                         qtype = USRQUOTA;
7648                         qctl->qc_id = 0;
7649                         goto quota_type_def;
7650                 case 'u':
7651                         qtype = USRQUOTA;
7652                         rc = name2uid(&qctl->qc_id, optarg);
7653                         goto quota_type;
7654                 case 'G':
7655                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7656                         qtype = GRPQUOTA;
7657                         qctl->qc_id = 0;
7658                         goto quota_type_def;
7659                 case 'g':
7660                         qtype = GRPQUOTA;
7661                         rc = name2gid(&qctl->qc_id, optarg);
7662                         goto quota_type;
7663                 case 'P':
7664                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7665                         qtype = PRJQUOTA;
7666                         qctl->qc_id = 0;
7667                         goto quota_type_def;
7668                 case 'p':
7669                         qtype = PRJQUOTA;
7670                         rc = name2projid(&qctl->qc_id, optarg);
7671 quota_type:
7672                         if (rc) {
7673                                 if (str2quotaid(&qctl->qc_id, optarg)) {
7674                                         fprintf(stderr,
7675                                                 "%s setquota: invalid id '%s'\n",
7676                                                 progname, optarg);
7677                                         rc = -1;
7678                                         goto out;
7679                                 }
7680                         }
7681
7682                         if (qctl->qc_id == 0) {
7683                                 fprintf(stderr,
7684                                         "%s setquota: can't set quota for root usr/group/project.\n",
7685                                         progname);
7686                                 rc = -1;
7687                                 goto out;
7688                         }
7689
7690 quota_type_def:
7691                         if (qctl->qc_type != ALLQUOTA) {
7692                                 fprintf(stderr,
7693                                         "%s setquota: only one of -u, -U, -g, -G, -p or -P may be specified\n",
7694                                         progname);
7695                                 rc = CMD_HELP;
7696                                 goto out;
7697                         }
7698                         qctl->qc_type = qtype;
7699                         break;
7700                 case 'd':
7701                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7702                         use_default = true;
7703                         break;
7704                 case 'b':
7705                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
7706                         dqb->dqb_bsoftlimit >>= 10;
7707                         limit_mask |= BSLIMIT;
7708                         if (dqb->dqb_bsoftlimit &&
7709                             dqb->dqb_bsoftlimit <= 1024) /* <= 1M? */
7710                                 fprintf(stderr,
7711                                         "%s setquota: warning: block softlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
7712                                         progname,
7713                                         (unsigned long long)dqb->dqb_bsoftlimit,
7714                                         progname);
7715                         break;
7716                 case 'B':
7717                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
7718                         dqb->dqb_bhardlimit >>= 10;
7719                         limit_mask |= BHLIMIT;
7720                         if (dqb->dqb_bhardlimit &&
7721                             dqb->dqb_bhardlimit <= 1024) /* <= 1M? */
7722                                 fprintf(stderr,
7723                                         "%s setquota: warning: block hardlimit '%llu' smaller than minimum qunit size\n"
7724                                         "See '%s help setquota' or Lustre manual for details\n",
7725                                         progname,
7726                                         (unsigned long long)dqb->dqb_bhardlimit,
7727                                         progname);
7728                         break;
7729                 case 'i':
7730                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
7731                         limit_mask |= ISLIMIT;
7732                         if (dqb->dqb_isoftlimit &&
7733                             dqb->dqb_isoftlimit <= 1024) /* <= 1K inodes? */
7734                                 fprintf(stderr,
7735                                         "%s setquota: warning: inode softlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
7736                                         progname,
7737                                         (unsigned long long)dqb->dqb_isoftlimit,
7738                                         progname);
7739                         break;
7740                 case 'I':
7741                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
7742                         limit_mask |= IHLIMIT;
7743                         if (dqb->dqb_ihardlimit &&
7744                             dqb->dqb_ihardlimit <= 1024) /* <= 1K inodes? */
7745                                 fprintf(stderr,
7746                                         "%s setquota: warning: inode hardlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
7747                                         progname,
7748                                         (unsigned long long)dqb->dqb_ihardlimit,
7749                                         progname);
7750                         break;
7751                 case LFS_POOL_OPT:
7752                         if (lfs_verify_poolarg(optarg)) {
7753                                 rc = -1;
7754                                 goto out;
7755                         }
7756                         strncpy(qctl->qc_poolname, optarg, LOV_MAXPOOLNAME);
7757                         qctl->qc_cmd = qctl->qc_cmd == LUSTRE_Q_SETDEFAULT ?
7758                                                 LUSTRE_Q_SETDEFAULT_POOL :
7759                                                 LUSTRE_Q_SETQUOTAPOOL;
7760                         break;
7761                 default:
7762                         fprintf(stderr,
7763                                 "%s setquota: unrecognized option '%s'\n",
7764                                 progname, argv[optind - 1]);
7765                         /* fallthrough */
7766                 case 'h':
7767                         rc = CMD_HELP;
7768                         goto out;
7769                 }
7770         }
7771
7772         if (qctl->qc_type == ALLQUOTA) {
7773                 fprintf(stderr,
7774                         "%s setquota: either -u or -g must be specified\n",
7775                         progname);
7776                 rc = CMD_HELP;
7777                 goto out;
7778         }
7779
7780         if (!use_default && limit_mask == 0) {
7781                 fprintf(stderr,
7782                         "%s setquota: at least one limit must be specified\n",
7783                         progname);
7784                 rc = CMD_HELP;
7785                 goto out;
7786         }
7787
7788         if (use_default && limit_mask != 0) {
7789                 fprintf(stderr,
7790                         "%s setquota: limits should not be specified when using default quota\n",
7791                         progname);
7792                 rc = CMD_HELP;
7793                 goto out;
7794         }
7795
7796         if (use_default && qctl->qc_id == 0) {
7797                 fprintf(stderr,
7798                         "%s setquota: can not set default quota for root user/group/project\n",
7799                         progname);
7800                 rc = CMD_HELP;
7801                 goto out;
7802         }
7803
7804         if (optind != argc - 1) {
7805                 fprintf(stderr,
7806                         "%s setquota: filesystem not specified or unexpected argument '%s'\n",
7807                         progname, argv[optind]);
7808                 rc = CMD_HELP;
7809                 goto out;
7810         }
7811
7812         mnt = argv[optind];
7813
7814         if (use_default) {
7815                 dqb->dqb_bhardlimit = 0;
7816                 dqb->dqb_bsoftlimit = 0;
7817                 dqb->dqb_ihardlimit = 0;
7818                 dqb->dqb_isoftlimit = 0;
7819                 dqb->dqb_itime = 0;
7820                 dqb->dqb_btime = 0;
7821                 dqb->dqb_valid |= QIF_LIMITS | QIF_TIMES;
7822                 /* do not set inode limits for Pool Quotas */
7823                 if (qctl->qc_cmd  == LUSTRE_Q_SETDEFAULT_POOL)
7824                         dqb->dqb_valid ^= QIF_ILIMITS | QIF_ITIME;
7825         } else if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
7826                    (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
7827                 /* sigh, we can't just set blimits/ilimits */
7828                 struct if_quotactl tmp_qctl = {.qc_cmd  = LUSTRE_Q_GETQUOTA,
7829                                                .qc_type = qctl->qc_type,
7830                                                .qc_id   = qctl->qc_id};
7831
7832                 rc = llapi_quotactl(mnt, &tmp_qctl);
7833                 if (rc < 0)
7834                         goto out;
7835
7836                 if (!(limit_mask & BHLIMIT))
7837                         dqb->dqb_bhardlimit = tmp_qctl.qc_dqblk.dqb_bhardlimit;
7838                 if (!(limit_mask & BSLIMIT))
7839                         dqb->dqb_bsoftlimit = tmp_qctl.qc_dqblk.dqb_bsoftlimit;
7840                 if (!(limit_mask & IHLIMIT))
7841                         dqb->dqb_ihardlimit = tmp_qctl.qc_dqblk.dqb_ihardlimit;
7842                 if (!(limit_mask & ISLIMIT))
7843                         dqb->dqb_isoftlimit = tmp_qctl.qc_dqblk.dqb_isoftlimit;
7844
7845                 /* Keep grace times if we have got no softlimit arguments */
7846                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
7847                         dqb->dqb_valid |= QIF_BTIME;
7848                         dqb->dqb_btime = tmp_qctl.qc_dqblk.dqb_btime;
7849                 }
7850
7851                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
7852                         dqb->dqb_valid |= QIF_ITIME;
7853                         dqb->dqb_itime = tmp_qctl.qc_dqblk.dqb_itime;
7854                 }
7855         }
7856
7857         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
7858         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
7859
7860         rc = llapi_quotactl(mnt, qctl);
7861         if (rc) {
7862                 if (*obd_type)
7863                         fprintf(stderr,
7864                                 "%s setquota: cannot quotactl '%s' '%s': %s",
7865                                 progname, obd_type,
7866                                 obd_uuid2str(&qctl->obd_uuid), strerror(-rc));
7867         }
7868 out:
7869         free(qctl);
7870         return rc;
7871 }
7872
7873 /* Converts seconds value into format string
7874  * result is returned in buf
7875  * Notes:
7876  *        1. result is in descenting order: 1w2d3h4m5s
7877  *        2. zero fields are not filled (except for p. 3): 5d1s
7878  *        3. zero seconds value is presented as "0s"
7879  */
7880 static char *__sec2str(time_t seconds, char *buf)
7881 {
7882         const char spec[] = "smhdw";
7883         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
7884         unsigned long c;
7885         char *tail = buf;
7886         int i;
7887
7888         for (i = ARRAY_SIZE(mult) - 1 ; i >= 0; i--) {
7889                 c = seconds / mult[i];
7890
7891                 if (c > 0 || (i == 0 && buf == tail))
7892                         tail += scnprintf(tail, 40-(tail-buf), "%lu%c", c,
7893                                           spec[i]);
7894
7895                 seconds %= mult[i];
7896         }
7897
7898         return tail;
7899 }
7900
7901 static void sec2str(time_t seconds, char *buf, int rc)
7902 {
7903         char *tail = buf;
7904
7905         if (rc)
7906                 *tail++ = '[';
7907
7908         tail = __sec2str(seconds, tail);
7909
7910         if (rc && tail - buf < 39) {
7911                 *tail++ = ']';
7912                 *tail++ = 0;
7913         }
7914 }
7915
7916 static void diff2str(time_t seconds, char *buf, time_t now)
7917 {
7918         buf[0] = 0;
7919         if (!seconds)
7920                 return;
7921         if (seconds <= now) {
7922                 strcpy(buf, "none");
7923                 return;
7924         }
7925         __sec2str(seconds - now, buf);
7926 }
7927
7928 static void print_quota_title(char *name, struct if_quotactl *qctl,
7929                               bool human_readable, bool show_default)
7930 {
7931         if (show_default) {
7932                 printf("Disk default %s quota:\n", qtype_name(qctl->qc_type));
7933                 printf("%15s %8s%8s%8s %8s%8s%8s\n",
7934                        "Filesystem", "bquota", "blimit", "bgrace",
7935                        "iquota", "ilimit", "igrace");
7936         } else {
7937                 printf("Disk quotas for %s %s (%cid %u):\n",
7938                        qtype_name(qctl->qc_type), name,
7939                        *qtype_name(qctl->qc_type), qctl->qc_id);
7940                 printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
7941                        "Filesystem", human_readable ? "used" : "kbytes",
7942                        "quota", "limit", "grace",
7943                        "files", "quota", "limit", "grace");
7944         }
7945 }
7946
7947 static void kbytes2str(__u64 num, char *buf, int buflen, bool h)
7948 {
7949         if (!h) {
7950                 snprintf(buf, buflen, "%ju", (uintmax_t)num);
7951         } else {
7952                 if (num >> 40)
7953                         snprintf(buf, buflen, "%5.4gP",
7954                                  (double)num / ((__u64)1 << 40));
7955                 else if (num >> 30)
7956                         snprintf(buf, buflen, "%5.4gT",
7957                                  (double)num / (1 << 30));
7958                 else if (num >> 20)
7959                         snprintf(buf, buflen, "%5.4gG",
7960                                  (double)num / (1 << 20));
7961                 else if (num >> 10)
7962                         snprintf(buf, buflen, "%5.4gM",
7963                                  (double)num / (1 << 10));
7964                 else
7965                         snprintf(buf, buflen, "%ju%s", (uintmax_t)num, "k");
7966         }
7967 }
7968
7969 #define STRBUF_LEN      24
7970 static void print_quota(char *mnt, struct if_quotactl *qctl, int type,
7971                         int rc, bool h, bool show_default)
7972 {
7973         time_t now;
7974
7975         time(&now);
7976
7977         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA ||
7978             qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ||
7979             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT ||
7980             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT_POOL) {
7981                 int bover = 0, iover = 0;
7982                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
7983                 char numbuf[3][STRBUF_LEN + 2]; /* 2 for brackets or wildcard */
7984                 char timebuf[40];
7985                 char strbuf[STRBUF_LEN];
7986
7987                 if (dqb->dqb_bhardlimit &&
7988                     lustre_stoqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
7989                         bover = 1;
7990                 } else if (dqb->dqb_bsoftlimit && dqb->dqb_btime) {
7991                         if (dqb->dqb_btime > now)
7992                                 bover = 2;
7993                         else
7994                                 bover = 3;
7995                 }
7996
7997                 if (dqb->dqb_ihardlimit &&
7998                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
7999                         iover = 1;
8000                 } else if (dqb->dqb_isoftlimit && dqb->dqb_itime) {
8001                         if (dqb->dqb_itime > now)
8002                                 iover = 2;
8003                         else
8004                                 iover = 3;
8005                 }
8006
8007                 if (strlen(mnt) > 15)
8008                         printf("%s\n%15s", mnt, "");
8009                 else
8010                         printf("%15s", mnt);
8011
8012                 if (bover)
8013                         diff2str(dqb->dqb_btime, timebuf, now);
8014                 else if (show_default)
8015                         snprintf(timebuf, sizeof(timebuf), "%llu",
8016                                  (unsigned long long)dqb->dqb_btime);
8017
8018                 kbytes2str(lustre_stoqb(dqb->dqb_curspace),
8019                            strbuf, sizeof(strbuf), h);
8020                 if (rc == -EREMOTEIO)
8021                         sprintf(numbuf[0], "%s*", strbuf);
8022                 else
8023                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
8024                                 "%s" : "[%s]", strbuf);
8025
8026                 kbytes2str(dqb->dqb_bsoftlimit, strbuf, sizeof(strbuf), h);
8027                 if (type == QC_GENERAL)
8028                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS) ?
8029                                 "%s" : "[%s]", strbuf);
8030                 else
8031                         sprintf(numbuf[1], "%s", "-");
8032
8033                 kbytes2str(dqb->dqb_bhardlimit, strbuf, sizeof(strbuf), h);
8034                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS) ?
8035                         "%s" : "[%s]", strbuf);
8036
8037                 if (show_default)
8038                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
8039                 else
8040                         printf(" %7s%c %6s %7s %7s",
8041                                numbuf[0], bover ? '*' : ' ', numbuf[1],
8042                                numbuf[2], bover > 1 ? timebuf : "-");
8043
8044                 if (iover)
8045                         diff2str(dqb->dqb_itime, timebuf, now);
8046                 else if (show_default)
8047                         snprintf(timebuf, sizeof(timebuf), "%llu",
8048                                  (unsigned long long)dqb->dqb_itime);
8049
8050                 snprintf(numbuf[0], sizeof(numbuf),
8051                          (dqb->dqb_valid & QIF_INODES) ? "%ju" : "[%ju]",
8052                          (uintmax_t)dqb->dqb_curinodes);
8053
8054                 if (type == QC_GENERAL)
8055                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS) ?
8056                                 "%ju" : "[%ju]",
8057                                 (uintmax_t)dqb->dqb_isoftlimit);
8058                 else
8059                         sprintf(numbuf[1], "%s", "-");
8060
8061                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
8062                         "%ju" : "[%ju]", (uintmax_t)dqb->dqb_ihardlimit);
8063
8064                 if (show_default)
8065                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
8066                 else if (type != QC_OSTIDX)
8067                         printf(" %7s%c %6s %7s %7s",
8068                                numbuf[0], iover ? '*' : ' ', numbuf[1],
8069                                numbuf[2], iover > 1 ? timebuf : "-");
8070                 else
8071                         printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
8072                 printf("\n");
8073         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO || LUSTRE_Q_GETINFOPOOL ||
8074                    qctl->qc_cmd == Q_GETOINFO) {
8075                 char bgtimebuf[40];
8076                 char igtimebuf[40];
8077
8078                 if (qctl->qc_dqinfo.dqi_bgrace == NOTIFY_GRACE_TIME)
8079                         strncpy(bgtimebuf, NOTIFY_GRACE, 40);
8080                 else
8081                         sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
8082                 if (qctl->qc_dqinfo.dqi_igrace == NOTIFY_GRACE_TIME)
8083                         strncpy(igtimebuf, NOTIFY_GRACE, 40);
8084                 else
8085                         sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
8086
8087                 printf("Block grace time: %s; Inode grace time: %s\n",
8088                        bgtimebuf, igtimebuf);
8089         }
8090 }
8091
8092 static int tgt_name2index(const char *tgtname, unsigned int *idx)
8093 {
8094         char *dash, *endp;
8095
8096         /* format is "lustre-OST0001" */
8097         dash = memchr(tgtname, '-', LUSTRE_MAXFSNAME + 1);
8098         if (!dash) {
8099                 fprintf(stderr, "wrong tgtname format '%s'\n", tgtname);
8100                 return -EINVAL;
8101         }
8102         dash += 4;
8103
8104         *idx = strtoul(dash, &endp, 16);
8105         if (*idx > 0xffff) {
8106                 fprintf(stderr, "wrong index %s\n", tgtname);
8107                 return -ERANGE;
8108         }
8109
8110         return 0;
8111 }
8112
8113 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt,
8114                            bool h, __u64 *total)
8115 {
8116         int rc = 0, rc1 = 0, count = 0, i = 0;
8117         char **list = NULL, *buffer = NULL;
8118         __u32 valid = qctl->qc_valid;
8119
8120         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL && is_mdt)
8121                 return 0;
8122
8123         /* Is it correct for the case OST0000, OST0002, OST0003 -
8124          * we will ask OST0001 that is absent and won't ask OST0003? */
8125         rc = llapi_get_obd_count(mnt, &count, is_mdt);
8126         if (rc) {
8127                 fprintf(stderr, "can not get %s count: %s\n",
8128                         is_mdt ? "mdt" : "ost", strerror(-rc));
8129                 return rc;
8130         }
8131
8132         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8133                 char fname[PATH_MAX];
8134                 char fsname[LUSTRE_MAXFSNAME + 1];
8135                 int bufsize = sizeof(struct obd_uuid) * count;
8136
8137                 rc = llapi_search_fsname(mnt, fsname);
8138                 if (rc) {
8139                         fprintf(stderr, "cannot get fsname for mountpoint %s\n",
8140                                 mnt);
8141                         goto out;
8142                 }
8143                 buffer = malloc(bufsize + sizeof(*list) * count);
8144                 if (!buffer)
8145                         return -ENOMEM;
8146                 list = (char **)(buffer + bufsize);
8147                 snprintf(fname, PATH_MAX, "%s.%s", fsname, qctl->qc_poolname);
8148                 count = llapi_get_poolmembers(fname, list, count,
8149                                               buffer, bufsize);
8150                 if (count <= 0)
8151                         goto out;
8152         }
8153
8154         for (i = 0; i < count; i++) {
8155                 if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8156                         unsigned int index;
8157
8158                         if (tgt_name2index(list[i], &index))
8159                                 continue;
8160                         qctl->qc_idx = index;
8161                 } else {
8162                         qctl->qc_idx = i;
8163                 }
8164
8165                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
8166                 rc = llapi_quotactl(mnt, qctl);
8167                 if (rc) {
8168                         /* It is remote client case. */
8169                         if (rc == -EOPNOTSUPP) {
8170                                 rc = 0;
8171                                 goto out;
8172                         }
8173
8174                         if (!rc1)
8175                                 rc1 = rc;
8176                         fprintf(stderr, "quotactl %s%d failed.\n",
8177                                 is_mdt ? "mdt" : "ost", qctl->qc_idx);
8178                         continue;
8179                 }
8180
8181                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl,
8182                             qctl->qc_valid, 0, h, false);
8183                 *total += is_mdt ? qctl->qc_dqblk.dqb_ihardlimit :
8184                                    qctl->qc_dqblk.dqb_bhardlimit;
8185         }
8186 out:
8187         if (buffer)
8188                 free(buffer);
8189         qctl->qc_valid = valid;
8190         return rc ? : rc1;
8191 }
8192
8193 static int get_print_quota(char *mnt, char *name, struct if_quotactl *qctl,
8194                            int verbose, int quiet, bool human_readable,
8195                            bool show_default)
8196 {
8197         int rc1 = 0, rc2 = 0, rc3 = 0;
8198         char *obd_type = (char *)qctl->obd_type;
8199         char *obd_uuid = (char *)qctl->obd_uuid.uuid;
8200         __u64 total_ialloc = 0, total_balloc = 0;
8201         bool use_default_for_blk = false;
8202         bool use_default_for_file = false;
8203         int inacc;
8204
8205         rc1 = llapi_quotactl(mnt, qctl);
8206         if (rc1 < 0) {
8207                 switch (rc1) {
8208                 case -ESRCH:
8209                         fprintf(stderr, "%s quotas are not enabled.\n",
8210                                 qtype_name(qctl->qc_type));
8211                         goto out;
8212                 case -EPERM:
8213                         fprintf(stderr, "Permission denied.\n");
8214                 case -ENODEV:
8215                 case -ENOENT:
8216                         /* We already got error message. */
8217                         goto out;
8218                 default:
8219                         fprintf(stderr, "Unexpected quotactl error: %s\n",
8220                                 strerror(-rc1));
8221                 }
8222         }
8223
8224         if (!show_default && qctl->qc_id == 0) {
8225                 qctl->qc_dqblk.dqb_bhardlimit = 0;
8226                 qctl->qc_dqblk.dqb_bsoftlimit = 0;
8227                 qctl->qc_dqblk.dqb_ihardlimit = 0;
8228                 qctl->qc_dqblk.dqb_isoftlimit = 0;
8229                 qctl->qc_dqblk.dqb_btime = 0;
8230                 qctl->qc_dqblk.dqb_itime = 0;
8231                 qctl->qc_dqblk.dqb_valid |= QIF_LIMITS | QIF_TIMES;
8232         }
8233
8234         if (qctl->qc_dqblk.dqb_valid & QIF_BTIME &&
8235             LQUOTA_FLAG(qctl->qc_dqblk.dqb_btime) & LQUOTA_FLAG_DEFAULT) {
8236                 use_default_for_blk = true;
8237                 qctl->qc_dqblk.dqb_btime &= LQUOTA_GRACE_MASK;
8238         }
8239
8240         if (qctl->qc_dqblk.dqb_valid & QIF_ITIME &&
8241             LQUOTA_FLAG(qctl->qc_dqblk.dqb_itime) & LQUOTA_FLAG_DEFAULT) {
8242                 use_default_for_file = true;
8243                 qctl->qc_dqblk.dqb_itime &= LQUOTA_GRACE_MASK;
8244         }
8245
8246         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8247              qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ||
8248              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT_POOL ||
8249              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) && !quiet)
8250                 print_quota_title(name, qctl, human_readable, show_default);
8251
8252         if (rc1 && *obd_type)
8253                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
8254
8255         if (qctl->qc_valid != QC_GENERAL)
8256                 mnt = "";
8257
8258         inacc = (qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8259                  qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) &&
8260                 ((qctl->qc_dqblk.dqb_valid & (QIF_LIMITS|QIF_USAGE)) !=
8261                  (QIF_LIMITS|QIF_USAGE));
8262
8263         print_quota(mnt, qctl, QC_GENERAL, rc1, human_readable, show_default);
8264
8265         if (!show_default && verbose &&
8266             qctl->qc_valid == QC_GENERAL && qctl->qc_cmd != LUSTRE_Q_GETINFO &&
8267             qctl->qc_cmd != LUSTRE_Q_GETINFOPOOL) {
8268                 char strbuf[STRBUF_LEN];
8269
8270                 rc2 = print_obd_quota(mnt, qctl, 1, human_readable,
8271                                       &total_ialloc);
8272                 rc3 = print_obd_quota(mnt, qctl, 0, human_readable,
8273                                       &total_balloc);
8274                 kbytes2str(total_balloc, strbuf, sizeof(strbuf),
8275                            human_readable);
8276                 printf("Total allocated inode limit: %ju, total allocated block limit: %s\n",
8277                        (uintmax_t)total_ialloc, strbuf);
8278         }
8279
8280         if (use_default_for_blk)
8281                 printf("%cid %u is using default block quota setting\n",
8282                        *qtype_name(qctl->qc_type), qctl->qc_id);
8283
8284         if (use_default_for_file)
8285                 printf("%cid %u is using default file quota setting\n",
8286                        *qtype_name(qctl->qc_type), qctl->qc_id);
8287
8288         if (rc1 || rc2 || rc3 || inacc)
8289                 printf("Some errors happened when getting quota info. Some devices may be not working or deactivated. The data in \"[]\" is inaccurate.\n");
8290 out:
8291         if (rc1)
8292                 return rc1;
8293         if (rc2)
8294                 return rc2;
8295         if (rc3)
8296                 return rc3;
8297         if (inacc)
8298                 return -EIO;
8299
8300         return 0;
8301 }
8302
8303 static int lfs_project(int argc, char **argv)
8304 {
8305         int ret = 0, err = 0, c, i;
8306         struct project_handle_control phc = { 0 };
8307         enum lfs_project_ops_t op;
8308
8309         phc.newline = true;
8310         phc.assign_projid = false;
8311         /* default action */
8312         op = LFS_PROJECT_LIST;
8313
8314         while ((c = getopt(argc, argv, "p:cCsdkr0")) != -1) {
8315                 switch (c) {
8316                 case 'c':
8317                         if (op != LFS_PROJECT_LIST) {
8318                                 fprintf(stderr,
8319                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8320                                         progname);
8321                                 return CMD_HELP;
8322                         }
8323
8324                         op = LFS_PROJECT_CHECK;
8325                         break;
8326                 case 'C':
8327                         if (op != LFS_PROJECT_LIST) {
8328                                 fprintf(stderr,
8329                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8330                                         progname);
8331                                 return CMD_HELP;
8332                         }
8333
8334                         op = LFS_PROJECT_CLEAR;
8335                         break;
8336                 case 's':
8337                         if (op != LFS_PROJECT_LIST) {
8338                                 fprintf(stderr,
8339                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8340                                         progname);
8341                                 return CMD_HELP;
8342                         }
8343
8344                         phc.set_inherit = true;
8345                         op = LFS_PROJECT_SET;
8346                         break;
8347                 case 'd':
8348                         phc.dironly = true;
8349                         break;
8350                 case 'k':
8351                         phc.keep_projid = true;
8352                         break;
8353                 case 'r':
8354                         phc.recursive = true;
8355                         break;
8356                 case 'p':
8357                         if (str2quotaid(&phc.projid, optarg)) {
8358                                 fprintf(stderr,
8359                                         "Invalid project ID: %s\n",
8360                                         optarg);
8361                                 return CMD_HELP;
8362                         }
8363
8364                         phc.assign_projid = true;
8365
8366                         break;
8367                 case '0':
8368                         phc.newline = false;
8369                         break;
8370                 default:
8371                         fprintf(stderr, "%s: invalid option '%c'\n",
8372                                 progname, optopt);
8373                         return CMD_HELP;
8374                 }
8375         }
8376
8377         if (phc.assign_projid && op == LFS_PROJECT_LIST) {
8378                 op = LFS_PROJECT_SET;
8379                 phc.set_projid = true;
8380         } else if (phc.assign_projid && op == LFS_PROJECT_SET) {
8381                 phc.set_projid = true;
8382         }
8383
8384         switch (op) {
8385         case LFS_PROJECT_CHECK:
8386                 if (phc.keep_projid) {
8387                         fprintf(stderr,
8388                                 "%s: '-k' is useless together with '-c'\n",
8389                                 progname);
8390                         return CMD_HELP;
8391                 }
8392                 break;
8393         case LFS_PROJECT_CLEAR:
8394                 if (!phc.newline) {
8395                         fprintf(stderr,
8396                                 "%s: '-0' is useless together with '-C'\n",
8397                                 progname);
8398                         return CMD_HELP;
8399                 }
8400                 if (phc.assign_projid) {
8401                         fprintf(stderr,
8402                                 "%s: '-p' is useless together with '-C'\n",
8403                                 progname);
8404                         return CMD_HELP;
8405                 }
8406                 break;
8407         case LFS_PROJECT_SET:
8408                 if (!phc.newline) {
8409                         fprintf(stderr,
8410                                 "%s: '-0' is useless together with '-s'\n",
8411                                 progname);
8412                         return CMD_HELP;
8413                 }
8414                 if (phc.keep_projid) {
8415                         fprintf(stderr,
8416                                 "%s: '-k' is useless together with '-s'\n",
8417                                 progname);
8418                         return CMD_HELP;
8419                 }
8420                 break;
8421         default:
8422                 if (!phc.newline) {
8423                         fprintf(stderr,
8424                                 "%s: '-0' is useless for list operations\n",
8425                                 progname);
8426                         return CMD_HELP;
8427                 }
8428                 break;
8429         }
8430
8431         argv += optind;
8432         argc -= optind;
8433         if (argc == 0) {
8434                 fprintf(stderr, "%s: missing file or directory target(s)\n",
8435                         progname);
8436                 return CMD_HELP;
8437         }
8438
8439         for (i = 0; i < argc; i++) {
8440                 switch (op) {
8441                 case LFS_PROJECT_CHECK:
8442                         err = lfs_project_check(argv[i], &phc);
8443                         break;
8444                 case LFS_PROJECT_LIST:
8445                         err = lfs_project_list(argv[i], &phc);
8446                         break;
8447                 case LFS_PROJECT_CLEAR:
8448                         err = lfs_project_clear(argv[i], &phc);
8449                         break;
8450                 case LFS_PROJECT_SET:
8451                         err = lfs_project_set(argv[i], &phc);
8452                         break;
8453                 default:
8454                         break;
8455                 }
8456                 if (err && !ret)
8457                         ret = err;
8458         }
8459
8460         return ret;
8461 }
8462
8463 static int lfs_quota(int argc, char **argv)
8464 {
8465         int c;
8466         char *mnt, *name = NULL;
8467         struct if_quotactl *qctl;
8468         char *obd_uuid;
8469         int rc = 0, rc1 = 0, verbose = 0, quiet = 0;
8470         __u32 valid = QC_GENERAL, idx = 0;
8471         bool human_readable = false;
8472         bool show_default = false;
8473         int qtype;
8474         bool show_pools = false;
8475         struct option long_opts[] = {
8476         { .val = LFS_POOL_OPT, .name = "pool", .has_arg = optional_argument },
8477         { .name = NULL } };
8478         char **poollist = NULL;
8479         char *buf = NULL;
8480         int poolcount, i;
8481
8482         qctl = calloc(1, sizeof(*qctl) + LOV_MAXPOOLNAME + 1);
8483         if (!qctl)
8484                 return -ENOMEM;
8485
8486         qctl->qc_cmd = LUSTRE_Q_GETQUOTA;
8487         qctl->qc_type = ALLQUOTA;
8488         obd_uuid = (char *)qctl->obd_uuid.uuid;
8489
8490         while ((c = getopt_long(argc, argv, "gGi:I:o:pPqtuUvh",
8491                 long_opts, NULL)) != -1) {
8492                 switch (c) {
8493                 case 'U':
8494                         show_default = true;
8495                 case 'u':
8496                         qtype = USRQUOTA;
8497                         goto quota_type;
8498                 case 'G':
8499                         show_default = true;
8500                 case 'g':
8501                         qtype = GRPQUOTA;
8502                         goto quota_type;
8503                 case 'P':
8504                         show_default = true;
8505                 case 'p':
8506                         qtype = PRJQUOTA;
8507 quota_type:
8508                         if (qctl->qc_type != ALLQUOTA) {
8509                                 fprintf(stderr,
8510                                         "%s quota: only one of -u, -g, or -p may be specified\n",
8511                                         progname);
8512                                 rc = CMD_HELP;
8513                                 goto out;
8514                         }
8515                         qctl->qc_type = qtype;
8516                         break;
8517                 case 't':
8518                         qctl->qc_cmd = LUSTRE_Q_GETINFO;
8519                         break;
8520                 case 'o':
8521                         valid = qctl->qc_valid = QC_UUID;
8522                         snprintf(obd_uuid, sizeof(*obd_uuid), "%s", optarg);
8523                         break;
8524                 case 'i':
8525                         valid = qctl->qc_valid = QC_MDTIDX;
8526                         idx = qctl->qc_idx = atoi(optarg);
8527                         if (idx == 0 && *optarg != '0') {
8528                                 fprintf(stderr,
8529                                         "%s quota: invalid MDT index '%s'\n",
8530                                         progname, optarg);
8531                                 rc = CMD_HELP;
8532                                 goto out;
8533                         }
8534                         break;
8535                 case 'I':
8536                         valid = qctl->qc_valid = QC_OSTIDX;
8537                         idx = qctl->qc_idx = atoi(optarg);
8538                         if (idx == 0 && *optarg != '0') {
8539                                 fprintf(stderr,
8540                                         "%s quota: invalid OST index '%s'\n",
8541                                         progname, optarg);
8542                                 rc = CMD_HELP;
8543                                 goto out;
8544                         }
8545                         break;
8546                 case 'v':
8547                         verbose = 1;
8548                         break;
8549                 case 'q':
8550                         quiet = 1;
8551                         break;
8552                 case 'h':
8553                         human_readable = true;
8554                         break;
8555                 case LFS_POOL_OPT:
8556                         if ((!optarg) && (argv[optind] != NULL) &&
8557                                 (argv[optind][0] != '-') &&
8558                                 (argv[optind][0] != '/')) {
8559                                 optarg = argv[optind++];
8560                                 if (lfs_verify_poolarg(optarg)) {
8561                                         rc = -EINVAL;
8562                                         goto out;
8563                                 }
8564                                 strncpy(qctl->qc_poolname, optarg,
8565                                         LOV_MAXPOOLNAME);
8566                                 if (qctl->qc_cmd == LUSTRE_Q_GETINFO)
8567                                         qctl->qc_cmd = LUSTRE_Q_GETINFOPOOL;
8568                                 else
8569                                         qctl->qc_cmd = LUSTRE_Q_GETQUOTAPOOL;
8570                                 break;
8571                         }
8572
8573                         /* optarg is NULL */
8574                         show_pools = true;
8575                         qctl->qc_cmd = LUSTRE_Q_GETQUOTAPOOL;
8576                         break;
8577                 default:
8578                         fprintf(stderr, "%s quota: unrecognized option '%s'\n",
8579                                 progname, argv[optind - 1]);
8580                         rc = CMD_HELP;
8581                         goto out;
8582                 }
8583         }
8584
8585         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
8586         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8587              qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) &&
8588              qctl->qc_type == ALLQUOTA &&
8589              optind == argc - 1 && !show_default) {
8590                 qctl->qc_idx = idx;
8591
8592                 for (qtype = USRQUOTA; qtype <= GRPQUOTA; qtype++) {
8593                         qctl->qc_type = qtype;
8594                         qctl->qc_valid = valid;
8595                         if (qtype == USRQUOTA) {
8596                                 qctl->qc_id = geteuid();
8597                                 rc = uid2name(&name, qctl->qc_id);
8598                         } else {
8599                                 qctl->qc_id = getegid();
8600                                 rc = gid2name(&name, qctl->qc_id);
8601                                 memset(&qctl->qc_dqblk, 0,
8602                                        sizeof(qctl->qc_dqblk));
8603                         }
8604                         if (rc)
8605                                 name = "<unknown>";
8606                         mnt = argv[optind];
8607                         rc1 = get_print_quota(mnt, name, qctl, verbose, quiet,
8608                                               human_readable, show_default);
8609                         if (rc1 && !rc)
8610                                 rc = rc1;
8611                 }
8612                 goto out;
8613         /* lfs quota -u username /path/to/lustre/mount */
8614         } else if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8615                    qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8616                 /* options should be followed by u/g-name and mntpoint */
8617                 if ((!show_default && optind + 2 != argc) ||
8618                     (show_default && optind + 1 != argc) ||
8619                     qctl->qc_type == ALLQUOTA) {
8620                         fprintf(stderr,
8621                                 "%s quota: name and mount point must be specified\n",
8622                                 progname);
8623                         rc = CMD_HELP;
8624                         goto out;
8625                 }
8626
8627                 if (!show_default) {
8628                         name = argv[optind++];
8629                         switch (qctl->qc_type) {
8630                         case USRQUOTA:
8631                                 rc = name2uid(&qctl->qc_id, name);
8632                                 break;
8633                         case GRPQUOTA:
8634                                 rc = name2gid(&qctl->qc_id, name);
8635                                 break;
8636                         case PRJQUOTA:
8637                                 rc = name2projid(&qctl->qc_id, name);
8638                                 break;
8639                         default:
8640                                 rc = -ENOTSUP;
8641                                 break;
8642                         }
8643                 } else {
8644                         qctl->qc_valid = QC_GENERAL;
8645                         qctl->qc_cmd = qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ?
8646                                         LUSTRE_Q_GETDEFAULT_POOL :
8647                                         LUSTRE_Q_GETDEFAULT;
8648                         qctl->qc_id = 0;
8649                 }
8650
8651                 if (rc) {
8652                         if (str2quotaid(&qctl->qc_id, name)) {
8653                                 fprintf(stderr, "%s quota: invalid id '%s'\n",
8654                                         progname, name);
8655                                 rc = CMD_HELP;
8656                                 goto out;
8657                         }
8658                 }
8659         } else if (optind + 1 != argc || qctl->qc_type == ALLQUOTA) {
8660                 fprintf(stderr, "%s quota: missing quota info argument(s)\n",
8661                         progname);
8662                 rc = CMD_HELP;
8663                 goto out;
8664         }
8665
8666         mnt = argv[optind];
8667         if (show_pools) {
8668                 char *p;
8669
8670                 i = 0;
8671                 rc = llapi_get_poolbuf(mnt, &buf, &poollist, &poolcount);
8672                 if (rc)
8673                         goto out;
8674
8675                 for (i = 0; i < poolcount; i++) {
8676                         p = memchr(poollist[i], '.', MAXNAMLEN);
8677                         if (!p) {
8678                                 fprintf(stderr, "bad string format %.*s\n",
8679                                         MAXNAMLEN, poollist[i]);
8680                                 rc = -EINVAL;
8681                                 goto out;
8682                         }
8683                         p++;
8684                         printf("Quotas for pool: %s\n", p);
8685                         strncpy(qctl->qc_poolname, p, LOV_MAXPOOLNAME);
8686                         rc = get_print_quota(mnt, name, qctl, verbose, quiet,
8687                                              human_readable, show_default);
8688                         if (rc)
8689                                 break;
8690                 }
8691                 goto out;
8692         }
8693
8694         rc = get_print_quota(mnt, name, qctl, verbose, quiet,
8695                              human_readable, show_default);
8696 out:
8697         free(buf);
8698         free(qctl);
8699         return rc;
8700 }
8701 #endif /* HAVE_SYS_QUOTA_H! */
8702
8703 static int flushctx_ioctl(char *mp)
8704 {
8705         int fd, rc;
8706
8707         fd = open(mp, O_RDONLY);
8708         if (fd == -1) {
8709                 fprintf(stderr, "flushctx: error open %s: %s\n",
8710                         mp, strerror(errno));
8711                 return -1;
8712         }
8713
8714         rc = ioctl(fd, LL_IOC_FLUSHCTX);
8715         if (rc == -1)
8716                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
8717                         mp, strerror(errno));
8718
8719         close(fd);
8720         return rc;
8721 }
8722
8723 static int lfs_flushctx(int argc, char **argv)
8724 {
8725         int     kdestroy = 0, reap = 0, c;
8726         char    mntdir[PATH_MAX] = {'\0'};
8727         int     index = 0;
8728         int     rc = 0;
8729
8730         while ((c = getopt(argc, argv, "kr")) != -1) {
8731                 switch (c) {
8732                 case 'k':
8733                         kdestroy = 1;
8734                         break;
8735                 case 'r':
8736                         reap = 1;
8737                         break;
8738                 default:
8739                         fprintf(stderr,
8740                                 "error: %s: option '-%c' unrecognized\n",
8741                                 argv[0], c);
8742                         return CMD_HELP;
8743                 }
8744         }
8745
8746         if (kdestroy) {
8747                 rc = system("kdestroy > /dev/null");
8748                 if (rc) {
8749                         rc = WEXITSTATUS(rc);
8750                         fprintf(stderr,
8751                                 "error destroying tickets: %d, continuing\n",
8752                                 rc);
8753                 }
8754         }
8755
8756         if (optind >= argc) {
8757                 /* flush for all mounted lustre fs. */
8758                 while (!llapi_search_mounts(NULL, index++, mntdir, NULL)) {
8759                         /* Check if we have a mount point */
8760                         if (mntdir[0] == '\0')
8761                                 continue;
8762
8763                         if (flushctx_ioctl(mntdir))
8764                                 rc = -1;
8765
8766                         mntdir[0] = '\0'; /* avoid matching in next loop */
8767                 }
8768         } else {
8769                 /* flush fs as specified */
8770                 while (optind < argc) {
8771                         if (flushctx_ioctl(argv[optind++]))
8772                                 rc = -1;
8773                 }
8774         }
8775
8776         if (reap) {
8777                 rc = system("keyctl reap > /dev/null");
8778                 if (rc != 0) {
8779                         rc = WEXITSTATUS(rc);
8780                         fprintf(stderr, "error reaping keyring: %d\n", rc);
8781                 }
8782         }
8783
8784         return rc;
8785 }
8786
8787 static int lfs_changelog(int argc, char **argv)
8788 {
8789         void *changelog_priv;
8790         struct changelog_rec *rec;
8791         long long startrec = 0, endrec = 0;
8792         char *mdd;
8793         struct option long_opts[] = {
8794                 { .val = 'f', .name = "follow", .has_arg = no_argument },
8795                 { .name = NULL } };
8796         char short_opts[] = "f";
8797         int rc, follow = 0;
8798
8799         while ((rc = getopt_long(argc, argv, short_opts,
8800                 long_opts, NULL)) != -1) {
8801                 switch (rc) {
8802                 case 'f':
8803                         follow++;
8804                         break;
8805                 default:
8806                         fprintf(stderr,
8807                                 "%s changelog: unrecognized option '%s'\n",
8808                                 progname, argv[optind - 1]);
8809                         return CMD_HELP;
8810                 }
8811         }
8812         if (optind >= argc) {
8813                 fprintf(stderr, "%s changelog: mdtname must be specified\n",
8814                         progname);
8815                 return CMD_HELP;
8816         }
8817
8818         mdd = argv[optind++];
8819         if (argc > optind) {
8820                 errno = 0;
8821                 startrec = strtoll(argv[optind++], NULL, 10);
8822                 if (errno != 0 || startrec < 0) {
8823                         fprintf(stderr,
8824                                 "%s changelog: bad startrec\n",
8825                                 progname);
8826                         return CMD_HELP;
8827                 }
8828         }
8829
8830         if (argc > optind) {
8831                 errno = 0;
8832                 endrec = strtoll(argv[optind++], NULL, 10);
8833                 if (errno != 0 || endrec < 0) {
8834                         fprintf(stderr,
8835                                 "%s changelog: bad endrec\n",
8836                                 progname);
8837                         return CMD_HELP;
8838                 }
8839         }
8840
8841         rc = llapi_changelog_start(&changelog_priv,
8842                                    CHANGELOG_FLAG_BLOCK |
8843                                    CHANGELOG_FLAG_JOBID |
8844                                    CHANGELOG_FLAG_EXTRA_FLAGS |
8845                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
8846                                    mdd, startrec);
8847         if (rc < 0) {
8848                 fprintf(stderr, "%s changelog: cannot start changelog: %s\n",
8849                         progname, strerror(errno = -rc));
8850                 return rc;
8851         }
8852
8853         rc = llapi_changelog_set_xflags(changelog_priv,
8854                                         CHANGELOG_EXTRA_FLAG_UIDGID |
8855                                         CHANGELOG_EXTRA_FLAG_NID |
8856                                         CHANGELOG_EXTRA_FLAG_OMODE |
8857                                         CHANGELOG_EXTRA_FLAG_XATTR);
8858         if (rc < 0) {
8859                 fprintf(stderr,
8860                         "%s changelog: cannot set xflags for changelog: %s\n",
8861                         progname, strerror(errno = -rc));
8862                 return rc;
8863         }
8864
8865         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
8866                 time_t secs;
8867                 struct tm ts;
8868
8869                 if (endrec && rec->cr_index > endrec) {
8870                         llapi_changelog_free(&rec);
8871                         break;
8872                 }
8873                 if (rec->cr_index < startrec) {
8874                         llapi_changelog_free(&rec);
8875                         continue;
8876                 }
8877
8878                 secs = rec->cr_time >> 30;
8879                 gmtime_r(&secs, &ts);
8880                 printf("%ju %02d%-5s %02d:%02d:%02d.%09d %04d.%02d.%02d "
8881                        "0x%x t="DFID, (uintmax_t)rec->cr_index, rec->cr_type,
8882                        changelog_type2str(rec->cr_type),
8883                        ts.tm_hour, ts.tm_min, ts.tm_sec,
8884                        (int)(rec->cr_time & ((1 << 30) - 1)),
8885                        ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday,
8886                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
8887
8888                 if (rec->cr_flags & CLF_JOBID) {
8889                         struct changelog_ext_jobid *jid =
8890                                 changelog_rec_jobid(rec);
8891
8892                         if (jid->cr_jobid[0] != '\0')
8893                                 printf(" j=%s", jid->cr_jobid);
8894                 }
8895
8896                 if (rec->cr_flags & CLF_EXTRA_FLAGS) {
8897                         struct changelog_ext_extra_flags *ef =
8898                                 changelog_rec_extra_flags(rec);
8899
8900                         printf(" ef=0x%llx",
8901                                (unsigned long long)ef->cr_extra_flags);
8902
8903                         if (ef->cr_extra_flags & CLFE_UIDGID) {
8904                                 struct changelog_ext_uidgid *uidgid =
8905                                         changelog_rec_uidgid(rec);
8906
8907                                 printf(" u=%llu:%llu",
8908                                        (unsigned long long)uidgid->cr_uid,
8909                                        (unsigned long long)uidgid->cr_gid);
8910                         }
8911                         if (ef->cr_extra_flags & CLFE_NID) {
8912                                 struct changelog_ext_nid *nid =
8913                                         changelog_rec_nid(rec);
8914
8915                                 printf(" nid=%s",
8916                                        libcfs_nid2str(nid->cr_nid));
8917                         }
8918
8919                         if (ef->cr_extra_flags & CLFE_OPEN) {
8920                                 struct changelog_ext_openmode *omd =
8921                                         changelog_rec_openmode(rec);
8922                                 char mode[] = "---";
8923
8924                                 /* exec mode must be exclusive */
8925                                 if (omd->cr_openflags & MDS_FMODE_EXEC) {
8926                                         mode[2] = 'x';
8927                                 } else {
8928                                         if (omd->cr_openflags & MDS_FMODE_READ)
8929                                                 mode[0] = 'r';
8930                                         if (omd->cr_openflags &
8931                                             (MDS_FMODE_WRITE |
8932                                              MDS_OPEN_TRUNC |
8933                                              MDS_OPEN_APPEND))
8934                                                 mode[1] = 'w';
8935                                 }
8936
8937                                 if (strcmp(mode, "---") != 0)
8938                                         printf(" m=%s", mode);
8939                         }
8940
8941                         if (ef->cr_extra_flags & CLFE_XATTR) {
8942                                 struct changelog_ext_xattr *xattr =
8943                                         changelog_rec_xattr(rec);
8944
8945                                 if (xattr->cr_xattr[0] != '\0')
8946                                         printf(" x=%s", xattr->cr_xattr);
8947                         }
8948                 }
8949
8950                 if (!fid_is_zero(&rec->cr_pfid))
8951                         printf(" p="DFID, PFID(&rec->cr_pfid));
8952                 if (rec->cr_namelen)
8953                         printf(" %.*s", rec->cr_namelen,
8954                                changelog_rec_name(rec));
8955
8956                 if (rec->cr_flags & CLF_RENAME) {
8957                         struct changelog_ext_rename *rnm =
8958                                 changelog_rec_rename(rec);
8959
8960                         if (!fid_is_zero(&rnm->cr_sfid))
8961                                 printf(" s="DFID" sp="DFID" %.*s",
8962                                        PFID(&rnm->cr_sfid),
8963                                        PFID(&rnm->cr_spfid),
8964                                        (int)changelog_rec_snamelen(rec),
8965                                        changelog_rec_sname(rec));
8966                 }
8967                 printf("\n");
8968
8969                 llapi_changelog_free(&rec);
8970         }
8971
8972         llapi_changelog_fini(&changelog_priv);
8973
8974         if (rc < 0)
8975                 fprintf(stderr, "%s changelog: cannot access changelog: %s\n",
8976                         progname, strerror(errno = -rc));
8977
8978         return (rc == 1 ? 0 : rc);
8979 }
8980
8981 static int lfs_changelog_clear(int argc, char **argv)
8982 {
8983         long long endrec;
8984         int rc;
8985
8986         if (argc != 4)
8987                 return CMD_HELP;
8988
8989         errno = 0;
8990         endrec = strtoll(argv[3], NULL, 10);
8991         if (errno != 0 || endrec < 0) {
8992                 fprintf(stderr,
8993                         "%s: bad endrec '%s'\n",
8994                         argv[0], argv[3]);
8995                 return CMD_HELP;
8996         }
8997
8998         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
8999
9000         if (rc == -EINVAL)
9001                 fprintf(stderr, "%s: record out of range: %llu\n",
9002                         argv[0], endrec);
9003         else if (rc == -ENOENT)
9004                 fprintf(stderr, "%s: no changelog user: %s\n",
9005                         argv[0], argv[2]);
9006         else if (rc)
9007                 fprintf(stderr, "%s error: %s\n", argv[0],
9008                         strerror(-rc));
9009
9010         if (rc)
9011                 errno = -rc;
9012
9013         return rc;
9014 }
9015
9016 static void rstripc(char *str, int c)
9017 {
9018         char *end = str + strlen(str);
9019
9020         for (; str < end && end[-1] == c; --end)
9021                 end[-1] = '\0';
9022 }
9023
9024 static int lfs_fid2path(int argc, char **argv)
9025 {
9026         struct option long_opts[] = {
9027                 { .val = 'c',   .name = "cur",  .has_arg = no_argument },
9028                 { .val = 'c',   .name = "current",      .has_arg = no_argument },
9029                 { .val = 'c',   .name = "print-link",   .has_arg = no_argument },
9030                 { .val = 'f',   .name = "print-fid",    .has_arg = no_argument },
9031                 { .val = 'l',   .name = "link", .has_arg = required_argument },
9032                 { .name = NULL } };
9033         char short_opts[] = "cfl:pr:";
9034         bool print_link = false;
9035         bool print_fid = false;
9036         bool print_mnt_dir;
9037         char mnt_dir[PATH_MAX] = "";
9038         int mnt_fd = -1;
9039         char *path_or_fsname;
9040         long long recno = -1;
9041         int linkno = -1;
9042         char *endptr = NULL;
9043         int rc = 0;
9044         int c;
9045         int i;
9046
9047         while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
9048                 switch (c) {
9049                 case 'c':
9050                         print_link = true;
9051                         break;
9052                 case 'f':
9053                         print_fid = true;
9054                         break;
9055                 case 'l':
9056                         errno = 0;
9057                         linkno = strtol(optarg, &endptr, 10);
9058                         if (errno != 0 || *endptr != '\0' || linkno < 0) {
9059                                 fprintf(stderr,
9060                                         "%s fid2path: invalid linkno '%s'\n",
9061                                         progname, optarg);
9062                                 return CMD_HELP;
9063                         }
9064                         break;
9065                 case 'r':
9066                         /* recno is something to do with changelogs
9067                          * that was never implemented. We just pass it
9068                          * through for the MDT to ignore.
9069                          */
9070                         errno = 0;
9071                         recno = strtoll(optarg, &endptr, 10);
9072                         if (errno != 0 || *endptr != '\0' || recno < 0) {
9073                                 fprintf(stderr,
9074                                         "%s fid2path: invalid recno '%s'\n",
9075                                         progname, optarg);
9076                                 return CMD_HELP;
9077                         }
9078                         break;
9079                 default:
9080                         fprintf(stderr,
9081                                 "%s fid2path: unrecognized option '%s'\n",
9082                                 progname, argv[optind - 1]);
9083                         return CMD_HELP;
9084                 }
9085         }
9086
9087         if (argc - optind < 2) {
9088                 fprintf(stderr,
9089                         "Usage: %s fid2path FSNAME|ROOT FID...\n",
9090                         progname);
9091                 return CMD_HELP;
9092         }
9093
9094         path_or_fsname = argv[optind];
9095
9096         if (*path_or_fsname == '/') {
9097                 print_mnt_dir = true;
9098                 rc = llapi_search_mounts(path_or_fsname, 0, mnt_dir, NULL);
9099         } else {
9100                 print_mnt_dir = false;
9101                 rc = llapi_search_rootpath(mnt_dir, path_or_fsname);
9102         }
9103
9104         if (rc < 0) {
9105                 fprintf(stderr,
9106                         "%s fid2path: cannot resolve mount point for '%s': %s\n",
9107                         progname, path_or_fsname, strerror(-rc));
9108                 goto out;
9109         }
9110
9111         mnt_fd = open(mnt_dir, O_RDONLY | O_DIRECTORY);
9112         if (mnt_fd < 0) {
9113                 fprintf(stderr,
9114                         "%s fid2path: cannot open mount point for '%s': %s\n",
9115                         progname, path_or_fsname, strerror(-rc));
9116                 goto out;
9117         }
9118
9119         /* Strip trailing slashes from mnt_dir. */
9120         rstripc(mnt_dir + 1, '/');
9121
9122         for (i = optind + 1; i < argc; i++) {
9123                 const char *fid_str = argv[i];
9124                 struct lu_fid fid;
9125                 int rc2;
9126
9127                 rc2 = llapi_fid_parse(fid_str, &fid, NULL);
9128                 if (rc2 < 0) {
9129                         fprintf(stderr,
9130                                 "%s fid2path: invalid FID '%s'\n",
9131                                 progname, fid_str);
9132                         if (rc == 0)
9133                                 rc = rc2;
9134
9135                         continue;
9136                 }
9137
9138                 int linktmp = (linkno >= 0) ? linkno : 0;
9139                 while (1) {
9140                         int oldtmp = linktmp;
9141                         long long rectmp = recno;
9142                         char path_buf[PATH_MAX];
9143
9144                         rc2 = llapi_fid2path_at(mnt_fd, &fid,
9145                                 path_buf, sizeof(path_buf), &rectmp, &linktmp);
9146                         if (rc2 < 0) {
9147                                 fprintf(stderr,
9148                                         "%s fid2path: cannot find %s %s: %s\n",
9149                                         progname, path_or_fsname, fid_str,
9150                                         strerror(-rc2));
9151                                 if (rc == 0)
9152                                         rc = rc2;
9153                                 break;
9154                         }
9155
9156                         if (print_fid)
9157                                 printf("%s ", fid_str);
9158
9159                         if (print_link)
9160                                 printf("%d ", linktmp);
9161
9162                         /* You may think this looks wrong or weird (and it is!)
9163                          * but we are actually trying to preserve the old quirky
9164                          * behaviors (enforced by our old quirky tests!) that
9165                          * make lfs so much fun to work on:
9166                          *
9167                          *   lustre 0x200000007:0x1:0x0 => "/"
9168                          *   /mnt/lustre 0x200000007:0x1:0x0 => "/mnt/lustre//"
9169                          *
9170                          * Note that llapi_fid2path() returns "" for the root
9171                          * FID. */
9172
9173                         printf("%s%s%s\n",
9174                                print_mnt_dir ? mnt_dir : "",
9175                                (print_mnt_dir || *path_buf == '\0') ? "/" : "",
9176                                path_buf);
9177
9178                         if (linkno >= 0)
9179                                 /* specified linkno */
9180                                 break;
9181
9182                         if (oldtmp == linktmp)
9183                                 /* no more links */
9184                                 break;
9185                 }
9186         }
9187 out:
9188         if (!(mnt_fd < 0))
9189                 close(mnt_fd);
9190
9191         return rc;
9192 }
9193
9194 static int lfs_path2fid(int argc, char **argv)
9195 {
9196         struct option long_opts[] = {
9197                 { .val = 'p', .name = "parents", .has_arg = no_argument },
9198                 { .name = NULL } };
9199         char            **path;
9200         const char        short_opts[] = "p";
9201         const char       *sep = "";
9202         struct lu_fid     fid;
9203         int               rc = 0;
9204         bool              show_parents = false;
9205
9206         while ((rc = getopt_long(argc, argv, short_opts,
9207                                  long_opts, NULL)) != -1) {
9208                 switch (rc) {
9209                 case 'p':
9210                         show_parents = true;
9211                         break;
9212                 default:
9213                         fprintf(stderr,
9214                                 "%s path2fid: unrecognized option '%s'\n",
9215                                 progname, argv[optind - 1]);
9216                         return CMD_HELP;
9217                 }
9218         }
9219
9220         if (optind > argc - 1) {
9221                 fprintf(stderr, "%s path2fid: FILE... must be specified\n",
9222                         progname);
9223                 return CMD_HELP;
9224         } else if (optind < argc - 1) {
9225                 sep = ": ";
9226         }
9227
9228         rc = 0;
9229         for (path = argv + optind; *path != NULL; path++) {
9230                 int err = 0;
9231
9232                 if (!show_parents) {
9233                         err = llapi_path2fid(*path, &fid);
9234                         if (!err)
9235                                 printf("%s%s"DFID"\n",
9236                                        *sep != '\0' ? *path : "", sep,
9237                                        PFID(&fid));
9238                 } else {
9239                         char            name[NAME_MAX + 1];
9240                         unsigned int    linkno = 0;
9241
9242                         while ((err = llapi_path2parent(*path, linkno, &fid,
9243                                                 name, sizeof(name))) == 0) {
9244                                 if (*sep != '\0' && linkno == 0)
9245                                         printf("%s%s", *path, sep);
9246
9247                                 printf("%s"DFID"/%s", linkno != 0 ? "\t" : "",
9248                                        PFID(&fid), name);
9249                                 linkno++;
9250                         }
9251
9252                         /* err == -ENODATA is end-of-loop */
9253                         if (linkno > 0 && err == -ENODATA) {
9254                                 printf("\n");
9255                                 err = 0;
9256                         }
9257                 }
9258
9259                 if (err) {
9260                         fprintf(stderr,
9261                                 "%s path2fid: cannot get %sfid for '%s': %s\n",
9262                                 progname, show_parents ? "parent " : "", *path,
9263                                 strerror(-err));
9264                         if (rc == 0) {
9265                                 rc = err;
9266                                 errno = -err;
9267                         }
9268                 }
9269         }
9270
9271         return rc;
9272 }
9273
9274 #define MAX_ERRNO       4095
9275 #define IS_ERR_VALUE(x) ((unsigned long)(x) >= (unsigned long)-MAX_ERRNO)
9276
9277 static int lfs_rmfid_and_show_errors(const char *device, struct fid_array *fa)
9278 {
9279         int rc, rc2, k;
9280
9281         rc = llapi_rmfid(device, fa);
9282         if (rc < 0) {
9283                 fprintf(stderr, "%s rmfid: cannot remove FIDs: %s\n",
9284                         progname, strerror(-rc));
9285                 return rc;
9286         }
9287
9288         for (k = 0; k < fa->fa_nr; k++) {
9289                 rc2 = (__s32)fa->fa_fids[k].f_ver;
9290                 if (!IS_ERR_VALUE(rc2))
9291                         continue;
9292
9293                 if (rc == 0)
9294                         rc = rc2;
9295
9296                 fa->fa_fids[k].f_ver = 0;
9297                 fprintf(stderr, "%s rmfid: cannot remove "DFID": %s\n",
9298                         progname, PFID(&fa->fa_fids[k]), strerror(-rc2));
9299         }
9300
9301         return rc;
9302 }
9303
9304 static int lfs_rmfid(int argc, char **argv)
9305 {
9306         char *fidstr, *device;
9307         int rc = 0, rc2, nr;
9308         struct fid_array *fa;
9309
9310         if (optind > argc - 1) {
9311                 fprintf(stderr, "%s rmfid: missing dirname\n", progname);
9312                 return CMD_HELP;
9313         }
9314
9315         device = argv[optind++];
9316
9317         nr = argc - optind;
9318         fa = malloc(offsetof(struct fid_array, fa_fids[nr + 1]));
9319         if (!fa)
9320                 return -ENOMEM;
9321
9322         fa->fa_nr = 0;
9323         rc = 0;
9324         while (optind < argc) {
9325                 int found;
9326
9327                 fidstr = argv[optind++];
9328                 while (*fidstr == '[')
9329                         fidstr++;
9330                 found = sscanf(fidstr, SFID, RFID(&fa->fa_fids[fa->fa_nr]));
9331                 if (found != 3) {
9332                         fprintf(stderr, "unrecognized FID: %s\n",
9333                                 argv[optind - 1]);
9334                         exit(1);
9335                 }
9336                 fa->fa_nr++;
9337                 if (fa->fa_nr == OBD_MAX_FIDS_IN_ARRAY) {
9338                         /* start another batch */
9339                         rc2 = lfs_rmfid_and_show_errors(device, fa);
9340                         if (rc2 && !rc)
9341                                 rc = rc2;
9342                         fa->fa_nr = 0;
9343                 }
9344         }
9345         if (fa->fa_nr) {
9346                 rc2 = lfs_rmfid_and_show_errors(device, fa);
9347                 if (rc2 && !rc)
9348                         rc = rc2;
9349         }
9350
9351         return rc;
9352 }
9353
9354 static int lfs_data_version(int argc, char **argv)
9355 {
9356         int data_version_flags = LL_DV_RD_FLUSH; /* Read by default */
9357         __u64 data_version;
9358         char *path;
9359         int fd;
9360         int rc;
9361         int c;
9362
9363         if (argc < 2) {
9364                 fprintf(stderr, "%s: FILE must be specified\n",
9365                         progname);
9366                 return CMD_HELP;
9367         }
9368
9369         while ((c = getopt(argc, argv, "hnrw")) != -1) {
9370                 switch (c) {
9371                 case 'n':
9372                         data_version_flags = 0;
9373                         break;
9374                 case 'r':
9375                         data_version_flags |= LL_DV_RD_FLUSH;
9376                         break;
9377                 case 'w':
9378                         data_version_flags |= LL_DV_WR_FLUSH;
9379                         break;
9380                 default:
9381                         fprintf(stderr,
9382                                 "%s data_version: unrecognized option '%s'\n",
9383                                 progname, argv[optind - 1]);
9384                         /* fallthrough */
9385                 case 'h':
9386                         return CMD_HELP;
9387                 }
9388         }
9389         if (optind == argc) {
9390                 fprintf(stderr, "%s data_version: FILE must be specified\n",
9391                         progname);
9392                 return CMD_HELP;
9393         }
9394
9395         path = argv[optind];
9396         fd = open(path, O_RDONLY);
9397         if (fd < 0) {
9398                 rc = -errno;
9399                 fprintf(stderr, "%s data_version: cannot open file '%s': %s\n",
9400                         progname, path, strerror(-rc));
9401                 return rc;
9402         }
9403
9404         rc = llapi_get_data_version(fd, &data_version, data_version_flags);
9405         if (rc < 0)
9406                 fprintf(stderr,
9407                         "%s data_version: cannot get version for '%s': %s\n",
9408                         progname, path, strerror(-rc));
9409         else
9410                 printf("%ju" "\n", (uintmax_t)data_version);
9411
9412         close(fd);
9413         return rc;
9414 }
9415
9416 static int lfs_hsm_state(int argc, char **argv)
9417 {
9418         int rc;
9419         int i = 1;
9420         char *path;
9421         struct hsm_user_state hus;
9422
9423         if (argc < 2)
9424                 return CMD_HELP;
9425
9426         do {
9427                 path = argv[i];
9428
9429                 rc = llapi_hsm_state_get(path, &hus);
9430                 if (rc) {
9431                         fprintf(stderr, "can't get hsm state for %s: %s\n",
9432                                 path, strerror(errno = -rc));
9433                         return rc;
9434                 }
9435
9436                 /* Display path name and status flags */
9437                 printf("%s: (0x%08x)", path, hus.hus_states);
9438
9439                 if (hus.hus_states & HS_RELEASED)
9440                         printf(" released");
9441                 if (hus.hus_states & HS_EXISTS)
9442                         printf(" exists");
9443                 if (hus.hus_states & HS_DIRTY)
9444                         printf(" dirty");
9445                 if (hus.hus_states & HS_ARCHIVED)
9446                         printf(" archived");
9447                 /* Display user-settable flags */
9448                 if (hus.hus_states & HS_NORELEASE)
9449                         printf(" never_release");
9450                 if (hus.hus_states & HS_NOARCHIVE)
9451                         printf(" never_archive");
9452                 if (hus.hus_states & HS_LOST)
9453                         printf(" lost_from_hsm");
9454
9455                 if (hus.hus_archive_id != 0)
9456                         printf(", archive_id:%d", hus.hus_archive_id);
9457                 printf("\n");
9458
9459         } while (++i < argc);
9460
9461         return 0;
9462 }
9463
9464 #define LFS_HSM_SET   0
9465 #define LFS_HSM_CLEAR 1
9466
9467 /**
9468  * Generic function to set or clear HSM flags.
9469  * Used by hsm_set and hsm_clear.
9470  *
9471  * @mode  if LFS_HSM_SET, set the flags, if LFS_HSM_CLEAR, clear the flags.
9472  */
9473 static int lfs_hsm_change_flags(int argc, char **argv, int mode)
9474 {
9475         struct option long_opts[] = {
9476         { .val = 'A',   .name = "archived",     .has_arg = no_argument },
9477         { .val = 'a',   .name = "noarchive",    .has_arg = no_argument },
9478         { .val = 'd',   .name = "dirty",        .has_arg = no_argument },
9479         { .val = 'e',   .name = "exists",       .has_arg = no_argument },
9480         { .val = 'h',   .name = "help",         .has_arg = no_argument },
9481         { .val = 'i',   .name = "archive-id",   .has_arg = required_argument },
9482         { .val = 'l',   .name = "lost",         .has_arg = no_argument },
9483         { .val = 'r',   .name = "norelease",    .has_arg = no_argument },
9484         { .name = NULL } };
9485         __u64 mask = 0;
9486         int c, rc;
9487         char *path;
9488         __u32 archive_id = 0;
9489         char *end = NULL;
9490
9491         if (argc < 3)
9492                 return CMD_HELP;
9493
9494         while ((c = getopt_long(argc, argv, "aAdehi:lr",
9495                                 long_opts, NULL)) != -1) {
9496                 switch (c) {
9497                 case 'l':
9498                         mask |= HS_LOST;
9499                         break;
9500                 case 'a':
9501                         mask |= HS_NOARCHIVE;
9502                         break;
9503                 case 'A':
9504                         mask |= HS_ARCHIVED;
9505                         break;
9506                 case 'r':
9507                         mask |= HS_NORELEASE;
9508                         break;
9509                 case 'd':
9510                         mask |= HS_DIRTY;
9511                         break;
9512                 case 'e':
9513                         mask |= HS_EXISTS;
9514                         break;
9515                 case 'i':
9516                         errno = 0;
9517                         archive_id = strtol(optarg, &end, 10);
9518                         if (errno != 0 || *end != '\0' || archive_id < 0) {
9519                                 fprintf(stderr,
9520                                         "%s: invalid archive_id: '%s'\n",
9521                                         progname, end);
9522                                 return CMD_HELP;
9523                         }
9524                         break;
9525                 default:
9526                         fprintf(stderr, "%s: unrecognized option '%s'\n",
9527                                 progname, argv[optind - 1]);
9528                         /* fallthrough */
9529                 case 'h':
9530                         return CMD_HELP;
9531                 }
9532         }
9533
9534         /* User should have specified a flag */
9535         if (mask == 0)
9536                 return CMD_HELP;
9537
9538         while (optind < argc) {
9539                 path = argv[optind];
9540
9541                 /* If mode == 0, this means we apply the mask. */
9542                 if (mode == LFS_HSM_SET)
9543                         rc = llapi_hsm_state_set(path, mask, 0, archive_id);
9544                 else
9545                         rc = llapi_hsm_state_set(path, 0, mask, 0);
9546
9547                 if (rc != 0) {
9548                         fprintf(stderr, "Can't change hsm flags for %s: %s\n",
9549                                 path, strerror(errno = -rc));
9550                         return rc;
9551                 }
9552                 optind++;
9553         }
9554
9555         return 0;
9556 }
9557
9558 static int lfs_hsm_action(int argc, char **argv)
9559 {
9560         int                              rc;
9561         int                              i = 1;
9562         char                            *path;
9563         struct hsm_current_action        hca;
9564         struct hsm_extent                he;
9565         enum hsm_user_action             hua;
9566         enum hsm_progress_states         hps;
9567
9568         if (argc < 2)
9569                 return CMD_HELP;
9570
9571         do {
9572                 path = argv[i];
9573
9574                 rc = llapi_hsm_current_action(path, &hca);
9575                 if (rc) {
9576                         fprintf(stderr, "can't get hsm action for %s: %s\n",
9577                                 path, strerror(errno = -rc));
9578                         return rc;
9579                 }
9580                 he = hca.hca_location;
9581                 hua = hca.hca_action;
9582                 hps = hca.hca_state;
9583
9584                 printf("%s: %s", path, hsm_user_action2name(hua));
9585
9586                 /* Skip file without action */
9587                 if (hca.hca_action == HUA_NONE) {
9588                         printf("\n");
9589                         continue;
9590                 }
9591
9592                 printf(" %s ", hsm_progress_state2name(hps));
9593
9594                 if ((hps == HPS_RUNNING) &&
9595                     (hua == HUA_ARCHIVE || hua == HUA_RESTORE))
9596                         printf("(%llu bytes moved)\n",
9597                                (unsigned long long)he.length);
9598                 else if ((he.offset + he.length) == LUSTRE_EOF)
9599                         printf("(from %llu to EOF)\n",
9600                                (unsigned long long)he.offset);
9601                 else
9602                         printf("(from %llu to %llu)\n",
9603                                (unsigned long long)he.offset,
9604                                (unsigned long long)(he.offset + he.length));
9605
9606         } while (++i < argc);
9607
9608         return 0;
9609 }
9610
9611 static int lfs_hsm_set(int argc, char **argv)
9612 {
9613         return lfs_hsm_change_flags(argc, argv, LFS_HSM_SET);
9614 }
9615
9616 static int lfs_hsm_clear(int argc, char **argv)
9617 {
9618         return lfs_hsm_change_flags(argc, argv, LFS_HSM_CLEAR);
9619 }
9620
9621 /**
9622  * Check file state and return its fid, to be used by lfs_hsm_request().
9623  *
9624  * \param[in]     file      Path to file to check
9625  * \param[in,out] fid       Pointer to allocated lu_fid struct.
9626  * \param[in,out] last_dev  Pointer to last device id used.
9627  *
9628  * \return 0 on success.
9629  */
9630 static int lfs_hsm_prepare_file(const char *file, struct lu_fid *fid,
9631                                 dev_t *last_dev)
9632 {
9633         struct stat     st;
9634         int             rc;
9635
9636         rc = lstat(file, &st);
9637         if (rc) {
9638                 fprintf(stderr, "Cannot stat %s: %s\n", file, strerror(errno));
9639                 return -errno;
9640         }
9641         /*
9642          * Checking for regular file as archiving as posix copytool
9643          * rejects archiving files other than regular files
9644          */
9645         if (!S_ISREG(st.st_mode)) {
9646                 fprintf(stderr, "error: \"%s\" is not a regular file\n", file);
9647                 return CMD_HELP;
9648         }
9649         /* A request should be ... */
9650         if (*last_dev != st.st_dev && *last_dev != 0) {
9651                 fprintf(stderr,
9652                         "All files should be on the same filesystem: %s\n",
9653                         file);
9654                 return -EINVAL;
9655         }
9656         *last_dev = st.st_dev;
9657
9658         rc = llapi_path2fid(file, fid);
9659         if (rc) {
9660                 fprintf(stderr, "Cannot read FID of %s: %s\n",
9661                         file, strerror(-rc));
9662                 return rc;
9663         }
9664         return 0;
9665 }
9666
9667 /* Fill an HSM HUR item with a given file name.
9668  *
9669  * If mntpath is set, then the filename is actually a FID, and no
9670  * lookup on the filesystem will be performed.
9671  *
9672  * \param[in]  hur         the user request to fill
9673  * \param[in]  idx         index of the item inside the HUR to fill
9674  * \param[in]  mntpath     mountpoint of Lustre
9675  * \param[in]  fname       filename (if mtnpath is NULL)
9676  *                         or FID (if mntpath is set)
9677  * \param[in]  last_dev    pointer to last device id used
9678  *
9679  * \retval 0 on success
9680  * \retval CMD_HELP or a negative errno on error
9681  */
9682 static int fill_hur_item(struct hsm_user_request *hur, unsigned int idx,
9683                          const char *mntpath, const char *fname,
9684                          dev_t *last_dev)
9685 {
9686         struct hsm_user_item *hui = &hur->hur_user_item[idx];
9687         int rc;
9688
9689         hui->hui_extent.length = -1;
9690
9691         if (mntpath) {
9692                 rc = llapi_fid_parse(fname, &hui->hui_fid, NULL);
9693                 if (rc)
9694                         fprintf(stderr, "hsm: '%s' is not a valid FID\n",
9695                                 fname);
9696         } else {
9697                 rc = lfs_hsm_prepare_file(fname, &hui->hui_fid, last_dev);
9698         }
9699
9700         if (rc == 0)
9701                 hur->hur_request.hr_itemcount++;
9702
9703         return rc;
9704 }
9705
9706 static int lfs_hsm_request(int argc, char **argv, int action)
9707 {
9708         struct option long_opts[] = {
9709         { .val = 'a',   .name = "archive",      .has_arg = required_argument },
9710         { .val = 'D',   .name = "data",         .has_arg = required_argument },
9711         { .val = 'h',   .name = "help",         .has_arg = no_argument },
9712         { .val = 'l',   .name = "filelist",     .has_arg = required_argument },
9713         { .val = 'm',   .name = "mntpath",      .has_arg = required_argument },
9714         { .name = NULL } };
9715         dev_t last_dev = 0;
9716         struct hsm_user_request *hur, *oldhur;
9717         int c, i;
9718         size_t len;
9719         int nbfile;
9720         char *line = NULL;
9721         char *filelist = NULL;
9722         char fullpath[PATH_MAX];
9723         char *opaque = NULL;
9724         int opaque_len = 0;
9725         int archive_id = 0;
9726         FILE *fp;
9727         int nbfile_alloc = 0;
9728         char *some_file = NULL;
9729         char *mntpath = NULL;
9730         int rc;
9731
9732         if (argc < 2)
9733                 return CMD_HELP;
9734
9735         while ((c = getopt_long(argc, argv, "a:D:hl:m:",
9736                                 long_opts, NULL)) != -1) {
9737                 switch (c) {
9738                 case 'l':
9739                         filelist = optarg;
9740                         break;
9741                 case 'D':
9742                         opaque = optarg;
9743                         break;
9744                 case 'a':
9745                         if (action != HUA_ARCHIVE &&
9746                             action != HUA_REMOVE) {
9747                                 fprintf(stderr,
9748                                         "error: -a is supported only when archiving or removing\n");
9749                                 return CMD_HELP;
9750                         }
9751                         archive_id = atoi(optarg);
9752                         break;
9753                 case 'm':
9754                         if (!some_file) {
9755                                 mntpath = optarg;
9756                                 some_file = strdup(optarg);
9757                         }
9758                         break;
9759                 default:
9760                         fprintf(stderr, "%s: unrecognized option '%s'\n",
9761                                 progname, argv[optind - 1]);
9762                         /* fallthrough */
9763                 case 'h':
9764                         return CMD_HELP;
9765                 }
9766         }
9767
9768         /* All remaining args are files, so we have at least nbfile */
9769         nbfile = argc - optind;
9770
9771         if ((nbfile == 0) && (!filelist))
9772                 return CMD_HELP;
9773
9774         if (opaque)
9775                 opaque_len = strlen(opaque);
9776
9777         /*
9778          * Alloc the request structure with enough place to store all files
9779          * from command line.
9780          */
9781         hur = llapi_hsm_user_request_alloc(nbfile, opaque_len);
9782         if (!hur) {
9783                 fprintf(stderr, "Cannot create the request: %s\n",
9784                         strerror(errno));
9785                 return errno;
9786         }
9787         nbfile_alloc = nbfile;
9788
9789         hur->hur_request.hr_action = action;
9790         hur->hur_request.hr_archive_id = archive_id;
9791         hur->hur_request.hr_flags = 0;
9792
9793         /* All remaining args are files, add them */
9794         if (nbfile != 0 && some_file == NULL)
9795                 some_file = strdup(argv[optind]);
9796
9797         for (i = 0; i < nbfile; i++) {
9798                 rc = fill_hur_item(hur, i, mntpath, argv[optind + i],
9799                                    &last_dev);
9800                 if (rc)
9801                         goto out_free;
9802         }
9803
9804         /* from here stop using nb_file, use hur->hur_request.hr_itemcount */
9805
9806         /* If a filelist was specified, read the filelist from it. */
9807         if (filelist) {
9808                 fp = fopen(filelist, "r");
9809                 if (!fp) {
9810                         fprintf(stderr, "Cannot read the file list %s: %s\n",
9811                                 filelist, strerror(errno));
9812                         rc = -errno;
9813                         goto out_free;
9814                 }
9815
9816                 while ((rc = getline(&line, &len, fp)) != -1) {
9817                         /*
9818                          * If allocated buffer was too small, get something
9819                          * larger
9820                          */
9821                         if (nbfile_alloc <= hur->hur_request.hr_itemcount) {
9822                                 ssize_t size;
9823
9824                                 nbfile_alloc = nbfile_alloc * 2 + 1;
9825                                 oldhur = hur;
9826                                 hur = llapi_hsm_user_request_alloc(nbfile_alloc,
9827                                                                    opaque_len);
9828                                 if (!hur) {
9829                                         fprintf(stderr,
9830                                                 "hsm: cannot allocate the request: %s\n",
9831                                                 strerror(errno));
9832                                         hur = oldhur;
9833                                         rc = -errno;
9834                                         fclose(fp);
9835                                         goto out_free;
9836                                 }
9837                                 size = hur_len(oldhur);
9838                                 if (size < 0) {
9839                                         fprintf(stderr,
9840                                                 "hsm: cannot allocate %u files + %u bytes data\n",
9841                                                 oldhur->hur_request.hr_itemcount,
9842                                                 oldhur->hur_request.hr_data_len);
9843                                         free(hur);
9844                                         hur = oldhur;
9845                                         rc = -E2BIG;
9846                                         fclose(fp);
9847                                         goto out_free;
9848                                 }
9849                                 memcpy(hur, oldhur, size);
9850                                 free(oldhur);
9851                         }
9852
9853                         /* Chop CR */
9854                         if (line[strlen(line) - 1] == '\n')
9855                                 line[strlen(line) - 1] = '\0';
9856
9857                         rc = fill_hur_item(hur, hur->hur_request.hr_itemcount,
9858                                            mntpath, line, &last_dev);
9859                         if (rc) {
9860                                 fclose(fp);
9861                                 goto out_free;
9862                         }
9863
9864                         if (!some_file) {
9865                                 some_file = line;
9866                                 line = NULL;
9867                         }
9868                 }
9869
9870                 rc = fclose(fp);
9871                 free(line);
9872         }
9873
9874         /* If a --data was used, add it to the request */
9875         hur->hur_request.hr_data_len = opaque_len;
9876         if (opaque)
9877                 memcpy(hur_data(hur), opaque, opaque_len);
9878
9879         /* Send the HSM request */
9880         if (realpath(some_file, fullpath) == NULL) {
9881                 fprintf(stderr, "Could not find path '%s': %s\n",
9882                         some_file, strerror(errno));
9883         }
9884         rc = llapi_hsm_request(fullpath, hur);
9885         if (rc) {
9886                 fprintf(stderr, "Cannot send HSM request (use of %s): %s\n",
9887                         some_file, strerror(-rc));
9888                 goto out_free;
9889         }
9890
9891 out_free:
9892         free(some_file);
9893         free(hur);
9894         return rc;
9895 }
9896
9897 static int lfs_hsm_archive(int argc, char **argv)
9898 {
9899         return lfs_hsm_request(argc, argv, HUA_ARCHIVE);
9900 }
9901
9902 static int lfs_hsm_restore(int argc, char **argv)
9903 {
9904         return lfs_hsm_request(argc, argv, HUA_RESTORE);
9905 }
9906
9907 static int lfs_hsm_release(int argc, char **argv)
9908 {
9909         return lfs_hsm_request(argc, argv, HUA_RELEASE);
9910 }
9911
9912 static int lfs_hsm_remove(int argc, char **argv)
9913 {
9914         return lfs_hsm_request(argc, argv, HUA_REMOVE);
9915 }
9916
9917 static int lfs_hsm_cancel(int argc, char **argv)
9918 {
9919         return lfs_hsm_request(argc, argv, HUA_CANCEL);
9920 }
9921
9922 static int lfs_swap_layouts(int argc, char **argv)
9923 {
9924         if (argc != 3)
9925                 return CMD_HELP;
9926
9927         return llapi_swap_layouts(argv[1], argv[2], 0, 0,
9928                                   SWAP_LAYOUTS_KEEP_MTIME |
9929                                   SWAP_LAYOUTS_KEEP_ATIME);
9930 }
9931
9932 static const char *const ladvise_names[] = LU_LADVISE_NAMES;
9933
9934 static const char *const lock_mode_names[] = LOCK_MODE_NAMES;
9935
9936 int lfs_get_mode(const char *string)
9937 {
9938         enum lock_mode_user mode;
9939
9940         for (mode = 0; mode < ARRAY_SIZE(lock_mode_names); mode++) {
9941                 if (lock_mode_names[mode] == NULL)
9942                         continue;
9943                 if (strcasecmp(string, lock_mode_names[mode]) == 0)
9944                         return mode;
9945         }
9946
9947         return -EINVAL;
9948 }
9949
9950 static enum lu_ladvise_type lfs_get_ladvice(const char *string)
9951 {
9952         enum lu_ladvise_type advice;
9953
9954         for (advice = 0;
9955              advice < ARRAY_SIZE(ladvise_names); advice++) {
9956                 if (ladvise_names[advice] == NULL)
9957                         continue;
9958                 if (strcmp(string, ladvise_names[advice]) == 0)
9959                         return advice;
9960         }
9961
9962         return LU_LADVISE_INVALID;
9963 }
9964
9965 static int lfs_ladvise(int argc, char **argv)
9966 {
9967         struct option long_opts[] = {
9968         { .val = 'a',   .name = "advice",       .has_arg = required_argument },
9969         { .val = 'b',   .name = "background",   .has_arg = no_argument },
9970         { .val = 'e',   .name = "end",          .has_arg = required_argument },
9971         { .val = 'h',   .name = "help",         .has_arg = no_argument },
9972         { .val = 'l',   .name = "length",       .has_arg = required_argument },
9973         { .val = 'm',   .name = "mode",         .has_arg = required_argument },
9974         { .val = 's',   .name = "start",        .has_arg = required_argument },
9975         { .val = 'u',   .name = "unset",        .has_arg = no_argument },
9976         { .name = NULL } };
9977         struct llapi_lu_ladvise advice;
9978         enum lu_ladvise_type advice_type = LU_LADVISE_INVALID;
9979         unsigned long long start = 0;
9980         unsigned long long end = LUSTRE_EOF;
9981         unsigned long long length = 0;
9982         unsigned long long size_units;
9983         unsigned long long flags = 0;
9984         int c, fd, rc = 0;
9985         const char *path;
9986         int mode = 0;
9987
9988         optind = 0;
9989         while ((c = getopt_long(argc, argv, "a:be:hl:m:s:u",
9990                                 long_opts, NULL)) != -1) {
9991                 switch (c) {
9992                 case 'a':
9993                         advice_type = lfs_get_ladvice(optarg);
9994                         if (advice_type == LU_LADVISE_INVALID) {
9995                                 fprintf(stderr,
9996                                         "%s: invalid advice type '%s'\n",
9997                                         progname, optarg);
9998                                 fprintf(stderr, "Valid types:");
9999
10000                                 for (advice_type = 0;
10001                                      advice_type < ARRAY_SIZE(ladvise_names);
10002                                      advice_type++) {
10003                                         if (ladvise_names[advice_type] == NULL)
10004                                                 continue;
10005                                         fprintf(stderr, " %s",
10006                                                 ladvise_names[advice_type]);
10007                                 }
10008                                 fprintf(stderr, "\n");
10009
10010                                 return CMD_HELP;
10011                         }
10012                         break;
10013                 case 'b':
10014                         flags |= LF_ASYNC;
10015                         break;
10016                 case 'u':
10017                         flags |= LF_UNSET;
10018                         break;
10019                 case 'e':
10020                         size_units = 1;
10021                         rc = llapi_parse_size(optarg, &end,
10022                                               &size_units, 0);
10023                         if (rc) {
10024                                 fprintf(stderr, "%s: bad end offset '%s'\n",
10025                                         argv[0], optarg);
10026                                 return CMD_HELP;
10027                         }
10028                         break;
10029                 case 's':
10030                         size_units = 1;
10031                         rc = llapi_parse_size(optarg, &start,
10032                                               &size_units, 0);
10033                         if (rc) {
10034                                 fprintf(stderr,
10035                                         "%s: bad start offset '%s'\n",
10036                                         argv[0], optarg);
10037                                 return CMD_HELP;
10038                         }
10039                         break;
10040                 case 'l':
10041                         size_units = 1;
10042                         rc = llapi_parse_size(optarg, &length,
10043                                               &size_units, 0);
10044                         if (rc) {
10045                                 fprintf(stderr, "%s: bad length '%s'\n",
10046                                         argv[0], optarg);
10047                                 return CMD_HELP;
10048                         }
10049                         break;
10050                 case 'm':
10051                         mode = lfs_get_mode(optarg);
10052                         if (mode < 0) {
10053                                 fprintf(stderr,
10054                                         "%s: bad mode '%s', valid modes are READ or WRITE\n",
10055                                         argv[0], optarg);
10056                                 return CMD_HELP;
10057                         }
10058                         break;
10059                 default:
10060                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10061                                 progname, argv[optind - 1]);
10062                         /* fallthrough */
10063                 case 'h':
10064                         return CMD_HELP;
10065                 }
10066         }
10067
10068         if (advice_type == LU_LADVISE_INVALID) {
10069                 fprintf(stderr, "%s: please give an advice type\n", argv[0]);
10070                 fprintf(stderr, "Valid types:");
10071                 for (advice_type = 0; advice_type < ARRAY_SIZE(ladvise_names);
10072                      advice_type++) {
10073                         if (ladvise_names[advice_type] == NULL)
10074                                 continue;
10075                         fprintf(stderr, " %s", ladvise_names[advice_type]);
10076                 }
10077                 fprintf(stderr, "\n");
10078                 return CMD_HELP;
10079         }
10080
10081         if (advice_type == LU_LADVISE_LOCKNOEXPAND) {
10082                 fprintf(stderr,
10083                         "%s: Lock no expand advice is a per file descriptor advice, so when called from lfs, it does nothing.\n",
10084                         argv[0]);
10085                 return CMD_HELP;
10086         }
10087
10088         if (argc <= optind) {
10089                 fprintf(stderr, "%s: please give one or more file names\n",
10090                         argv[0]);
10091                 return CMD_HELP;
10092         }
10093
10094         if (end != LUSTRE_EOF && length != 0 && end != start + length) {
10095                 fprintf(stderr, "%s: conflicting arguments of -l and -e\n",
10096                         argv[0]);
10097                 return CMD_HELP;
10098         }
10099
10100         if (end == LUSTRE_EOF && length != 0)
10101                 end = start + length;
10102
10103         if (end <= start) {
10104                 fprintf(stderr, "%s: range [%llu, %llu] is invalid\n",
10105                         argv[0], start, end);
10106                 return CMD_HELP;
10107         }
10108
10109         if (advice_type != LU_LADVISE_LOCKAHEAD && mode != 0) {
10110                 fprintf(stderr, "%s: mode is only valid with lockahead\n",
10111                         argv[0]);
10112                 return CMD_HELP;
10113         }
10114
10115         if (advice_type == LU_LADVISE_LOCKAHEAD && mode == 0) {
10116                 fprintf(stderr, "%s: mode is required with lockahead\n",
10117                         argv[0]);
10118                 return CMD_HELP;
10119         }
10120
10121         while (optind < argc) {
10122                 int rc2;
10123
10124                 path = argv[optind++];
10125
10126                 fd = open(path, O_RDONLY);
10127                 if (fd < 0) {
10128                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10129                                 argv[0], path, strerror(errno));
10130                         rc2 = -errno;
10131                         goto next;
10132                 }
10133
10134                 advice.lla_start = start;
10135                 advice.lla_end = end;
10136                 advice.lla_advice = advice_type;
10137                 advice.lla_value1 = 0;
10138                 advice.lla_value2 = 0;
10139                 advice.lla_value3 = 0;
10140                 advice.lla_value4 = 0;
10141                 if (advice_type == LU_LADVISE_LOCKAHEAD) {
10142                         advice.lla_lockahead_mode = mode;
10143                         advice.lla_peradvice_flags = flags;
10144                 }
10145
10146                 rc2 = llapi_ladvise(fd, flags, 1, &advice);
10147                 close(fd);
10148                 if (rc2 < 0) {
10149                         fprintf(stderr,
10150                                 "%s: cannot give advice '%s' to file '%s': %s\n",
10151                                 argv[0], ladvise_names[advice_type],
10152                                 path, strerror(errno));
10153
10154                         goto next;
10155                 }
10156
10157 next:
10158                 if (rc == 0 && rc2 < 0)
10159                         rc = rc2;
10160         }
10161         return rc;
10162 }
10163
10164 static const char *const heat_names[] = LU_HEAT_NAMES;
10165
10166 static int lfs_heat_get(int argc, char **argv)
10167 {
10168         struct lu_heat *heat;
10169         int rc = 0, rc2;
10170         char *path;
10171         int fd;
10172         int i;
10173
10174         if (argc <= 1)
10175                 return CMD_HELP;
10176
10177         heat = calloc(sizeof(*heat) + sizeof(__u64) * OBD_HEAT_COUNT, 1);
10178         if (!heat) {
10179                 fprintf(stderr, "%s: memory allocation failed\n", argv[0]);
10180                 return -ENOMEM;
10181         }
10182
10183         optind = 1;
10184         while (optind < argc) {
10185                 path = argv[optind++];
10186
10187                 fd = open(path, O_RDONLY);
10188                 if (fd < 0) {
10189                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10190                                 argv[0], path, strerror(errno));
10191                         rc2 = -errno;
10192                         goto next;
10193                 }
10194
10195                 heat->lh_count = OBD_HEAT_COUNT;
10196                 rc2 = llapi_heat_get(fd, heat);
10197                 close(fd);
10198                 if (rc2 < 0) {
10199                         fprintf(stderr,
10200                                 "%s: cannot get heat of file '%s': %s\n",
10201                                 argv[0], path, strerror(errno));
10202                         goto next;
10203                 }
10204
10205                 printf("flags: %x\n", heat->lh_flags);
10206                 for (i = 0; i < heat->lh_count; i++)
10207                         printf("%s: %llu\n", heat_names[i],
10208                                (unsigned long long)heat->lh_heat[i]);
10209 next:
10210                 if (rc == 0 && rc2 < 0)
10211                         rc = rc2;
10212         }
10213
10214         free(heat);
10215         return rc;
10216 }
10217
10218 static int lfs_heat_set(int argc, char **argv)
10219 {
10220         struct option long_opts[] = {
10221         { .val = 'c',   .name = "clear",        .has_arg = no_argument },
10222         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10223         { .val = 'o',   .name = "off",          .has_arg = no_argument },
10224         { .val = 'O',   .name = "on",           .has_arg = no_argument },
10225         { .name = NULL } };
10226         enum lu_heat_flag flags = 0;
10227         int rc = 0, rc2;
10228         char *path;
10229         int fd;
10230         int c;
10231
10232         if (argc <= 1)
10233                 return CMD_HELP;
10234
10235         optind = 0;
10236         while ((c = getopt_long(argc, argv, "choO", long_opts, NULL)) != -1) {
10237                 switch (c) {
10238                 case 'c':
10239                         flags |= LU_HEAT_FLAG_CLEAR;
10240                         break;
10241                 case 'o':
10242                         flags |= LU_HEAT_FLAG_CLEAR;
10243                         flags |= LU_HEAT_FLAG_OFF;
10244                         break;
10245                 case 'O':
10246                         flags &= ~LU_HEAT_FLAG_OFF;
10247                         break;
10248                 default:
10249                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10250                                 progname, argv[optind - 1]);
10251                         /* fallthrough */
10252                 case 'h':
10253                         return CMD_HELP;
10254                 }
10255         }
10256
10257         if (argc <= optind) {
10258                 fprintf(stderr, "%s: please give one or more file names\n",
10259                         argv[0]);
10260                 return CMD_HELP;
10261         }
10262
10263         while (optind < argc) {
10264                 path = argv[optind++];
10265
10266                 fd = open(path, O_RDONLY);
10267                 if (fd < 0) {
10268                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10269                                 argv[0], path, strerror(errno));
10270                         rc2 = -errno;
10271                         goto next;
10272                 }
10273
10274                 rc2 = llapi_heat_set(fd, flags);
10275                 close(fd);
10276                 if (rc2 < 0) {
10277                         fprintf(stderr,
10278                                 "%s: cannot setflags heat of file '%s': %s\n",
10279                                 argv[0], path, strerror(errno));
10280                         goto next;
10281                 }
10282 next:
10283                 if (rc == 0 && rc2 < 0)
10284                         rc = rc2;
10285         }
10286         return rc;
10287 }
10288
10289 /**
10290  * The input string contains a comma delimited list of component ids and
10291  * ranges, for example "1,2-4,7".
10292  */
10293 static int parse_mirror_ids(__u16 *ids, int size, char *arg)
10294 {
10295         bool end_of_loop = false;
10296         char *ptr = NULL;
10297         int nr = 0;
10298         int rc;
10299
10300         if (!arg)
10301                 return -EINVAL;
10302
10303         while (!end_of_loop) {
10304                 int start_index;
10305                 int end_index;
10306                 int i;
10307                 char *endptr = NULL;
10308
10309                 rc = -EINVAL;
10310                 ptr = strchrnul(arg, ',');
10311                 end_of_loop = *ptr == '\0';
10312                 *ptr = '\0';
10313
10314                 start_index = strtol(arg, &endptr, 0);
10315                 if (endptr == arg) /* no data at all */
10316                         break;
10317                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
10318                         break;
10319                 if (start_index < 0)
10320                         break;
10321
10322                 end_index = start_index;
10323                 if (*endptr == '-') {
10324                         end_index = strtol(endptr + 1, &endptr, 0);
10325                         if (*endptr != '\0')
10326                                 break;
10327                         if (end_index < start_index)
10328                                 break;
10329                 }
10330
10331                 for (i = start_index; i <= end_index && size > 0; i++) {
10332                         int j;
10333
10334                         /* remove duplicate */
10335                         for (j = 0; j < nr; j++) {
10336                                 if (ids[j] == i)
10337                                         break;
10338                         }
10339                         if (j == nr) { /* no duplicate */
10340                                 ids[nr++] = i;
10341                                 --size;
10342                         }
10343                 }
10344
10345                 if (size == 0 && i < end_index)
10346                         break;
10347
10348                 *ptr = ',';
10349                 arg = ++ptr;
10350                 rc = 0;
10351         }
10352         if (!end_of_loop && ptr)
10353                 *ptr = ',';
10354
10355         return rc < 0 ? rc : nr;
10356 }
10357
10358 /**
10359  * struct verify_mirror_id - Mirror id to be verified.
10360  * @mirror_id:   A specified mirror id.
10361  * @is_valid_id: @mirror_id is valid or not in the mirrored file.
10362  */
10363 struct verify_mirror_id {
10364         __u16 mirror_id;
10365         bool is_valid_id;
10366 };
10367
10368 /**
10369  * compare_mirror_ids() - Compare mirror ids.
10370  * @layout: Mirror component list.
10371  * @cbdata: Callback data in verify_mirror_id structure.
10372  *
10373  * This is a callback function called by llapi_layout_comp_iterate()
10374  * to compare the specified mirror id with the one in the current
10375  * component of @layout. If they are the same, then the specified
10376  * mirror id is valid.
10377  *
10378  * Return: a negative error code on failure or
10379  *         LLAPI_LAYOUT_ITER_CONT: Proceed iteration
10380  *         LLAPI_LAYOUT_ITER_STOP: Stop iteration
10381  */
10382 static inline
10383 int compare_mirror_ids(struct llapi_layout *layout, void *cbdata)
10384 {
10385         struct verify_mirror_id *mirror_id_cbdata =
10386                                  (struct verify_mirror_id *)cbdata;
10387         uint32_t mirror_id;
10388         int rc = 0;
10389
10390         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
10391         if (rc < 0) {
10392                 rc = -errno;
10393                 fprintf(stderr,
10394                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
10395                         progname, strerror(errno));
10396                 return rc;
10397         }
10398
10399         if (mirror_id_cbdata->mirror_id == mirror_id) {
10400                 mirror_id_cbdata->is_valid_id = true;
10401                 return LLAPI_LAYOUT_ITER_STOP;
10402         }
10403
10404         return LLAPI_LAYOUT_ITER_CONT;
10405 }
10406
10407 /**
10408  * verify_mirror_ids() - Verify specified mirror ids.
10409  * @fname:      Mirrored file name.
10410  * @mirror_ids: Specified mirror ids to be verified.
10411  * @ids_nr:     Number of specified mirror ids.
10412  *
10413  * This function verifies that specified @mirror_ids are valid
10414  * in the mirrored file @fname.
10415  *
10416  * Return: 0 on success or a negative error code on failure.
10417  */
10418 static inline
10419 int verify_mirror_ids(const char *fname, __u16 *mirror_ids, int ids_nr)
10420 {
10421         struct llapi_layout *layout = NULL;
10422         struct verify_mirror_id mirror_id_cbdata = { 0 };
10423         struct stat stbuf;
10424         uint32_t flr_state;
10425         int i;
10426         int fd;
10427         int rc = 0;
10428         int rc2 = 0;
10429
10430         if (ids_nr <= 0)
10431                 return -EINVAL;
10432
10433         if (stat(fname, &stbuf) < 0) {
10434                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
10435                         progname, fname, strerror(errno));
10436                 rc = -errno;
10437                 goto error;
10438         }
10439
10440         if (!S_ISREG(stbuf.st_mode)) {
10441                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
10442                         progname, fname);
10443                 rc = -EINVAL;
10444                 goto error;
10445         }
10446
10447         fd = open(fname, O_DIRECT | O_RDONLY);
10448         if (fd < 0) {
10449                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
10450                         progname, fname, strerror(errno));
10451                 rc = -errno;
10452                 goto error;
10453         }
10454
10455         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
10456         if (rc < 0) {
10457                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
10458                         progname, fname, strerror(errno));
10459                 goto close_fd;
10460         }
10461
10462         layout = llapi_layout_get_by_fd(fd, 0);
10463         if (!layout) {
10464                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
10465                         progname, fname, strerror(errno));
10466                 rc = -errno;
10467                 llapi_lease_release(fd);
10468                 goto close_fd;
10469         }
10470
10471         rc = llapi_layout_flags_get(layout, &flr_state);
10472         if (rc < 0) {
10473                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
10474                         progname, fname, strerror(errno));
10475                 rc = -errno;
10476                 goto free_layout;
10477         }
10478
10479         flr_state &= LCM_FL_FLR_MASK;
10480         switch (flr_state) {
10481         case LCM_FL_NONE:
10482                 rc = -EINVAL;
10483                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
10484                         progname, fname, llapi_layout_flags_string(flr_state));
10485                 goto free_layout;
10486         default:
10487                 break;
10488         }
10489
10490         rc2 = 0;
10491         for (i = 0; i < ids_nr; i++) {
10492                 mirror_id_cbdata.mirror_id = mirror_ids[i];
10493                 mirror_id_cbdata.is_valid_id = false;
10494
10495                 rc = llapi_layout_comp_iterate(layout, compare_mirror_ids,
10496                                                &mirror_id_cbdata);
10497                 if (rc < 0) {
10498                         rc = -errno;
10499                         fprintf(stderr,
10500                                 "%s: '%s' failed to verify mirror id: %u.\n",
10501                                 progname, fname, mirror_ids[i]);
10502                         goto free_layout;
10503                 }
10504
10505                 if (!mirror_id_cbdata.is_valid_id) {
10506                         rc2 = -EINVAL;
10507                         fprintf(stderr,
10508                                 "%s: '%s' invalid specified mirror id: %u.\n",
10509                                 progname, fname, mirror_ids[i]);
10510                 }
10511         }
10512         rc = rc2;
10513
10514 free_layout:
10515         llapi_layout_free(layout);
10516         llapi_lease_release(fd);
10517 close_fd:
10518         close(fd);
10519 error:
10520         return rc;
10521 }
10522
10523 static inline
10524 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
10525                            __u16 *mirror_ids, int ids_nr)
10526 {
10527         struct llapi_resync_comp comp_array[1024] = { { 0 } };
10528         struct llapi_layout *layout;
10529         struct stat stbuf;
10530         uint32_t flr_state;
10531         uint64_t start;
10532         uint64_t end;
10533         int comp_size = 0;
10534         int idx;
10535         int fd;
10536         int rc;
10537         int rc2;
10538
10539         if (stat(fname, &stbuf) < 0) {
10540                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
10541                         progname, fname, strerror(errno));
10542                 rc = -errno;
10543                 goto error;
10544         }
10545         if (!S_ISREG(stbuf.st_mode)) {
10546                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
10547                         progname, fname);
10548                 rc = -EINVAL;
10549                 goto error;
10550         }
10551
10552         fd = open(fname, O_DIRECT | O_RDWR);
10553         if (fd < 0) {
10554                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
10555                         progname, fname, strerror(errno));
10556                 rc = -errno;
10557                 goto error;
10558         }
10559
10560         layout = llapi_layout_get_by_fd(fd, 0);
10561         if (!layout) {
10562                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
10563                         progname, fname, strerror(errno));
10564                 rc = -errno;
10565                 goto close_fd;
10566         }
10567
10568         rc = llapi_layout_flags_get(layout, &flr_state);
10569         if (rc) {
10570                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
10571                         progname, fname, strerror(errno));
10572                 rc = -errno;
10573                 goto free_layout;
10574         }
10575
10576         flr_state &= LCM_FL_FLR_MASK;
10577         if (flr_state == LCM_FL_NONE) {
10578                 rc = -EINVAL;
10579                 fprintf(stderr, "%s: '%s' is not a FLR file.\n",
10580                         progname, fname);
10581                 goto free_layout;
10582         }
10583
10584         /* get stale component info */
10585         comp_size = llapi_mirror_find_stale(layout, comp_array,
10586                                             ARRAY_SIZE(comp_array),
10587                                             mirror_ids, ids_nr);
10588         if (comp_size <= 0) {
10589                 rc = comp_size;
10590                 goto free_layout;
10591         }
10592
10593         ioc->lil_mode = LL_LEASE_WRLCK;
10594         ioc->lil_flags = LL_LEASE_RESYNC;
10595         rc = llapi_lease_set(fd, ioc);
10596         if (rc < 0) {
10597                 if (rc == -EALREADY)
10598                         rc = 0;
10599                 else
10600                         fprintf(stderr,
10601                             "%s: '%s' llapi_lease_get_ext resync failed: %s.\n",
10602                                 progname, fname, strerror(-rc));
10603                 goto free_layout;
10604         }
10605
10606         /* get the read range [start, end) */
10607         start = comp_array[0].lrc_start;
10608         end = comp_array[0].lrc_end;
10609         for (idx = 1; idx < comp_size; idx++) {
10610                 if (comp_array[idx].lrc_start < start)
10611                         start = comp_array[idx].lrc_start;
10612                 if (end < comp_array[idx].lrc_end)
10613                         end = comp_array[idx].lrc_end;
10614         }
10615
10616         rc = llapi_lease_check(fd);
10617         if (rc != LL_LEASE_WRLCK) {
10618                 fprintf(stderr, "%s: '%s' lost lease lock.\n",
10619                         progname, fname);
10620                 goto free_layout;
10621         }
10622
10623         rc = llapi_mirror_resync_many(fd, layout, comp_array, comp_size,
10624                                       start, end);
10625         if (rc < 0)
10626                 fprintf(stderr, "%s: '%s' llapi_mirror_resync_many: %s.\n",
10627                         progname, fname, strerror(-rc));
10628
10629         /* need to do the lease unlock even resync fails */
10630         ioc->lil_mode = LL_LEASE_UNLCK;
10631         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
10632         ioc->lil_count = 0;
10633         for (idx = 0; idx < comp_size; idx++) {
10634                 if (comp_array[idx].lrc_synced) {
10635                         ioc->lil_ids[ioc->lil_count] = comp_array[idx].lrc_id;
10636                         ioc->lil_count++;
10637                 }
10638         }
10639
10640         rc2 = llapi_lease_set(fd, ioc);
10641         /**
10642          * llapi_lease_set returns lease mode when it request to unlock
10643          * the lease lock.
10644          */
10645         if (rc2 <= 0) {
10646                 /* rc2 == 0 means lost lease lock */
10647                 if (rc2 == 0 && rc == 0)
10648                         rc = -EBUSY;
10649                 fprintf(stderr, "%s: resync file '%s' failed: %s.\n",
10650                         progname, fname,
10651                         rc2 == 0 ? "lost lease lock" : strerror(-rc2));
10652         }
10653
10654 free_layout:
10655         llapi_layout_free(layout);
10656 close_fd:
10657         close(fd);
10658 error:
10659         return rc;
10660 }
10661
10662 static inline int lfs_mirror_resync(int argc, char **argv)
10663 {
10664         struct option long_opts[] = {
10665         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10666         { .val = 'o',   .name = "only",         .has_arg = required_argument },
10667         { .name = NULL } };
10668         struct ll_ioc_lease *ioc = NULL;
10669         __u16 mirror_ids[128] = { 0 };
10670         int ids_nr = 0;
10671         int c;
10672         int rc = 0;
10673
10674         while ((c = getopt_long(argc, argv, "ho:", long_opts, NULL)) >= 0) {
10675                 switch (c) {
10676                 case 'o':
10677                         rc = parse_mirror_ids(mirror_ids,
10678                                         sizeof(mirror_ids) / sizeof(__u16),
10679                                         optarg);
10680                         if (rc < 0) {
10681                                 fprintf(stderr,
10682                                         "%s: bad mirror ids '%s'.\n",
10683                                         argv[0], optarg);
10684                                 goto error;
10685                         }
10686                         ids_nr = rc;
10687                         break;
10688                 default:
10689                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10690                                 progname, argv[optind - 1]);
10691                         /* fallthrough */
10692                 case 'h':
10693                         rc = CMD_HELP;
10694                         goto error;
10695                 }
10696         }
10697
10698         if (argc == optind) {
10699                 fprintf(stderr, "%s: no file name given.\n", argv[0]);
10700                 rc = CMD_HELP;
10701                 goto error;
10702         }
10703
10704         if (ids_nr > 0 && argc > optind + 1) {
10705                 fprintf(stderr,
10706                     "%s: option '--only' cannot be used upon multiple files.\n",
10707                         argv[0]);
10708                 rc = CMD_HELP;
10709                 goto error;
10710         }
10711
10712         if (ids_nr > 0) {
10713                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
10714                 if (rc < 0)
10715                         goto error;
10716         }
10717
10718         /* set the lease on the file */
10719         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
10720         if (!ioc) {
10721                 fprintf(stderr, "%s: cannot alloc id array for ioc: %s.\n",
10722                         argv[0], strerror(errno));
10723                 rc = -errno;
10724                 goto error;
10725         }
10726
10727         for (; optind < argc; optind++) {
10728                 rc = lfs_mirror_resync_file(argv[optind], ioc,
10729                                             mirror_ids, ids_nr);
10730                 /* ignore previous file's error, continue with next file */
10731
10732                 /* reset ioc */
10733                 memset(ioc, 0, sizeof(*ioc) + sizeof(__u32) * 4096);
10734         }
10735
10736         free(ioc);
10737 error:
10738         return rc;
10739 }
10740
10741 static inline int verify_mirror_id_by_fd(int fd, __u16 mirror_id)
10742 {
10743         struct llapi_layout *layout;
10744         int rc;
10745
10746         layout = llapi_layout_get_by_fd(fd, 0);
10747         if (!layout) {
10748                 fprintf(stderr, "could not get layout.\n");
10749                 return  -EINVAL;
10750         }
10751
10752         rc = llapi_layout_comp_iterate(layout, find_mirror_id, &mirror_id);
10753         if (rc < 0) {
10754                 fprintf(stderr, "failed to iterate layout\n");
10755                 llapi_layout_free(layout);
10756
10757                 return rc;
10758         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
10759                 fprintf(stderr, "does not find mirror with ID %u\n", mirror_id);
10760                 llapi_layout_free(layout);
10761
10762                 return -EINVAL;
10763         }
10764         llapi_layout_free(layout);
10765
10766         return 0;
10767 }
10768
10769 /**
10770  * Check whether two files are the same file
10771  * \retval      0  same file
10772  * \retval      1  not the same file
10773  * \retval      <0 error code
10774  */
10775 static inline int check_same_file(int fd, const char *f2)
10776 {
10777         struct stat stbuf1;
10778         struct stat stbuf2;
10779
10780         if (fstat(fd, &stbuf1) < 0)
10781                 return -errno;
10782
10783         if (stat(f2, &stbuf2) < 0)
10784                 return 1;
10785
10786         if (stbuf1.st_rdev == stbuf2.st_rdev &&
10787             stbuf1.st_ino == stbuf2.st_ino)
10788                 return 0;
10789
10790         return 1;
10791 }
10792
10793 static inline int lfs_mirror_read(int argc, char **argv)
10794 {
10795         int rc = CMD_HELP;
10796         __u16 mirror_id = 0;
10797         const char *outfile = NULL;
10798         char *fname;
10799         int fd = 0;
10800         int outfd;
10801         int c;
10802         void *buf;
10803         const size_t buflen = 4 << 20;
10804         off_t pos;
10805         struct option long_opts[] = {
10806         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10807         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
10808         { .val = 'o',   .name = "outfile",      .has_arg = required_argument },
10809         { .name = NULL } };
10810
10811         while ((c = getopt_long(argc, argv, "hN:o:", long_opts, NULL)) >= 0) {
10812                 char *end;
10813
10814                 switch (c) {
10815                 case 'N': {
10816                         unsigned long int id;
10817
10818                         errno = 0;
10819                         id = strtoul(optarg, &end, 0);
10820                         if (errno != 0 || *end != '\0' || id == 0 ||
10821                             id > UINT16_MAX) {
10822                                 fprintf(stderr,
10823                                         "%s %s: invalid mirror ID '%s'\n",
10824                                         progname, argv[0], optarg);
10825                                 return rc;
10826                         }
10827
10828                         mirror_id = (__u16)id;
10829                         break;
10830                 }
10831                 case 'o':
10832                         outfile = optarg;
10833                         break;
10834                 default:
10835                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10836                                 progname, argv[optind - 1]);
10837                         /* fallthrough */
10838                 case 'h':
10839                         return CMD_HELP;
10840                 }
10841         }
10842
10843         if (argc == optind) {
10844                 fprintf(stderr, "%s %s: no mirrored file provided\n",
10845                         progname, argv[0]);
10846                 return rc;
10847         } else if (argc > optind + 1) {
10848                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
10849                 return rc;
10850         }
10851
10852         if (mirror_id == 0) {
10853                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
10854                         progname, argv[0]);
10855                 return rc;
10856         }
10857
10858         /* open mirror file */
10859         fname = argv[optind];
10860         fd = open(fname, O_DIRECT | O_RDONLY);
10861         if (fd < 0) {
10862                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
10863                         progname, argv[0], fname, strerror(errno));
10864                 return rc;
10865         }
10866
10867         /* verify mirror id */
10868         rc = verify_mirror_id_by_fd(fd, mirror_id);
10869         if (rc) {
10870                 fprintf(stderr,
10871                         "%s %s: cannot find mirror with ID %u in '%s'\n",
10872                         progname, argv[0], mirror_id, fname);
10873                 goto close_fd;
10874         }
10875
10876         /* open output file - O_EXCL ensures output is not the same as input */
10877         if (outfile) {
10878                 outfd = open(outfile, O_EXCL | O_WRONLY | O_CREAT, 0644);
10879                 if (outfd < 0) {
10880                         fprintf(stderr, "%s %s: cannot create file '%s': %s\n",
10881                                 progname, argv[0], outfile, strerror(errno));
10882                         rc = -errno;
10883                         goto close_fd;
10884                 }
10885         } else {
10886                 outfd = STDOUT_FILENO;
10887         }
10888
10889         /* allocate buffer */
10890         rc = posix_memalign(&buf, sysconf(_SC_PAGESIZE), buflen);
10891         if (rc) {
10892                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
10893                                 progname, argv[0], rc);
10894                 goto close_outfd;
10895         }
10896
10897         pos = 0;
10898         while (1) {
10899                 ssize_t bytes_read;
10900                 ssize_t written = 0;
10901
10902                 bytes_read = llapi_mirror_read(fd, mirror_id, buf, buflen, pos);
10903                 if (bytes_read < 0) {
10904                         rc = bytes_read;
10905                         fprintf(stderr,
10906                                 "%s %s: fail to read data from mirror %u: %s\n",
10907                                 progname, argv[0], mirror_id, strerror(-rc));
10908                         goto free_buf;
10909                 }
10910
10911                 /* EOF reached */
10912                 if (bytes_read == 0)
10913                         break;
10914
10915                 while (written < bytes_read) {
10916                         ssize_t written2;
10917
10918                         written2 = write(outfd, buf + written,
10919                                          bytes_read - written);
10920                         if (written2 < 0) {
10921                                 fprintf(stderr,
10922                                         "%s %s: fail to write %s: %s\n",
10923                                         progname, argv[0], outfile ? : "STDOUT",
10924                                         strerror(errno));
10925                                 rc = -errno;
10926                                 goto free_buf;
10927                         }
10928                         written += written2;
10929                 }
10930
10931                 if (written != bytes_read) {
10932                         fprintf(stderr,
10933                 "%s %s: written %ld bytes does not match with %ld read.\n",
10934                                 progname, argv[0], written, bytes_read);
10935                         rc = -EIO;
10936                         goto free_buf;
10937                 }
10938
10939                 pos += bytes_read;
10940         }
10941
10942         fsync(outfd);
10943         rc = 0;
10944
10945 free_buf:
10946         free(buf);
10947 close_outfd:
10948         if (outfile)
10949                 close(outfd);
10950 close_fd:
10951         close(fd);
10952
10953         return rc;
10954 }
10955
10956 static inline int lfs_mirror_write(int argc, char **argv)
10957 {
10958         int rc = CMD_HELP;
10959         __u16 mirror_id = 0;
10960         const char *inputfile = NULL;
10961         char *fname;
10962         int fd = 0;
10963         int inputfd;
10964         int c;
10965         void *buf;
10966         const size_t buflen = 4 << 20;
10967         off_t pos;
10968         size_t page_size = sysconf(_SC_PAGESIZE);
10969         struct ll_ioc_lease_id ioc;
10970         struct option long_opts[] = {
10971         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10972         { .val = 'i',   .name = "inputfile",    .has_arg = required_argument },
10973         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
10974         { .name = NULL } };
10975
10976         while ((c = getopt_long(argc, argv, "hi:N:", long_opts, NULL)) >= 0) {
10977                 char *end;
10978
10979                 switch (c) {
10980                 case 'N': {
10981                         unsigned long int id;
10982
10983                         errno = 0;
10984                         id = strtoul(optarg, &end, 0);
10985                         if (errno != 0 || *end != '\0' || id == 0 ||
10986                             id > UINT16_MAX) {
10987                                 fprintf(stderr,
10988                                         "%s %s: invalid mirror ID '%s'\n",
10989                                         progname, argv[0], optarg);
10990                                 return rc;
10991                         }
10992
10993                         mirror_id = (__u16)id;
10994                         break;
10995                 }
10996                 case 'i':
10997                         inputfile = optarg;
10998                         break;
10999                 default:
11000                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11001                                 progname, argv[optind - 1]);
11002                         /* fallthrough */
11003                 case 'h':
11004                         return CMD_HELP;
11005                 }
11006         }
11007
11008         if (argc == optind) {
11009                 fprintf(stderr, "%s %s: no mirrored file provided\n",
11010                         progname, argv[0]);
11011                 return rc;
11012         } else if (argc > optind + 1) {
11013                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
11014                 return rc;
11015         }
11016
11017         if (mirror_id == 0) {
11018                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
11019                         progname, argv[0]);
11020                 return rc;
11021         }
11022
11023         /* open mirror file */
11024         fname = argv[optind];
11025         fd = open(fname, O_DIRECT | O_WRONLY);
11026         if (fd < 0) {
11027                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
11028                         progname, argv[0], fname, strerror(errno));
11029                 return rc;
11030         }
11031
11032         /* verify mirror id */
11033         rc = verify_mirror_id_by_fd(fd, mirror_id);
11034         if (rc) {
11035                 fprintf(stderr,
11036                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11037                         progname, argv[0], mirror_id, fname);
11038                 goto close_fd;
11039         }
11040
11041         /* open input file */
11042         if (inputfile) {
11043                 rc = check_same_file(fd, inputfile);
11044                 if (rc == 0) {
11045                         fprintf(stderr,
11046                         "%s %s: input file cannot be the mirrored file\n",
11047                                 progname, argv[0]);
11048                         goto close_fd;
11049                 }
11050                 if (rc < 0)
11051                         goto close_fd;
11052
11053                 inputfd = open(inputfile, O_RDONLY, 0644);
11054                 if (inputfd < 0) {
11055                         fprintf(stderr, "%s %s: cannot open file '%s': %s\n",
11056                                 progname, argv[0], inputfile, strerror(errno));
11057                         rc = -errno;
11058                         goto close_fd;
11059                 }
11060         } else {
11061                 inputfd = STDIN_FILENO;
11062         }
11063
11064         /* allocate buffer */
11065         rc = posix_memalign(&buf, page_size, buflen);
11066         if (rc) {
11067                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
11068                         progname, argv[0], rc);
11069                 goto close_inputfd;
11070         }
11071
11072         /* prepare target mirror components instantiation */
11073         ioc.lil_mode = LL_LEASE_WRLCK;
11074         ioc.lil_flags = LL_LEASE_RESYNC;
11075         ioc.lil_mirror_id = mirror_id;
11076         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
11077         if (rc < 0) {
11078                 fprintf(stderr,
11079                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
11080                         progname, argv[0], fname, strerror(errno));
11081                 goto free_buf;
11082         }
11083
11084         pos = 0;
11085         while (1) {
11086                 ssize_t bytes_read;
11087                 ssize_t written;
11088                 size_t to_write;
11089
11090                 rc = llapi_lease_check(fd);
11091                 if (rc != LL_LEASE_WRLCK) {
11092                         fprintf(stderr, "%s %s: '%s' lost lease lock\n",
11093                                 progname, argv[0], fname);
11094                         goto free_buf;
11095                 }
11096
11097                 bytes_read = read(inputfd, buf, buflen);
11098                 if (bytes_read < 0) {
11099                         rc = bytes_read;
11100                         fprintf(stderr,
11101                                 "%s %s: fail to read data from '%s': %s\n",
11102                                 progname, argv[0], inputfile ? : "STDIN",
11103                                 strerror(errno));
11104                         rc = -errno;
11105                         goto free_buf;
11106                 }
11107
11108                 /* EOF reached */
11109                 if (bytes_read == 0)
11110                         break;
11111
11112                 /* round up to page align to make direct IO happy. */
11113                 to_write = (bytes_read + page_size - 1) & ~(page_size - 1);
11114
11115                 written = llapi_mirror_write(fd, mirror_id, buf, to_write,
11116                                              pos);
11117                 if (written < 0) {
11118                         rc = written;
11119                         fprintf(stderr,
11120                               "%s %s: fail to write to mirror %u: %s\n",
11121                                 progname, argv[0], mirror_id,
11122                                 strerror(-rc));
11123                         goto free_buf;
11124                 }
11125
11126                 pos += bytes_read;
11127         }
11128
11129         if (pos & (page_size - 1)) {
11130                 rc = llapi_mirror_truncate(fd, mirror_id, pos);
11131                 if (rc < 0)
11132                         goto free_buf;
11133         }
11134
11135         ioc.lil_mode = LL_LEASE_UNLCK;
11136         ioc.lil_flags = LL_LEASE_RESYNC_DONE;
11137         ioc.lil_count = 0;
11138         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
11139         if (rc <= 0) {
11140                 if (rc == 0)
11141                         rc = -EBUSY;
11142                 fprintf(stderr,
11143                         "%s %s: release lease lock of '%s' failed: %s\n",
11144                         progname, argv[0], fname, strerror(errno));
11145                 goto free_buf;
11146         }
11147
11148         rc = 0;
11149
11150 free_buf:
11151         free(buf);
11152 close_inputfd:
11153         if (inputfile)
11154                 close(inputfd);
11155 close_fd:
11156         close(fd);
11157
11158         return rc;
11159 }
11160
11161 static inline int get_other_mirror_ids(int fd, __u16 *ids, __u16 exclude_id)
11162 {
11163         struct llapi_layout *layout;
11164         struct collect_ids_data cid = { .cid_ids = ids,
11165                                         .cid_count = 0,
11166                                         .cid_exclude = exclude_id, };
11167         int rc;
11168
11169         layout = llapi_layout_get_by_fd(fd, 0);
11170         if (!layout) {
11171                 fprintf(stderr, "could not get layout\n");
11172                 return -EINVAL;
11173         }
11174
11175         rc = llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
11176         if (rc < 0) {
11177                 fprintf(stderr, "failed to iterate layout\n");
11178                 llapi_layout_free(layout);
11179
11180                 return rc;
11181         }
11182         llapi_layout_free(layout);
11183
11184         return cid.cid_count;
11185 }
11186
11187 static inline int lfs_mirror_copy(int argc, char **argv)
11188 {
11189         int rc = CMD_HELP;
11190         __u16 read_mirror_id = 0;
11191         __u16 ids[128] = { 0 };
11192         int count = 0;
11193         struct llapi_layout *layout = NULL;
11194         struct llapi_resync_comp comp_array[1024] = { { 0 } };
11195         int comp_size = 0;
11196         char *fname;
11197         int fd = 0;
11198         int c;
11199         int i;
11200         ssize_t copied;
11201         struct ll_ioc_lease *ioc = NULL;
11202         struct ll_ioc_lease_id *resync_ioc;
11203         struct option long_opts[] = {
11204         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11205         { .val = 'i',   .name = "read-mirror",  .has_arg = required_argument },
11206         { .val = 'o',   .name = "write-mirror", .has_arg = required_argument },
11207         { .name = NULL } };
11208         char cmd[PATH_MAX];
11209
11210         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
11211         progname = cmd;
11212         while ((c = getopt_long(argc, argv, "hi:o:", long_opts, NULL)) >= 0) {
11213                 char *end;
11214
11215                 switch (c) {
11216                 case 'i': {
11217                         unsigned long int id;
11218
11219                         errno = 0;
11220                         id = strtoul(optarg, &end, 0);
11221                         if (errno != 0 || *end != '\0' || id == 0 ||
11222                             id > UINT16_MAX) {
11223                                 fprintf(stderr,
11224                                         "%s: invalid read mirror ID '%s'\n",
11225                                         progname, optarg);
11226                                 return rc;
11227                         }
11228
11229                         read_mirror_id = (__u16)id;
11230                         break;
11231                 }
11232                 case 'o':
11233                         if (!strcmp(optarg, "-1")) {
11234                                 /* specify all other mirrors */
11235                                 ids[0] = (__u16)-1;
11236                                 count = 1;
11237                         } else {
11238                                 count = parse_mirror_ids((__u16 *)ids,
11239                                                          ARRAY_SIZE(ids),
11240                                                          optarg);
11241                                 if (count < 0)
11242                                         return rc;
11243                         }
11244                         break;
11245                 default:
11246                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11247                                 progname, argv[optind - 1]);
11248                         /* fallthrough */
11249                 case 'h':
11250                         return CMD_HELP;
11251                 }
11252         }
11253
11254         if (argc == optind) {
11255                 fprintf(stderr, "%s %s: no mirrored file provided\n",
11256                         progname, argv[0]);
11257                 return rc;
11258         } else if (argc > optind + 1) {
11259                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
11260                 return rc;
11261         }
11262
11263         if (read_mirror_id == 0) {
11264                 fprintf(stderr,
11265                         "%s %s: no valid read mirror ID %d is provided\n",
11266                         progname, argv[0], read_mirror_id);
11267                 return rc;
11268         }
11269
11270         if (count == 0) {
11271                 fprintf(stderr,
11272                         "%s %s: no write mirror ID is provided\n",
11273                         progname, argv[0]);
11274                 return rc;
11275         }
11276
11277         for (i = 0; i < count; i++) {
11278                 if (read_mirror_id == ids[i]) {
11279                         fprintf(stderr,
11280                         "%s %s: read and write mirror ID cannot be the same\n",
11281                                 progname, argv[0]);
11282                         return rc;
11283                 }
11284         }
11285
11286         /* open mirror file */
11287         fname = argv[optind];
11288
11289         fd = open(fname, O_DIRECT | O_RDWR);
11290         if (fd < 0) {
11291                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
11292                         progname, argv[0], fname, strerror(errno));
11293                 return rc;
11294         }
11295
11296         /* write to all other mirrors */
11297         if (ids[0] == (__u16)-1) {
11298                 count = get_other_mirror_ids(fd, ids, read_mirror_id);
11299                 if (count <= 0) {
11300                         rc = count;
11301                         fprintf(stderr,
11302                         "%s %s: failed to get other mirror ids in '%s': %d\n",
11303                                 progname, argv[0], fname, rc);
11304                         goto close_fd;
11305                 }
11306         }
11307
11308         /* verify mirror id */
11309         rc = verify_mirror_id_by_fd(fd, read_mirror_id);
11310         if (rc) {
11311                 fprintf(stderr,
11312                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11313                         progname, argv[0], read_mirror_id, fname);
11314                 goto close_fd;
11315         }
11316
11317         for (i = 0; i < count; i++) {
11318                 rc = verify_mirror_id_by_fd(fd, ids[i]);
11319                 if (rc) {
11320                         fprintf(stderr,
11321                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11322                                 progname, argv[0], ids[i], fname);
11323                         goto close_fd;
11324                 }
11325         }
11326
11327         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
11328         if (!ioc) {
11329                 fprintf(stderr,
11330                         "%s %s: cannot alloc comp id array for ioc: %s\n",
11331                         progname, argv[0], strerror(errno));
11332                 rc = -errno;
11333                 goto close_fd;
11334         }
11335
11336         /* get stale component info */
11337         layout = llapi_layout_get_by_fd(fd, 0);
11338         if (!layout) {
11339                 fprintf(stderr, "%s %s: failed to get layout of '%s': %s\n",
11340                         progname, argv[0], fname, strerror(errno));
11341                 rc = -errno;
11342                 goto free_ioc;
11343         }
11344         comp_size = llapi_mirror_find_stale(layout, comp_array,
11345                                             ARRAY_SIZE(comp_array),
11346                                             ids, count);
11347         llapi_layout_free(layout);
11348         if (comp_size < 0) {
11349                 rc = comp_size;
11350                 goto free_ioc;
11351         }
11352
11353         /* prepare target mirror components instantiation */
11354         resync_ioc = (struct ll_ioc_lease_id *)ioc;
11355         resync_ioc->lil_mode = LL_LEASE_WRLCK;
11356         resync_ioc->lil_flags = LL_LEASE_RESYNC;
11357         if (count == 1)
11358                 resync_ioc->lil_mirror_id = ids[0];
11359         else
11360                 resync_ioc->lil_mirror_id = read_mirror_id | MIRROR_ID_NEG;
11361         rc = llapi_lease_set(fd, ioc);
11362         if (rc < 0) {
11363                 fprintf(stderr,
11364                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
11365                         progname, argv[0], fname, strerror(errno));
11366                 goto free_ioc;
11367         }
11368
11369         copied = llapi_mirror_copy_many(fd, read_mirror_id, ids, count);
11370         if (copied < 0) {
11371                 rc = copied;
11372                 fprintf(stderr, "%s %s: copy error: %d\n",
11373                         progname, argv[0], rc);
11374                 goto free_ioc;
11375         }
11376
11377         fprintf(stdout, "mirror copied successfully: ");
11378         for (i = 0; i < copied; i++)
11379                 fprintf(stdout, "%d ", ids[i]);
11380         fprintf(stdout, "\n");
11381
11382         ioc->lil_mode = LL_LEASE_UNLCK;
11383         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
11384         ioc->lil_count = 0;
11385         for (i = 0; i < comp_size; i++) {
11386                 int j;
11387
11388                 for (j = 0; j < copied; j++) {
11389                         if (comp_array[i].lrc_mirror_id != ids[j])
11390                                 continue;
11391
11392                         ioc->lil_ids[ioc->lil_count] = comp_array[i].lrc_id;
11393                         ioc->lil_count++;
11394                 }
11395         }
11396         rc = llapi_lease_set(fd, ioc);
11397         if (rc <= 0) {
11398                 if (rc == 0)
11399                         rc = -EBUSY;
11400                 fprintf(stderr,
11401                         "%s %s: release lease lock of '%s' failed: %s\n",
11402                         progname, argv[0], fname, strerror(errno));
11403                 goto free_ioc;
11404         }
11405
11406         rc = 0;
11407
11408 free_ioc:
11409         free(ioc);
11410 close_fd:
11411         close(fd);
11412
11413         return rc;
11414 }
11415
11416 /**
11417  * struct verify_chunk - Mirror chunk to be verified.
11418  * @chunk:        [start, end) of the chunk.
11419  * @mirror_count: Number of mirror ids in @mirror_id array.
11420  * @mirror_id:    Array of valid mirror ids that cover the chunk.
11421  */
11422 struct verify_chunk {
11423         struct lu_extent chunk;
11424         unsigned int mirror_count;
11425         __u16 mirror_id[LUSTRE_MIRROR_COUNT_MAX];
11426 };
11427
11428 /**
11429  * print_chunks() - Print chunk information.
11430  * @fname:       Mirrored file name.
11431  * @chunks:      Array of chunks.
11432  * @chunk_count: Number of chunks in @chunks array.
11433  *
11434  * This function prints [start, end) of each chunk in @chunks
11435  * for mirrored file @fname, and also prints the valid mirror ids
11436  * that cover the chunk.
11437  *
11438  * Return: void.
11439  */
11440 static inline
11441 void print_chunks(const char *fname, struct verify_chunk *chunks,
11442                   int chunk_count)
11443 {
11444         int i;
11445         int j;
11446
11447         fprintf(stdout, "Chunks to be verified in %s:\n", fname);
11448         for (i = 0; i < chunk_count; i++) {
11449                 fprintf(stdout, DEXT, PEXT(&chunks[i].chunk));
11450
11451                 if (chunks[i].mirror_count == 0)
11452                         fprintf(stdout, "\t[");
11453                 else {
11454                         fprintf(stdout, "\t[%u", chunks[i].mirror_id[0]);
11455                         for (j = 1; j < chunks[i].mirror_count; j++)
11456                                 fprintf(stdout, ", %u", chunks[i].mirror_id[j]);
11457                 }
11458                 fprintf(stdout, "]\t%u\n", chunks[i].mirror_count);
11459         }
11460         fprintf(stdout, "\n");
11461 }
11462
11463 /**
11464  * print_checksums() - Print CRC-32 checksum values.
11465  * @chunk: A chunk and its corresponding valid mirror ids.
11466  * @crc:   CRC-32 checksum values on the chunk for each valid mirror.
11467  *
11468  * This function prints CRC-32 checksum values on @chunk for
11469  * each valid mirror that covers it.
11470  *
11471  * Return: void.
11472  */
11473 static inline
11474 void print_checksums(struct verify_chunk *chunk, unsigned long *crc)
11475 {
11476         int i;
11477
11478         fprintf(stdout,
11479                 "CRC-32 checksum value for chunk "DEXT":\n",
11480                 PEXT(&chunk->chunk));
11481         for (i = 0; i < chunk->mirror_count; i++)
11482                 fprintf(stdout, "Mirror %u:\t%#lx\n",
11483                         chunk->mirror_id[i], crc[i]);
11484         fprintf(stdout, "\n");
11485 }
11486
11487 /**
11488  * filter_mirror_id() - Filter specified mirror ids.
11489  * @chunks:      Array of chunks.
11490  * @chunk_count: Number of chunks in @chunks array.
11491  * @mirror_ids:  Specified mirror ids to be verified.
11492  * @ids_nr:      Number of specified mirror ids.
11493  *
11494  * This function scans valid mirror ids that cover each chunk in @chunks
11495  * and filters specified mirror ids.
11496  *
11497  * Return: void.
11498  */
11499 static inline
11500 void filter_mirror_id(struct verify_chunk *chunks, int chunk_count,
11501                       __u16 *mirror_ids, int ids_nr)
11502 {
11503         int i;
11504         int j;
11505         int k;
11506         __u16 valid_id[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
11507         unsigned int valid_count = 0;
11508
11509         for (i = 0; i < chunk_count; i++) {
11510                 if (chunks[i].mirror_count == 0)
11511                         continue;
11512
11513                 valid_count = 0;
11514                 for (j = 0; j < ids_nr; j++) {
11515                         for (k = 0; k < chunks[i].mirror_count; k++) {
11516                                 if (chunks[i].mirror_id[k] == mirror_ids[j]) {
11517                                         valid_id[valid_count] = mirror_ids[j];
11518                                         valid_count++;
11519                                         break;
11520                                 }
11521                         }
11522                 }
11523
11524                 memcpy(chunks[i].mirror_id, valid_id,
11525                        sizeof(__u16) * valid_count);
11526                 chunks[i].mirror_count = valid_count;
11527         }
11528 }
11529
11530 /**
11531  * lfs_mirror_prepare_chunk() - Find mirror chunks to be verified.
11532  * @layout:      Mirror component list.
11533  * @chunks:      Array of chunks.
11534  * @chunks_size: Array size of @chunks.
11535  *
11536  * This function scans the components in @layout from offset 0 to LUSTRE_EOF
11537  * to find out chunk segments and store them in @chunks array.
11538  *
11539  * The @mirror_id array in each element of @chunks will store the valid
11540  * mirror ids that cover the chunk. If a mirror component covering the
11541  * chunk has LCME_FL_STALE or LCME_FL_OFFLINE flag, then the mirror id
11542  * will not be stored into the @mirror_id array, and the chunk for that
11543  * mirror will not be verified.
11544  *
11545  * The @mirror_count in each element of @chunks will store the number of
11546  * mirror ids in @mirror_id array. If @mirror_count is 0, it indicates the
11547  * chunk is invalid in all of the mirrors. And if @mirror_count is 1, it
11548  * indicates the chunk is valid in only one mirror. In both cases, the
11549  * chunk will not be verified.
11550  *
11551  * Here is an example:
11552  *
11553  *  0      1M     2M     3M     4M           EOF
11554  *  +------+-------------+--------------------+
11555  *  |      |             |      S             |       mirror1
11556  *  +------+------+------+------+-------------+
11557  *  |             |   S  |   S  |             |       mirror2
11558  *  +-------------+------+------+-------------+
11559  *
11560  * prepared @chunks array will contain 5 elements:
11561  * (([0, 1M), [1, 2], 2),
11562  *  ([1M, 2M), [1, 2], 2),
11563  *  ([2M, 3M), [1], 1),
11564  *  ([3M, 4M], [], 0),
11565  *  ([4M, EOF), [2], 1))
11566  *
11567  * Return: the actual array size of @chunks on success
11568  *         or a negative error code on failure.
11569  */
11570 static inline
11571 int lfs_mirror_prepare_chunk(struct llapi_layout *layout,
11572                              struct verify_chunk *chunks,
11573                              size_t chunks_size)
11574 {
11575         uint64_t start;
11576         uint64_t end;
11577         uint32_t mirror_id;
11578         uint32_t flags;
11579         int idx = 0;
11580         int i = 0;
11581         int rc = 0;
11582
11583         memset(chunks, 0, sizeof(*chunks) * chunks_size);
11584
11585         while (1) {
11586                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
11587                 if (rc < 0) {
11588                         fprintf(stderr,
11589                                 "%s: move to the first layout component: %s.\n",
11590                                 progname, strerror(errno));
11591                         goto error;
11592                 }
11593
11594                 i = 0;
11595                 rc = 0;
11596                 chunks[idx].chunk.e_end = LUSTRE_EOF;
11597                 while (rc == 0) {
11598                         rc = llapi_layout_comp_extent_get(layout, &start, &end);
11599                         if (rc < 0) {
11600                                 fprintf(stderr,
11601                                         "%s: llapi_layout_comp_extent_get failed: %s.\n",
11602                                         progname, strerror(errno));
11603                                 goto error;
11604                         }
11605
11606                         if (start > chunks[idx].chunk.e_start ||
11607                             end <= chunks[idx].chunk.e_start)
11608                                 goto next;
11609
11610                         if (end < chunks[idx].chunk.e_end)
11611                                 chunks[idx].chunk.e_end = end;
11612
11613                         rc = llapi_layout_comp_flags_get(layout, &flags);
11614                         if (rc < 0) {
11615                                 fprintf(stderr,
11616                                         "%s: llapi_layout_comp_flags_get failed: %s.\n",
11617                                         progname, strerror(errno));
11618                                 goto error;
11619                         }
11620
11621                         if (flags & LCME_FL_STALE || flags & LCME_FL_OFFLINE)
11622                                 goto next;
11623
11624                         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
11625                         if (rc < 0) {
11626                                 fprintf(stderr,
11627                                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
11628                                         progname, strerror(errno));
11629                                 goto error;
11630                         }
11631
11632                         chunks[idx].mirror_id[i] = mirror_id;
11633                         i++;
11634                         if (i >= ARRAY_SIZE(chunks[idx].mirror_id)) {
11635                                 fprintf(stderr,
11636                                         "%s: mirror_id array is too small.\n",
11637                                         progname);
11638                                 rc = -EINVAL;
11639                                 goto error;
11640                         }
11641
11642 next:
11643                         rc = llapi_layout_comp_use(layout,
11644                                                    LLAPI_LAYOUT_COMP_USE_NEXT);
11645                         if (rc < 0) {
11646                                 fprintf(stderr,
11647                                         "%s: move to the next layout component: %s.\n",
11648                                         progname, strerror(errno));
11649                                 goto error;
11650                         }
11651                 } /* loop through all components */
11652
11653                 chunks[idx].mirror_count = i;
11654
11655                 if (chunks[idx].chunk.e_end == LUSTRE_EOF)
11656                         break;
11657
11658                 idx++;
11659                 if (idx >= chunks_size) {
11660                         fprintf(stderr, "%s: chunks array is too small.\n",
11661                                 progname);
11662                         rc = -EINVAL;
11663                         goto error;
11664                 }
11665
11666                 chunks[idx].chunk.e_start = chunks[idx - 1].chunk.e_end;
11667         }
11668
11669 error:
11670         return rc < 0 ? rc : idx + 1;
11671 }
11672
11673 /**
11674  * lfs_mirror_verify_chunk() - Verify a chunk.
11675  * @fd:        File descriptor of the mirrored file.
11676  * @file_size: Size of the mirrored file.
11677  * @chunk:     A chunk and its corresponding valid mirror ids.
11678  * @verbose:   Verbose mode.
11679  *
11680  * This function verifies a @chunk contains exactly the same data
11681  * ammong the mirrors that cover it.
11682  *
11683  * If @verbose is specified, then the function will print where the
11684  * differences are if the data do not match. Otherwise, it will
11685  * just return an error in that case.
11686  *
11687  * Return: 0 on success or a negative error code on failure.
11688  */
11689 static inline
11690 int lfs_mirror_verify_chunk(int fd, size_t file_size,
11691                             struct verify_chunk *chunk, int verbose)
11692 {
11693         const size_t buflen = 4 * 1024 * 1024; /* 4M */
11694         void *buf;
11695         size_t page_size = sysconf(_SC_PAGESIZE);
11696         ssize_t bytes_read;
11697         ssize_t bytes_done;
11698         size_t count;
11699         off_t pos;
11700         unsigned long crc;
11701         unsigned long crc_array[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
11702         int i;
11703         int rc = 0;
11704
11705         if (file_size == 0)
11706                 return 0;
11707
11708         rc = posix_memalign(&buf, page_size, buflen);
11709         if (rc) /* error code is returned directly */
11710                 return -rc;
11711
11712         if (verbose > 1) {
11713                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
11714                         PEXT(&chunk->chunk));
11715                 for (i = 0; i < chunk->mirror_count; i++)
11716                         fprintf(stdout, " %u", chunk->mirror_id[i]);
11717                 fprintf(stdout, "\n");
11718         }
11719
11720         bytes_done = 0;
11721         count = MIN(chunk->chunk.e_end, file_size) - chunk->chunk.e_start;
11722         pos = chunk->chunk.e_start;
11723         while (bytes_done < count) {
11724                 /* compute initial CRC-32 checksum */
11725                 crc = crc32(0L, Z_NULL, 0);
11726                 memset(crc_array, 0, sizeof(crc_array));
11727
11728                 bytes_read = 0;
11729                 for (i = 0; i < chunk->mirror_count; i++) {
11730                         bytes_read = llapi_mirror_read(fd, chunk->mirror_id[i],
11731                                                        buf, buflen, pos);
11732                         if (bytes_read < 0) {
11733                                 rc = bytes_read;
11734                                 fprintf(stderr,
11735                                         "%s: failed to read data from mirror %u: %s.\n",
11736                                         progname, chunk->mirror_id[i],
11737                                         strerror(-rc));
11738                                 goto error;
11739                         }
11740
11741                         /* compute new CRC-32 checksum */
11742                         crc_array[i] = crc32(crc, buf, bytes_read);
11743                 }
11744
11745                 if (verbose)
11746                         print_checksums(chunk, crc_array);
11747
11748                 /* compare CRC-32 checksum values */
11749                 for (i = 1; i < chunk->mirror_count; i++) {
11750                         if (crc_array[i] != crc_array[0]) {
11751                                 rc = -EINVAL;
11752
11753                                 fprintf(stderr,
11754                                         "%s: chunk "DEXT" has different checksum value on mirror %u and mirror %u.\n",
11755                                         progname, PEXT(&chunk->chunk),
11756                                         chunk->mirror_id[0],
11757                                         chunk->mirror_id[i]);
11758                         }
11759                 }
11760
11761                 pos += bytes_read;
11762                 bytes_done += bytes_read;
11763         }
11764
11765         if (verbose > 1 && rc == 0) {
11766                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
11767                         PEXT(&chunk->chunk));
11768                 for (i = 0; i < chunk->mirror_count; i++)
11769                         fprintf(stdout, " %u", chunk->mirror_id[i]);
11770                 fprintf(stdout, " PASS\n\n");
11771         }
11772
11773 error:
11774         free(buf);
11775         return rc;
11776 }
11777
11778 /**
11779  * lfs_mirror_verify_file() - Verify a mirrored file.
11780  * @fname:      Mirrored file name.
11781  * @mirror_ids: Specified mirror ids to be verified.
11782  * @ids_nr:     Number of specified mirror ids.
11783  * @verbose:    Verbose mode.
11784  *
11785  * This function verifies that each SYNC mirror of a mirrored file
11786  * specified by @fname contains exactly the same data.
11787  *
11788  * If @mirror_ids is specified, then the function will verify the
11789  * mirrors specified by @mirror_ids contain exactly the same data.
11790  *
11791  * If @verbose is specified, then the function will print where the
11792  * differences are if the data do not match. Otherwise, it will
11793  * just return an error in that case.
11794  *
11795  * Return: 0 on success or a negative error code on failure.
11796  */
11797 static inline
11798 int lfs_mirror_verify_file(const char *fname, __u16 *mirror_ids, int ids_nr,
11799                            int verbose)
11800 {
11801         struct verify_chunk chunks_array[1024] = { };
11802         struct llapi_layout *layout = NULL;
11803         struct stat stbuf;
11804         uint32_t flr_state;
11805         int fd;
11806         int chunk_count = 0;
11807         int idx = 0;
11808         int rc = 0;
11809         int rc1 = 0;
11810         int rc2 = 0;
11811
11812         if (stat(fname, &stbuf) < 0) {
11813                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
11814                         progname, fname, strerror(errno));
11815                 rc = -errno;
11816                 goto error;
11817         }
11818
11819         if (!S_ISREG(stbuf.st_mode)) {
11820                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
11821                         progname, fname);
11822                 rc = -EINVAL;
11823                 goto error;
11824         }
11825
11826         if (stbuf.st_size == 0) {
11827                 if (verbose)
11828                         fprintf(stdout, "%s: '%s' file size is 0.\n",
11829                                 progname, fname);
11830                 rc = 0;
11831                 goto error;
11832         }
11833
11834         fd = open(fname, O_DIRECT | O_RDONLY);
11835         if (fd < 0) {
11836                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
11837                         progname, fname, strerror(errno));
11838                 rc = -errno;
11839                 goto error;
11840         }
11841
11842         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
11843         if (rc < 0) {
11844                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
11845                         progname, fname, strerror(errno));
11846                 goto close_fd;
11847         }
11848
11849         layout = llapi_layout_get_by_fd(fd, 0);
11850         if (!layout) {
11851                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
11852                         progname, fname, strerror(errno));
11853                 rc = -errno;
11854                 llapi_lease_release(fd);
11855                 goto close_fd;
11856         }
11857
11858         rc = llapi_layout_flags_get(layout, &flr_state);
11859         if (rc < 0) {
11860                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
11861                         progname, fname, strerror(errno));
11862                 rc = -errno;
11863                 goto free_layout;
11864         }
11865
11866         flr_state &= LCM_FL_FLR_MASK;
11867         switch (flr_state) {
11868         case LCM_FL_NONE:
11869                 rc = -EINVAL;
11870                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
11871                         progname, fname, llapi_layout_flags_string(flr_state));
11872                 goto free_layout;
11873         default:
11874                 break;
11875         }
11876
11877         /* find out mirror chunks to be verified */
11878         chunk_count = lfs_mirror_prepare_chunk(layout, chunks_array,
11879                                                ARRAY_SIZE(chunks_array));
11880         if (chunk_count < 0) {
11881                 rc = chunk_count;
11882                 goto free_layout;
11883         }
11884
11885         if (ids_nr > 0)
11886                 /* filter specified mirror ids */
11887                 filter_mirror_id(chunks_array, chunk_count, mirror_ids, ids_nr);
11888
11889         if (verbose > 2)
11890                 print_chunks(fname, chunks_array, chunk_count);
11891
11892         for (idx = 0; idx < chunk_count; idx++) {
11893                 if (chunks_array[idx].chunk.e_start >= stbuf.st_size) {
11894                         if (verbose)
11895                                 fprintf(stdout,
11896                                         "%s: '%s' chunk "DEXT" exceeds file size %#llx: skipped\n",
11897                                         progname, fname,
11898                                         PEXT(&chunks_array[idx].chunk),
11899                                         (unsigned long long)stbuf.st_size);
11900                         break;
11901                 }
11902
11903                 if (chunks_array[idx].mirror_count == 0) {
11904                         fprintf(stderr,
11905                                 "%s: '%s' chunk "DEXT" is invalid in all of the mirrors: ",
11906                                 progname, fname,
11907                                 PEXT(&chunks_array[idx].chunk));
11908                         if (verbose) {
11909                                 fprintf(stderr, "skipped\n");
11910                                 continue;
11911                         }
11912                         rc = -EINVAL;
11913                         fprintf(stderr, "failed\n");
11914                         goto free_layout;
11915                 }
11916
11917                 if (chunks_array[idx].mirror_count == 1) {
11918                         if (verbose)
11919                                 fprintf(stdout,
11920                                         "%s: '%s' chunk "DEXT" is only valid in mirror %u: skipped\n",
11921                                         progname, fname,
11922                                         PEXT(&chunks_array[idx].chunk),
11923                                         chunks_array[idx].mirror_id[0]);
11924                         continue;
11925                 }
11926
11927                 rc = llapi_lease_check(fd);
11928                 if (rc != LL_LEASE_RDLCK) {
11929                         fprintf(stderr, "%s: '%s' lost lease lock.\n",
11930                                 progname, fname);
11931                         goto free_layout;
11932                 }
11933
11934                 /* verify one chunk */
11935                 rc1 = lfs_mirror_verify_chunk(fd, stbuf.st_size,
11936                                               &chunks_array[idx], verbose);
11937                 if (rc1 < 0) {
11938                         rc2 = rc1;
11939                         if (!verbose) {
11940                                 rc = rc1;
11941                                 goto free_layout;
11942                         }
11943                 }
11944         }
11945
11946         if (rc2 < 0)
11947                 rc = rc2;
11948
11949 free_layout:
11950         llapi_layout_free(layout);
11951         llapi_lease_release(fd);
11952 close_fd:
11953         close(fd);
11954 error:
11955         return rc;
11956 }
11957
11958 /**
11959  * lfs_mirror_verify() - Parse and execute lfs mirror verify command.
11960  * @argc: The count of lfs mirror verify command line arguments.
11961  * @argv: Array of strings for lfs mirror verify command line arguments.
11962  *
11963  * This function parses lfs mirror verify command and verifies the
11964  * specified mirrored file(s).
11965  *
11966  * Return: 0 on success or a negative error code on failure.
11967  */
11968 static inline int lfs_mirror_verify(int argc, char **argv)
11969 {
11970         __u16 mirror_ids[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
11971         int ids_nr = 0;
11972         int c;
11973         int verbose = 0;
11974         int rc = 0;
11975         int rc1 = 0;
11976         char cmd[PATH_MAX];
11977
11978         struct option long_opts[] = {
11979         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11980         { .val = 'o',   .name = "only",         .has_arg = required_argument },
11981         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
11982         { .name = NULL } };
11983
11984         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
11985         progname = cmd;
11986         while ((c = getopt_long(argc, argv, "ho:v", long_opts, NULL)) >= 0) {
11987                 switch (c) {
11988                 case 'o':
11989                         rc = parse_mirror_ids(mirror_ids,
11990                                               ARRAY_SIZE(mirror_ids),
11991                                               optarg);
11992                         if (rc < 0) {
11993                                 fprintf(stderr,
11994                                         "%s: bad mirror ids '%s'.\n",
11995                                         progname, optarg);
11996                                 goto error;
11997                         }
11998                         ids_nr = rc;
11999                         if (ids_nr < 2) {
12000                                 fprintf(stderr,
12001                                         "%s: at least 2 mirror ids needed with '--only' option.\n",
12002                                         progname);
12003                                 rc = CMD_HELP;
12004                                 goto error;
12005                         }
12006                         break;
12007                 case 'v':
12008                         verbose++;
12009                         break;
12010                 default:
12011                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12012                                 progname, argv[optind - 1]);
12013                         /* fallthrough */
12014                 case 'h':
12015                         rc = CMD_HELP;
12016                         goto error;
12017                 }
12018         }
12019
12020         if (argc == optind) {
12021                 fprintf(stderr, "%s: no file name given.\n", progname);
12022                 rc = CMD_HELP;
12023                 goto error;
12024         }
12025
12026         if (ids_nr > 0 && argc > optind + 1) {
12027                 fprintf(stderr,
12028                         "%s: '--only' cannot be used upon multiple files.\n",
12029                         progname);
12030                 rc = CMD_HELP;
12031                 goto error;
12032         }
12033
12034         if (ids_nr > 0) {
12035                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
12036                 if (rc < 0)
12037                         goto error;
12038         }
12039
12040         rc = 0;
12041         for (; optind < argc; optind++) {
12042                 rc1 = lfs_mirror_verify_file(argv[optind], mirror_ids, ids_nr,
12043                                              verbose);
12044                 if (rc1 < 0)
12045                         rc = rc1;
12046         }
12047 error:
12048         return rc;
12049 }
12050
12051 /**
12052  * lfs_mirror() - Parse and execute lfs mirror commands.
12053  * @argc: The count of lfs mirror command line arguments.
12054  * @argv: Array of strings for lfs mirror command line arguments.
12055  *
12056  * This function parses lfs mirror commands and performs the
12057  * corresponding functions specified in mirror_cmdlist[].
12058  *
12059  * Return: 0 on success or an error code on failure.
12060  */
12061 static int lfs_mirror(int argc, char **argv)
12062 {
12063         char cmd[PATH_MAX];
12064         int rc = 0;
12065
12066         setlinebuf(stdout);
12067
12068         Parser_init("lfs-mirror > ", mirror_cmdlist);
12069
12070         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
12071         progname = cmd;
12072         program_invocation_short_name = cmd;
12073         if (argc > 1)
12074                 rc = Parser_execarg(argc - 1, argv + 1, mirror_cmdlist);
12075         else
12076                 rc = Parser_commands();
12077
12078         return rc < 0 ? -rc : rc;
12079 }
12080
12081 static void lustre_som_swab(struct lustre_som_attrs *attrs)
12082 {
12083 #if __BYTE_ORDER == __BIG_ENDIAN
12084         __swab16s(&attrs->lsa_valid);
12085         __swab64s(&attrs->lsa_size);
12086         __swab64s(&attrs->lsa_blocks);
12087 #endif
12088 }
12089
12090 enum lfs_som_type {
12091         LFS_SOM_SIZE = 0x1,
12092         LFS_SOM_BLOCKS = 0x2,
12093         LFS_SOM_FLAGS = 0x4,
12094         LFS_SOM_ATTR_ALL = LFS_SOM_SIZE | LFS_SOM_BLOCKS |
12095                            LFS_SOM_FLAGS,
12096 };
12097
12098 static int lfs_getsom(int argc, char **argv)
12099 {
12100         const char *path;
12101         struct lustre_som_attrs *attrs;
12102         char buf[sizeof(*attrs) + 64];
12103         enum lfs_som_type type = LFS_SOM_ATTR_ALL;
12104         int rc = 0, c;
12105
12106         while ((c = getopt(argc, argv, "bfhs")) != -1) {
12107                 switch (c) {
12108                 case 'b':
12109                         type = LFS_SOM_BLOCKS;
12110                         break;
12111                 case 'f':
12112                         type = LFS_SOM_FLAGS;
12113                         break;
12114                 case 's':
12115                         type = LFS_SOM_SIZE;
12116                         break;
12117                 default:
12118                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12119                                 progname, argv[optind - 1]);
12120                         /* fallthrough */
12121                 case 'h':
12122                         return CMD_HELP;
12123                 }
12124         }
12125
12126         argc -= optind;
12127         argv += optind;
12128
12129         if (argc != 1) {
12130                 fprintf(stderr, "%s: %s\n",
12131                         progname, argc == 0 ? "miss file target" :
12132                         "input more than 2 files");
12133                 return CMD_HELP;
12134         }
12135
12136         path = argv[0];
12137         attrs = (void *)buf;
12138         rc = lgetxattr(path, "trusted.som", attrs, sizeof(buf));
12139         if (rc < 0) {
12140                 rc = -errno;
12141                 fprintf(stderr, "%s failed to get som xattr: %s (%d)\n",
12142                         argv[0], strerror(errno), errno);
12143                 return rc;
12144         }
12145
12146         lustre_som_swab(attrs);
12147
12148         switch (type) {
12149         case LFS_SOM_ATTR_ALL:
12150                 printf("file: %s size: %llu blocks: %llu flags: %x\n",
12151                        path, (unsigned long long)attrs->lsa_size,
12152                        (unsigned long long)attrs->lsa_blocks,
12153                        attrs->lsa_valid);
12154                 break;
12155         case LFS_SOM_SIZE:
12156                 printf("%llu\n", (unsigned long long)attrs->lsa_size);
12157                 break;
12158         case LFS_SOM_BLOCKS:
12159                 printf("%llu\n", (unsigned long long)attrs->lsa_blocks);
12160                 break;
12161         case LFS_SOM_FLAGS:
12162                 printf("%x\n", attrs->lsa_valid);
12163                 break;
12164         default:
12165                 fprintf(stderr, "%s: unknown option\n", progname);
12166                 return CMD_HELP;
12167         }
12168
12169         return 0;
12170 }
12171
12172 /**
12173  * lfs_mirror_list_commands() - List lfs mirror commands.
12174  * @argc: The count of command line arguments.
12175  * @argv: Array of strings for command line arguments.
12176  *
12177  * This function lists lfs mirror commands defined in mirror_cmdlist[].
12178  *
12179  * Return: 0 on success.
12180  */
12181 static int lfs_mirror_list_commands(int argc, char **argv)
12182 {
12183         char buffer[81] = "";
12184
12185         Parser_list_commands(mirror_cmdlist, buffer, sizeof(buffer),
12186                              NULL, 0, 4);
12187
12188         return 0;
12189 }
12190
12191 static int lfs_pcc_attach(int argc, char **argv)
12192 {
12193         struct option long_opts[] = {
12194         { .val = 'h',   .name = "help", .has_arg = no_argument },
12195         { .val = 'i',   .name = "id",   .has_arg = required_argument },
12196         { .name = NULL } };
12197         int c;
12198         int rc = 0;
12199         __u32 archive_id = 0;
12200         const char *path;
12201         char *end;
12202         char fullpath[PATH_MAX];
12203         enum lu_pcc_type type = LU_PCC_READWRITE;
12204
12205         optind = 0;
12206         while ((c = getopt_long(argc, argv, "hi:",
12207                                 long_opts, NULL)) != -1) {
12208                 switch (c) {
12209                 case 'i':
12210                         errno = 0;
12211                         archive_id = strtoul(optarg, &end, 0);
12212                         if (errno != 0 || *end != '\0' ||
12213                             archive_id == 0 || archive_id > UINT32_MAX) {
12214                                 fprintf(stderr,
12215                                         "error: %s: bad archive ID '%s'\n",
12216                                         progname, optarg);
12217                                 return CMD_HELP;
12218                         }
12219                         break;
12220                 default:
12221                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12222                                 progname, argv[optind - 1]);
12223                         /* fallthrough */
12224                 case 'h':
12225                         return CMD_HELP;
12226                 }
12227         }
12228
12229         if (archive_id == 0) {
12230                 fprintf(stderr, "%s: must specify attach ID\n", argv[0]);
12231                 return CMD_HELP;
12232         }
12233
12234         if (argc <= optind) {
12235                 fprintf(stderr, "%s: must specify one or more file names\n",
12236                         argv[0]);
12237                 return CMD_HELP;
12238         }
12239
12240         while (optind < argc) {
12241                 int rc2;
12242
12243                 path = argv[optind++];
12244                 if (!realpath(path, fullpath)) {
12245                         fprintf(stderr, "%s: could not find path '%s': %s\n",
12246                                 argv[0], path, strerror(errno));
12247                         if (rc == 0)
12248                                 rc = -EINVAL;
12249                         continue;
12250                 }
12251
12252                 rc2 = llapi_pcc_attach(fullpath, archive_id, type);
12253                 if (rc2 < 0) {
12254                         fprintf(stderr,
12255                                 "%s: cannot attach '%s' to PCC with archive ID '%u': %s\n",
12256                                 argv[0], path, archive_id, strerror(-rc2));
12257                         if (rc == 0)
12258                                 rc = rc2;
12259                 }
12260         }
12261         return rc;
12262 }
12263
12264 static int lfs_pcc_attach_fid(int argc, char **argv)
12265 {
12266         struct option long_opts[] = {
12267         { .val = 'h',   .name = "help", .has_arg = no_argument },
12268         { .val = 'i',   .name = "id",   .has_arg = required_argument },
12269         { .val = 'm',   .name = "mnt",  .has_arg = required_argument },
12270         { .name = NULL } };
12271         int c;
12272         int rc = 0;
12273         __u32 archive_id = 0;
12274         char *end;
12275         const char *mntpath = NULL;
12276         const char *fidstr;
12277         enum lu_pcc_type type = LU_PCC_READWRITE;
12278
12279         optind = 0;
12280         while ((c = getopt_long(argc, argv, "hi:m:",
12281                                 long_opts, NULL)) != -1) {
12282                 switch (c) {
12283                 case 'i':
12284                         errno = 0;
12285                         archive_id = strtoul(optarg, &end, 0);
12286                         if (errno != 0 || *end != '\0' ||
12287                             archive_id > UINT32_MAX) {
12288                                 fprintf(stderr,
12289                                         "error: %s: bad archive ID '%s'\n",
12290                                         argv[0], optarg);
12291                                 return CMD_HELP;
12292                         }
12293                         break;
12294                 case 'm':
12295                         mntpath = optarg;
12296                         break;
12297                 default:
12298                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12299                                 progname, argv[optind - 1]);
12300                         /* fallthrough */
12301                 case 'h':
12302                         return CMD_HELP;
12303                 }
12304         }
12305
12306         if (archive_id == 0) {
12307                 fprintf(stderr, "%s: must specify an archive ID\n", argv[0]);
12308                 return CMD_HELP;
12309         }
12310
12311         if (!mntpath) {
12312                 fprintf(stderr, "%s: must specify Lustre mount point\n",
12313                         argv[0]);
12314                 return CMD_HELP;
12315         }
12316
12317         if (argc <= optind) {
12318                 fprintf(stderr, "%s: must specify one or more fids\n", argv[0]);
12319                 return CMD_HELP;
12320         }
12321
12322         while (optind < argc) {
12323                 int rc2;
12324
12325                 fidstr = argv[optind++];
12326
12327                 rc2 = llapi_pcc_attach_fid_str(mntpath, fidstr,
12328                                                archive_id, type);
12329                 if (rc2 < 0) {
12330                         fprintf(stderr,
12331                                 "%s: cannot attach '%s' on '%s' to PCC with archive ID '%u': %s\n",
12332                                 argv[0], fidstr, mntpath, archive_id,
12333                                 strerror(rc2));
12334                 }
12335                 if (rc == 0 && rc2 < 0)
12336                         rc = rc2;
12337         }
12338         return rc;
12339 }
12340
12341 static int lfs_pcc_detach(int argc, char **argv)
12342 {
12343         struct option long_opts[] = {
12344         { .val = 'h',   .name = "help", .has_arg = no_argument },
12345         { .val = 'k',   .name = "keep", .has_arg = no_argument },
12346         { .name = NULL } };
12347         int c;
12348         int rc = 0;
12349         const char *path;
12350         char fullpath[PATH_MAX];
12351         __u32 detach_opt = PCC_DETACH_OPT_UNCACHE;
12352
12353         optind = 0;
12354         while ((c = getopt_long(argc, argv, "hk",
12355                                 long_opts, NULL)) != -1) {
12356                 switch (c) {
12357                 case 'k':
12358                         detach_opt = PCC_DETACH_OPT_NONE;
12359                         break;
12360                 default:
12361                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12362                                 progname, argv[optind - 1]);
12363                         /* fallthrough */
12364                 case 'h':
12365                         return CMD_HELP;
12366                 }
12367         }
12368
12369         while (optind < argc) {
12370                 int rc2;
12371
12372                 path = argv[optind++];
12373                 if (!realpath(path, fullpath)) {
12374                         fprintf(stderr, "%s: could not find path '%s': %s\n",
12375                                 argv[0], path, strerror(errno));
12376                         if (rc == 0)
12377                                 rc = -EINVAL;
12378                         continue;
12379                 }
12380
12381                 rc2 = llapi_pcc_detach_file(fullpath, detach_opt);
12382                 if (rc2 < 0) {
12383                         rc2 = -errno;
12384                         fprintf(stderr,
12385                                 "%s: cannot detach '%s' from PCC: %s\n",
12386                                 argv[0], path, strerror(errno));
12387                         if (rc == 0)
12388                                 rc = rc2;
12389                 }
12390         }
12391         return rc;
12392 }
12393
12394 static int lfs_pcc_detach_fid(int argc, char **argv)
12395 {
12396         struct option long_opts[] = {
12397         { .val = 'h',   .name = "help", .has_arg = no_argument },
12398         { .val = 'k',   .name = "keep", .has_arg = no_argument },
12399         { .name = NULL } };
12400         int c;
12401         int rc = 0;
12402         const char *fid;
12403         const char *mntpath;
12404         __u32 detach_opt = PCC_DETACH_OPT_UNCACHE;
12405
12406         optind = 0;
12407         while ((c = getopt_long(argc, argv, "hk",
12408                                 long_opts, NULL)) != -1) {
12409                 switch (c) {
12410                 case 'k':
12411                         detach_opt = PCC_DETACH_OPT_NONE;
12412                         break;
12413                 default:
12414                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12415                                 progname, argv[optind - 1]);
12416                         /* fallthrough */
12417                 case 'h':
12418                         return CMD_HELP;
12419                 }
12420         }
12421
12422         mntpath = argv[optind++];
12423
12424         while (optind < argc) {
12425                 int rc2;
12426
12427                 fid = argv[optind++];
12428
12429                 rc2 = llapi_pcc_detach_fid_str(mntpath, fid, detach_opt);
12430                 if (rc2 < 0) {
12431                         fprintf(stderr,
12432                                 "%s: cannot detach '%s' on '%s' from PCC: %s\n",
12433                                 argv[0], fid, mntpath, strerror(-rc2));
12434                         if (rc == 0)
12435                                 rc = rc2;
12436                 }
12437         }
12438         return rc;
12439 }
12440
12441 static int lfs_pcc_state(int argc, char **argv)
12442 {
12443         int rc = 0;
12444         const char *path;
12445         char fullpath[PATH_MAX];
12446         struct lu_pcc_state state;
12447
12448         optind = 1;
12449
12450         if (argc <= 1) {
12451                 fprintf(stderr, "%s: must specify one or more file names\n",
12452                         progname);
12453                 return CMD_HELP;
12454         }
12455
12456         while (optind < argc) {
12457                 int rc2;
12458
12459                 path = argv[optind++];
12460                 if (!realpath(path, fullpath)) {
12461                         fprintf(stderr, "%s: could not find path '%s': %s\n",
12462                                 argv[0], path, strerror(errno));
12463                         if (rc == 0)
12464                                 rc = -EINVAL;
12465                         continue;
12466                 }
12467
12468                 rc2 = llapi_pcc_state_get(fullpath, &state);
12469                 if (rc2 < 0) {
12470                         if (rc == 0)
12471                                 rc = rc2;
12472                         fprintf(stderr,
12473                                 "%s: cannot get PCC state of '%s': %s\n",
12474                                 argv[0], path, strerror(-rc2));
12475                         continue;
12476                 }
12477
12478                 printf("file: %s", path);
12479                 printf(", type: %s", pcc_type2string(state.pccs_type));
12480                 if (state.pccs_type == LU_PCC_NONE &&
12481                     state.pccs_open_count == 0) {
12482                         printf("\n");
12483                         continue;
12484                 }
12485
12486                 printf(", PCC file: %s", state.pccs_path);
12487                 printf(", user number: %u", state.pccs_open_count);
12488                 printf(", flags: %x", state.pccs_flags);
12489                 printf("\n");
12490         }
12491         return rc;
12492 }
12493
12494 /**
12495  * lfs_pcc_list_commands() - List lfs pcc commands.
12496  * @argc: The count of command line arguments.
12497  * @argv: Array of strings for command line arguments.
12498  *
12499  * This function lists lfs pcc commands defined in pcc_cmdlist[].
12500  *
12501  * Return: 0 on success.
12502  */
12503 static int lfs_pcc_list_commands(int argc, char **argv)
12504 {
12505         char buffer[81] = "";
12506
12507         Parser_list_commands(pcc_cmdlist, buffer, sizeof(buffer),
12508                              NULL, 0, 4);
12509
12510         return 0;
12511 }
12512
12513 /**
12514  * lfs_pcc() - Parse and execute lfs pcc commands.
12515  * @argc: The count of lfs pcc command line arguments.
12516  * @argv: Array of strings for lfs pcc command line arguments.
12517  *
12518  * This function parses lfs pcc commands and performs the
12519  * corresponding functions specified in pcc_cmdlist[].
12520  *
12521  * Return: 0 on success or an error code on failure.
12522  */
12523 static int lfs_pcc(int argc, char **argv)
12524 {
12525         char cmd[PATH_MAX];
12526         int rc = 0;
12527
12528         setlinebuf(stdout);
12529
12530         Parser_init("lfs-pcc > ", pcc_cmdlist);
12531
12532         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
12533         progname = cmd;
12534         program_invocation_short_name = cmd;
12535         if (argc > 1)
12536                 rc = Parser_execarg(argc - 1, argv + 1, pcc_cmdlist);
12537         else
12538                 rc = Parser_commands();
12539
12540         return rc < 0 ? -rc : rc;
12541 }
12542
12543 static int lfs_list_commands(int argc, char **argv)
12544 {
12545         char buffer[81] = ""; /* 80 printable chars + terminating NUL */
12546
12547         Parser_list_commands(cmdlist, buffer, sizeof(buffer), NULL, 0, 4);
12548
12549         return 0;
12550 }
12551
12552 int main(int argc, char **argv)
12553 {
12554         int rc;
12555
12556         /* Ensure that liblustreapi constructor has run */
12557         if (!llapi_liblustreapi_initialized())
12558                 fprintf(stderr, "liblustreapi was not properly initialized\n");
12559
12560         setlinebuf(stdout);
12561         opterr = 0;
12562
12563         Parser_init("lfs > ", cmdlist);
12564
12565         progname = program_invocation_short_name; /* Used in error messages */
12566         if (argc > 1) {
12567                 llapi_set_command_name(argv[1]);
12568                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
12569                 llapi_clear_command_name();
12570         } else {
12571                 rc = Parser_commands();
12572         }
12573
12574         return rc < 0 ? -rc : rc;
12575 }
12576
12577 #ifdef _LUSTRE_IDL_H_
12578 /* Everything we need here should be included by lustreapi.h. */
12579 # error "lfs should not depend on lustre_idl.h"
12580 #endif /* _LUSTRE_IDL_H_ */