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