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