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