Whamcloud - gitweb
LU-15121 llite: skip request slot for lmv_revalidate_slaves()
[fs/lustre-release.git] / lustre / utils / lfs.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * lustre/utils/lfs.c
32  *
33  * Author: Peter J. Braam <braam@clusterfs.com>
34  * Author: Phil Schwan <phil@clusterfs.com>
35  * Author: Robert Read <rread@clusterfs.com>
36  */
37
38 /* for O_DIRECTORY */
39 #ifndef _GNU_SOURCE
40 #define _GNU_SOURCE
41 #endif
42
43 #include <stdlib.h>
44 #include <stdio.h>
45 #include <inttypes.h>
46 #include <getopt.h>
47 #include <string.h>
48 #include <mntent.h>
49 #include <unistd.h>
50 #include <errno.h>
51 #include <err.h>
52 #include <pwd.h>
53 #include <grp.h>
54 #include <sys/ioctl.h>
55 #include <sys/quota.h>
56 #include <sys/time.h>
57 #include <sys/types.h>
58 #include <sys/stat.h>
59 #include <sys/param.h>
60 #include <sys/xattr.h>
61 #include <fcntl.h>
62 #include <dirent.h>
63 #include <time.h>
64 #include <ctype.h>
65 #include <zlib.h>
66 #include <libgen.h>
67 #include <asm/byteorder.h>
68 #include "lfs_project.h"
69
70 #include <libcfs/util/string.h>
71 #include <libcfs/util/ioctl.h>
72 #include <libcfs/util/parser.h>
73 #include <libcfs/util/string.h>
74 #include <lustre/lustreapi.h>
75 #include <linux/lustre/lustre_ver.h>
76 #include <linux/lustre/lustre_param.h>
77 #include <linux/lnet/nidstr.h>
78 #include <lnetconfig/cyaml.h>
79 #include "lstddef.h"
80
81 /* all functions */
82 static int lfs_find(int argc, char **argv);
83 static int lfs_getstripe(int argc, char **argv);
84 static int lfs_getdirstripe(int argc, char **argv);
85 static int lfs_setdirstripe(int argc, char **argv);
86 static int lfs_rmentry(int argc, char **argv);
87 static int lfs_unlink_foreign(int argc, char **argv);
88 static int lfs_osts(int argc, char **argv);
89 static int lfs_mdts(int argc, char **argv);
90 static int lfs_df(int argc, char **argv);
91 static int lfs_getname(int argc, char **argv);
92 static int lfs_check(int argc, char **argv);
93 #ifdef HAVE_SYS_QUOTA_H
94 static int lfs_setquota(int argc, char **argv);
95 static int lfs_quota(int argc, char **argv);
96 static int lfs_project(int argc, char **argv);
97 #endif
98 static int lfs_flushctx(int argc, char **argv);
99 static int lfs_poollist(int argc, char **argv);
100 static int lfs_changelog(int argc, char **argv);
101 static int lfs_changelog_clear(int argc, char **argv);
102 static int lfs_fid2path(int argc, char **argv);
103 static int lfs_path2fid(int argc, char **argv);
104 static int lfs_rmfid(int argc, char **argv);
105 static int lfs_data_version(int argc, char **argv);
106 static int lfs_hsm_state(int argc, char **argv);
107 static int lfs_hsm_set(int argc, char **argv);
108 static int lfs_hsm_clear(int argc, char **argv);
109 static int lfs_hsm_action(int argc, char **argv);
110 static int lfs_hsm_archive(int argc, char **argv);
111 static int lfs_hsm_restore(int argc, char **argv);
112 static int lfs_hsm_release(int argc, char **argv);
113 static int lfs_hsm_remove(int argc, char **argv);
114 static int lfs_hsm_cancel(int argc, char **argv);
115 static int lfs_swap_layouts(int argc, char **argv);
116 static int lfs_mv(int argc, char **argv);
117 static int lfs_ladvise(int argc, char **argv);
118 static int lfs_getsom(int argc, char **argv);
119 static int lfs_heat_get(int argc, char **argv);
120 static int lfs_heat_set(int argc, char **argv);
121 static int lfs_mirror(int argc, char **argv);
122 static int lfs_mirror_list_commands(int argc, char **argv);
123 static int lfs_list_commands(int argc, char **argv);
124 static inline int lfs_mirror_resync(int argc, char **argv);
125 static inline int lfs_mirror_verify(int argc, char **argv);
126 static inline int lfs_mirror_read(int argc, char **argv);
127 static inline int lfs_mirror_write(int argc, char **argv);
128 static inline int lfs_mirror_copy(int argc, char **argv);
129 static int lfs_pcc_attach(int argc, char **argv);
130 static int lfs_pcc_attach_fid(int argc, char **argv);
131 static int lfs_pcc_detach(int argc, char **argv);
132 static int lfs_pcc_detach_fid(int argc, char **argv);
133 static int lfs_pcc_state(int argc, char **argv);
134 static int lfs_pcc(int argc, char **argv);
135 static int lfs_pcc_list_commands(int argc, char **argv);
136 static int lfs_migrate_to_dom(int fd, int fdv, char *name,
137                               __u64 migration_flags,
138                               struct llapi_stripe_param *param,
139                               struct llapi_layout *layout);
140
141 struct pool_to_id_cbdata {
142         const char *pool;
143         __u32 id;
144 };
145 static int find_comp_id_by_pool(struct llapi_layout *layout, void *cbdata);
146 static int find_mirror_id_by_pool(struct llapi_layout *layout, void *cbdata);
147
148 enum setstripe_origin {
149         SO_SETSTRIPE,
150         SO_MIGRATE,
151         SO_MIGRATE_MDT,
152         SO_MIRROR_CREATE,
153         SO_MIRROR_EXTEND,
154         SO_MIRROR_SPLIT,
155         SO_MIRROR_DELETE,
156 };
157
158 static int lfs_setstripe_internal(int argc, char **argv,
159                                   enum setstripe_origin opc);
160
161 static inline int lfs_setstripe(int argc, char **argv)
162 {
163         return lfs_setstripe_internal(argc, argv, SO_SETSTRIPE);
164 }
165
166 static inline int lfs_setstripe_migrate(int argc, char **argv)
167 {
168         return lfs_setstripe_internal(argc, argv, SO_MIGRATE);
169 }
170
171 static inline int lfs_mirror_create(int argc, char **argv)
172 {
173         return lfs_setstripe_internal(argc, argv, SO_MIRROR_CREATE);
174 }
175
176 static inline int lfs_mirror_extend(int argc, char **argv)
177 {
178         return lfs_setstripe_internal(argc, argv, SO_MIRROR_EXTEND);
179 }
180
181 static inline int lfs_mirror_split(int argc, char **argv)
182 {
183         return lfs_setstripe_internal(argc, argv, SO_MIRROR_SPLIT);
184 }
185
186 static inline int lfs_mirror_delete(int argc, char **argv)
187 {
188         return lfs_setstripe_internal(argc, argv, SO_MIRROR_DELETE);
189 }
190
191 /* Setstripe and migrate share mostly the same parameters */
192 #define SSM_CMD_COMMON(cmd) \
193         "usage: "cmd" [--component-end|-E COMP_END]\n"                  \
194         "                 [--stripe-count|-c STRIPE_COUNT]\n"           \
195         "                 [--overstripe-count|-C STRIPE_COUNT]\n"       \
196         "                 [--stripe-index|-i START_OST_IDX]\n"          \
197         "                 [--stripe-size|-S STRIPE_SIZE]\n"             \
198         "                 [--extension-size|--ext-size|-z]\n"           \
199         "                 [--help|-h] [--layout|-L PATTERN]\n"          \
200         "                 [--mirror_count|-N[MIRROR_COUNT]]\n"          \
201         "                 [--ost|-o OST_INDICES]\n"                     \
202         "                 [--pool|-p POOL_NAME]\n"                      \
203         "                 [--yaml|-y YAML_TEMPLATE_FILE]\n"             \
204         "                 [--copy=LUSTRE_SRC]\n"
205
206 #define SSM_HELP_COMMON \
207         "\tSTRIPE_COUNT: Number of OSTs to stripe on (0=fs default, -1 all)\n" \
208         "\t              Using -C instead of -c allows overstriping, which\n"  \
209         "\t              will place more than one stripe per OST if\n"         \
210         "\t              stripe_count is greater than the number of OSTs.\n"   \
211         "\tSTART_OST_IDX: OST index of first stripe (-1=default round robin)\n"\
212         "\tSTRIPE_SIZE:  Number of bytes on each OST (0=fs default)\n"         \
213         "\t              Optional K, M, or G suffix (for KB, MB, GB\n"         \
214         "\t              respectively).  Must be a multiple of 64KiB.\n"       \
215         "\tEXTENSION_SIZE:\n"                                                  \
216         "\t              Number of bytes the previous component is extended\n" \
217         "\t              each time. Optional K, M, or G suffix (for KB,\n"     \
218         "\t              MB, GB respectively)\n"                               \
219         "\tPOOL_NAME:    Name of OST pool to use (default none)\n"             \
220         "\tLAYOUT:       stripe pattern type: raid0, mdt (default raid0)\n"    \
221         "\tOST_INDICES:  List of OST indices, can be repeated multiple times\n"\
222         "\t              Indices be specified in a format of:\n"               \
223         "\t                -o OST_1,OST_I-OST_J,OST_N\n"                       \
224         "\t              Or:\n"                                                \
225         "\t                -o OST_1 -o OST_I-OST_J -o OST_N\n"                 \
226         "\t              If --pool is set with --ost then the OSTs\n"          \
227         "\t              must be the members of the pool.\n"                   \
228         "\tCOMP_END:     Extent end of component, start after previous end.\n" \
229         "\t              Optional K, M, or G suffix (for KiB, MiB, GiB), or\n" \
230         "\t              -1 or 'eof' for max file size). Must be a multiple\n" \
231         "\t              of stripe_size and a multiple of 64KiB.\n"            \
232         "\tYAML_TEMPLATE_FILE:\n"                                              \
233         "\t              YAML layout template file, can't be used with -c,\n"  \
234         "\t              -i, -S, -p, -o, or -E arguments.\n"                   \
235         "\tLUSTRE_SRC:   Lustre file/dir whose layout info is used to set\n"   \
236         "\t              another lustre file or directory, can't used with\n"  \
237         "\t              -c, -i, -S, -p, -o, or -E arguments.\n"
238
239 #define MIRROR_CREATE_HELP                                                     \
240         "\tMIRROR_COUNT: Number of mirrors to be created with the upcoming\n"  \
241         "\t              setstripe layout options\n"                           \
242         "\t              It defaults to 1 if not specified; if specified,\n"   \
243         "\t              it must follow the option without a space.\n"         \
244         "\t              The option can also be repeated multiple times to\n"  \
245         "\t              separate mirrors that have different layouts.\n"      \
246         "\tSETSTRIPE_OPTIONS: Mirror layout as with 'setstripe'\n"             \
247         "\t              It can be a plain layout or a composite layout.\n"    \
248         "\t              If not specified, the stripe options inherited\n"     \
249         "\t              from the previous component will be used.\n"          \
250         "\tFLAGS:        set flags to the component of the current mirror.\n"  \
251         "\t              Only \"prefer\" flag is supported so far.\n"
252
253 #define MIRROR_EXTEND_HELP                                                     \
254         MIRROR_CREATE_HELP                                                     \
255         "\tVICTIM_FILE:  The layout of victim_file will be split and used\n"   \
256         "\t              as a mirror added to the mirrored file.\n"            \
257         "\tno-verify:    This option indicates not to verify the mirror(s)\n"  \
258         "\t              from victim file(s) in case the victim file(s)\n"     \
259         "\t              contains the same data as the original mirrored\n"    \
260         "\t              file.\n"
261
262 #define MIRROR_EXTEND_USAGE                                                    \
263         "                 {--mirror-count|-N[mirror_count]}\n"                 \
264         "                 [SETSTRIPE_OPTIONS|-f|--file VICTIM_FILE]\n"         \
265         "                 [--no-verify]\n"
266
267 #define SETSTRIPE_USAGE                                                 \
268         SSM_CMD_COMMON("setstripe")                                     \
269         MIRROR_EXTEND_USAGE                                             \
270         "                 <directory|filename>\n"                       \
271         SSM_HELP_COMMON                                                 \
272         MIRROR_EXTEND_HELP
273
274 #define MIGRATE_USAGE                                                   \
275         SSM_CMD_COMMON("migrate  ")                                     \
276         "                 [--block|-b] [--non-block|-n]\n"              \
277         "                 [--non-direct|-D] [--verbose|-v]\n"           \
278         "                 <filename>\n"                                 \
279         SSM_HELP_COMMON                                                 \
280         "\n"                                                            \
281         "\tblock:        Block file access during data migration (default)\n" \
282         "\tnon-block:    Abort migrations if concurrent access is detected\n" \
283         "\tnon-direct:   Do not use direct I/O to copy file contents\n" \
284         "\tverbose:      Print each filename as it is migrated\n"       \
285
286 #define SETDIRSTRIPE_USAGE                                              \
287         "               [--mdt-count|-c stripe_count>\n"                \
288         "               [--help|-h] [--mdt-hash|-H mdt_hash]\n"         \
289         "               [--mdt-index|-i mdt_index[,mdt_index,...]\n"    \
290         "               [--default|-D] [--mode|-o mode]\n"              \
291         "               [--max-inherit|-X max_inherit]\n"               \
292         "               [--max-inherit-rr max_inherit_rr] <dir>\n"      \
293         "\tstripe_count: stripe count of the striped directory\n"       \
294         "\tmdt_index: MDT index of first stripe\n"                      \
295         "\tmdt_hash:  hash type of the striped directory. mdt types:\n" \
296         "       crush     CRUSH hash algorithm (default)\n" \
297         "       fnv_1a_64 FNV-1a hash algorithm\n"              \
298         "       all_char  sum of characters % MDT_COUNT (not recommended)\n" \
299         "\tdefault_stripe: set default dirstripe of the directory\n"    \
300         "\tmode: the file access permission of the directory (octal)\n" \
301         "To create dir with a foreign (free format) layout :\n"         \
302         "setdirstripe|mkdir --foreign[=FOREIGN_TYPE] -x|-xattr STRING " \
303                 "[--mode|-o MODE] [--flags HEX] <dir>\n" \
304         "\tmode: the file access permissions of the directory\n"        \
305         "\tforeign_type: none, daos, symlink, or numeric value\n"
306
307 /**
308  * command_t mirror_cmdlist - lfs mirror commands.
309  */
310 command_t mirror_cmdlist[] = {
311         { .pc_name = "create", .pc_func = lfs_mirror_create,
312           .pc_help = "Create a mirrored file.\n"
313                 "usage: lfs mirror create {--mirror-count|-N[MIRROR_COUNT]}\n"
314                 "\t\t[SETSTRIPE_OPTIONS] <filename|directory> ...\n"
315           MIRROR_CREATE_HELP },
316         { .pc_name = "delete", .pc_func = lfs_mirror_delete,
317           .pc_help = "Delete a mirror from a file.\n"
318         "usage: lfs mirror delete {--mirror-id MIRROR_ID|-p POOL|\n"
319         "\t               --component-id|--comp-id|-I COMP_ID} <mirror_file>\n"
320         },
321         { .pc_name = "extend", .pc_func = lfs_mirror_extend,
322           .pc_help = "Extend a mirrored file.\n"
323                 "usage: lfs mirror extend {--mirror-count|-N[MIRROR_COUNT]}\n"
324                 "\t\t[--no-verify] [SETSTRIPE_OPTIONS|-f VICTIM_FILE] ... <filename> ...\n"
325           MIRROR_EXTEND_HELP },
326         { .pc_name = "split", .pc_func = lfs_mirror_split,
327           .pc_help = "Split a mirrored file.\n"
328         "usage: lfs mirror split [--destroy|-d] [-f NEW_FILE] [--help|-h]\n"
329         "\t\t{--mirror-id MIRROR_ID|--component-id|-I COMP_ID|-p POOL}\n"
330         "\t\t<mirrored file> ...\n"
331         "\tMIRROR_ID: The numerical unique identifier for a mirror.\n"
332         "\t           It can be fetched by the 'lfs getstripe' command.\n"
333         "\tCOMP_ID:   Unique component ID within a mirror.\n"
334         "\tPOOL:      Components using specified pool.\n"
335         "\tNEW_FILE:  This option indicates the layout of the split\n"
336         "\t           mirror will be stored into. If not specified,\n"
337         "\t           a new file named <mirrored_file>.mirror~MIRROR_ID\n"
338         "\t           will be used.\n" },
339         { .pc_name = "read", .pc_func = lfs_mirror_read,
340           .pc_help = "Read the content of a specified mirror of a file.\n"
341                 "usage: lfs mirror read {--mirror-id|-N MIRROR_ID}\n"
342                 "\t\t[--outfile|-o <output_file>] <mirrored_file>\n" },
343         { .pc_name = "write", .pc_func = lfs_mirror_write,
344           .pc_help = "Write to a specified mirror of a file.\n"
345                 "usage: lfs mirror write {--mirror-id|-N MIRROR_ID}\n"
346                 "\t\t[--inputfile|-i <input_file>] <mirrored_file>\n" },
347         { .pc_name = "copy", .pc_func = lfs_mirror_copy,
348           .pc_help = "Copy a specified mirror to other mirror(s) of a file.\n"
349                 "usage: lfs mirror copy {--read-mirror|-i MIRROR_ID0}\n"
350                 "\t\t{--write-mirror|-o MIRROR_ID1[,...]} <mirrored_file>\n" },
351         { .pc_name = "resync", .pc_func = lfs_mirror_resync,
352           .pc_help = "Resynchronizes out-of-sync mirrored file(s).\n"
353                 "usage: lfs mirror resync [--only MIRROR_ID[,...]>]\n"
354                 "\t\t<mirrored_file> [<mirrored_file2>...]\n" },
355         { .pc_name = "verify", .pc_func = lfs_mirror_verify,
356           .pc_help = "Verify mirrored file(s).\n"
357                 "usage: lfs mirror verify [--only MIRROR_ID[,...]]\n"
358                 "\t\t[--verbose|-v] <mirrored_file> [<mirrored_file2> ...]\n" },
359         { .pc_name = "list-commands", .pc_func = lfs_mirror_list_commands,
360           .pc_help = "list commands supported by lfs mirror"},
361         { .pc_name = "help", .pc_func = Parser_help, .pc_help = "help" },
362         { .pc_name = "exit", .pc_func = Parser_quit, .pc_help = "quit" },
363         { .pc_name = "quit", .pc_func = Parser_quit, .pc_help = "quit" },
364         { .pc_help = NULL }
365 };
366
367 /**
368  * command_t pcc_cmdlist - lfs pcc commands.
369  */
370 command_t pcc_cmdlist[] = {
371         { .pc_name = "attach", .pc_func = lfs_pcc_attach,
372           .pc_help = "Attach given files to the Persistent Client Cache.\n"
373                 "usage: lfs pcc attach <--id|-i NUM> <file> ...\n"
374                 "\t-i: archive id for RW-PCC\n" },
375         { .pc_name = "attach_fid", .pc_func = lfs_pcc_attach_fid,
376           .pc_help = "Attach given files into PCC by FID(s).\n"
377                 "usage: lfs pcc attach_id {--id|-i NUM} {--mnt|-m MOUNTPOINT} FID ...\n"
378                 "\t-i: archive id for RW-PCC\n"
379                 "\t-m: Lustre mount point\n" },
380         { .pc_name = "state", .pc_func = lfs_pcc_state,
381           .pc_help = "Display the PCC state for given files.\n"
382                 "usage: lfs pcc state <file> ...\n" },
383         { .pc_name = "detach", .pc_func = lfs_pcc_detach,
384           .pc_help = "Detach given files from the Persistent Client Cache.\n"
385                 "usage: lfs pcc detach <file> ...\n" },
386         { .pc_name = "detach_fid", .pc_func = lfs_pcc_detach_fid,
387           .pc_help = "Detach given files from PCC by FID(s).\n"
388                 "usage: lfs pcc detach_fid <mntpath> <fid>...\n" },
389         { .pc_name = "list-commands", .pc_func = lfs_pcc_list_commands,
390           .pc_help = "list commands supported by lfs pcc"},
391         { .pc_name = "help", .pc_func = Parser_help, .pc_help = "help" },
392         { .pc_name = "exit", .pc_func = Parser_quit, .pc_help = "quit" },
393         { .pc_name = "quit", .pc_func = Parser_quit, .pc_help = "quit" },
394         { .pc_help = NULL }
395 };
396
397 /* all available commands */
398 command_t cmdlist[] = {
399         {"setstripe", lfs_setstripe, 0,
400          "To create a file with specified striping/composite layout, or\n"
401          "create/replace the default layout on an existing directory:\n"
402          SSM_CMD_COMMON("setstripe")
403          "                 [--mode MODE]\n"
404          "                 <directory|filename>\n"
405          " or\n"
406          "To add component(s) to an existing composite file:\n"
407          SSM_CMD_COMMON("setstripe --component-add")
408          SSM_HELP_COMMON
409          "To totally delete the default striping from an existing directory:\n"
410          "usage: setstripe [--delete|-d] <directory>\n"
411          " or\n"
412          "To create a mirrored file or set s default mirror layout on a directory:\n"
413          "usage: setstripe {--mirror-count|-N}[MIRROR_COUNT] [SETSTRIPE_OPTIONS] <directory|filename>\n"
414          " or\n"
415          "To delete the last component(s) from an existing composite file\n"
416          "(note that this will also delete any data in those components):\n"
417          "usage: setstripe --component-del [--component-id|-I COMP_ID]\n"
418          "                               [--component-flags|-F COMP_FLAGS]\n"
419          "                               <filename>\n"
420          "\tCOMP_ID:     Unique component ID to delete\n"
421          "\tCOMP_FLAGS:  'init' indicating all instantiated components\n"
422          "\t             '^init' indicating all uninstantiated components\n"
423          "\t-I and -F cannot be specified at the same time\n"
424          " or\n"
425          "To set or clear flags on a specific component\n"
426          "(note that this command can only be applied to mirrored files:\n"
427          "usage: setstripe --comp-set {-I COMP_ID|--comp-flags=COMP_FLAGS}\n"
428          "                            <filename>\n"
429          " or\n"
430          "To create a file with a foreign (free format) layout:\n"
431          "usage: setstripe --foreign[=FOREIGN_TYPE]\n"
432          "                 --xattr|-x LAYOUT_STRING [--flags HEX]\n"
433          "                 [--mode MODE] <filename>\n"},
434         {"getstripe", lfs_getstripe, 0,
435          "To list the layout pattern for a given file or files in a\n"
436          "directory or recursively for all files in a directory tree.\n"
437          "usage: getstripe [--ost|-O UUID] [--quiet|-q] [--verbose|-v]\n"
438          "                 [--stripe-count|-c] [--stripe-index|-i] [--fid|-F]\n"
439          "                 [--pool|-p] [--stripe-size|-S] [--directory|-d]\n"
440          "                 [--mdt-index|-m] [--recursive|-r] [--raw|-R]\n"
441          "                 [--layout|-L] [--generation|-g] [--yaml|-y]\n"
442          "                 [--help|-h] [--component-id|-I[=COMP_ID]]\n"
443          "                 [--component-flags[=COMP_FLAGS]]\n"
444          "                 [--component-count]\n"
445          "                 [--extension-size|--ext-size|-z]\n"
446          "                 [--component-start[=[+-]COMP_START]]\n"
447          "                 [--component-end[=[+-]COMP_END]|-E[[+-]comp_end]]\n"
448          "                 [[!] --mirror-index=[+-]INDEX |\n"
449          "                 [!] --mirror-id=[+-]MIRROR_ID] [--mirror-count|-N]\n"
450          "                 <directory|filename> ..."},
451         {"setdirstripe", lfs_setdirstripe, 0,
452          "Create striped directory on specified MDT, same as mkdir.\n"
453          "May be restricted to root or group users, depending on settings.\n"
454          "usage: setdirstripe [OPTION] <directory>\n"
455          SETDIRSTRIPE_USAGE},
456         {"getdirstripe", lfs_getdirstripe, 0,
457          "To list the layout pattern info for a given directory\n"
458          "or recursively for all directories in a directory tree.\n"
459          "usage: getdirstripe [--mdt-count|-c] [--mdt-index|-m|-i]\n"
460          "                    [--help|-h] [--mdt-hash|-H] [--obd|-O UUID]\n"
461          "                    [--recursive|-r] [--yaml|-y]\n"
462          "                    [--verbose|-v] [--default|-D]\n"
463          "                    [--max-inherit|-X]\n"
464          "                    [--max-inherit-rr] <dir> ..."},
465         {"mkdir", lfs_setdirstripe, 0,
466          "Create striped directory on specified MDT, same as setdirstripe.\n"
467          "usage: mkdir [OPTION] <directory>\n"
468          SETDIRSTRIPE_USAGE},
469         {"rm_entry", lfs_rmentry, 0,
470          "To remove the name entry of the remote directory. Note: This\n"
471          "command will only delete the name entry, i.e. the remote directory\n"
472          "will become inaccessable after this command. This can only be done\n"
473          "by the administrator\n"
474          "usage: rm_entry <dir>\n"},
475         {"unlink_foreign", lfs_unlink_foreign, 0,
476          "To remove the foreign file/dir.\n"
477          "Note: This is for files/dirs prevented to be removed using\n"
478          "unlink/rmdir, but works also for regular ones\n"
479          "usage: unlink_foreign <foreign_dir/file> [<foreign_dir/file> ...]\n"},
480         {"pool_list", lfs_poollist, 0,
481          "List pools or pool OSTs\n"
482          "usage: pool_list <fsname>[.<pool>] | <pathname>\n"},
483         {"find", lfs_find, 0,
484          "find files matching given attributes recursively in directory tree.\n"
485          "usage: find <directory|filename> ...\n"
486          "     [[!] --atime|-A [+-]N[smhdwy]] [[!] --ctime|-C [+-]N[smhdwy]]\n"
487          "     [[!] --mtime|-M [+-]N[smhdwy]]\n"
488          "     [[!] --btime|--Btime|-B [+-]N[smhdwy]] [--help|-h]\n"
489          "     [[!] --newer[XY] <reference>] [[!] --blocks|-b N]\n"
490          "     [--maxdepth|-D N] [[!] --mdt-index|--mdt|-m <uuid|index,...>]\n"
491          "     [[!] --name|-n <pattern>] [[!] --ost|-O <uuid|index,...>]\n"
492          "     [[!] --perm [/-]mode] [[!] --pool <pool>] [--print|-P]\n"
493          "     [--print0|-0] [[!] --projid <projid>]\n"
494          "     [[!] --size|-s [+-]N[bkMGTPE]]\n"
495          "     [[!] --stripe-count|-c [+-]<stripes>]\n"
496          "     [[!] --stripe-index|-i <index,...>]\n"
497          "     [[!] --stripe-size|-S [+-]N[kMGT]] [[!] --type|-t <filetype>]\n"
498          "     [[!] --extension-size|--ext-size|-z [+-]N[kMGT]]\n"
499          "     [[!] --gid|-g|--group|-G <gid>|<gname>]\n"
500          "     [[!] --uid|-u|--user|-U <uid>|<uname>]\n"
501          "     [[!] --layout|-L released,raid0,mdt]\n"
502          "     [[!] --foreign[=<foreign_type>]]\n"
503          "     [[!] --component-count [+-]<comp_cnt>]\n"
504          "     [[!] --component-start [+-]N[kMGTPE]]\n"
505          "     [[!] --component-end|-E [+-]N[kMGTPE]]\n"
506          "     [[!] --component-flags {init,stale,prefer,offline,nosync,extension}]\n"
507          "     [[!] --mirror-count|-N [+-]<n>]\n"
508          "     [[!] --mirror-state <[^]state>]\n"
509          "     [[!] --mdt-count|-T [+-]<stripes>]\n"
510          "     [[!] --mdt-hash|-H <[^][blm],[^]fnv_1a_64,all_char,crush,...>\n"
511          "     [[!] --mdt-index|-m <uuid|index,...>]\n"
512          "\t !: used before an option indicates 'NOT' requested attribute\n"
513          "\t -: used before a value indicates less than requested value\n"
514          "\t +: used before a value indicates more than requested value\n"
515          "\t ^: used before a flag indicates to exclude it\n"},
516         {"check", lfs_check, 0,
517          "Display the status of MGTs, MDTs or OSTs (as specified in the command)\n"
518          "or all the servers (MGTs, MDTs and OSTs).\n"
519          "usage: check {mgts|osts|mdts|all}"},
520         {"osts", lfs_osts, 0, "list OSTs connected to client "
521          "[for specified path only]\n" "usage: osts [path]"},
522         {"mdts", lfs_mdts, 0, "list MDTs connected to client "
523          "[for specified path only]\n" "usage: mdts [path]"},
524         {"df", lfs_df, 0,
525          "report filesystem disk space usage or inodes usage "
526          "of each MDS and all OSDs or a batch belonging to a specific pool.\n"
527          "Usage: df [--inodes|-i] [--human-readable|-h] [--lazy|-l]\n"
528          "          [--pool|-p <fsname>[.<pool>]] [path]"},
529         {"getname", lfs_getname, 0,
530          "list instances and specified mount points [for specified path only]\n"
531          "Usage: getname [--help|-h] [--instance|-i] [--fsname|-n] [path ...]"},
532 #ifdef HAVE_SYS_QUOTA_H
533         {"setquota", lfs_setquota, 0, "Set filesystem quotas.\n"
534          "usage: setquota {-u|-g|-p} UNAME|UID|GNAME|GID|PROJID\n"
535          "                -b BLOCK_SOFTLIMIT -B BLOCK_HARDLIMIT\n"
536          "                -i INODE_SOFTLIMIT -I INODE_HARDLIMIT <filesystem>\n"
537          "       setquota {-u|--user USER|UID|-g|--group GROUP|GID|-p|--projid PROJID}\n"
538          "                [--block-softlimit BLOCK_SOFTLIMIT]\n"
539          "                [--block-hardlimit BLOCK_HARDLIMIT]\n"
540          "                [--inode-softlimit INODE_SOFTLIMIT]\n"
541          "                [--inode-hardlimit INODE_HARDLIMIT] <filesystem>\n"
542          "       setquota [-t] {-h|--help|-u|--user|-g|--group|-p|--projid}\n"
543          "                [--block-grace 'notify'|BLOCK_GRACE]\n"
544          "                [--inode-grace 'notify'|INODE_GRACE] <filesystem>\n"
545          "       setquota {-U|-G|-P}\n"
546          "                -b BLOCK_SOFTLIMIT -B BLOCK_HARDLIMIT\n"
547          "                -i INODE_SOFTLIMIT -I INODE_HARDLIMIT <filesystem>\n"
548          "       setquota {-U|--default-usr|-G|--default-grp|-P|--default-prj}\n"
549          "                [--block-softlimit BLOCK_SOFTLIMIT]\n"
550          "                [--block-hardlimit BLOCK_HARDLIMIT]\n"
551          "                [--inode-softlimit INODE_SOFTLIMIT]\n"
552          "                [--inode-hardlimit INODE_HARDLIMIT] <filesystem>\n"
553          "       setquota {-u|-g|-p} UNAME|UID|GNAME|GID|PROJID\n"
554          "                {-d|--default}\n"
555          "       -b can be used instead of --block-softlimit/--block-grace\n"
556          "       -B can be used instead of --block-hardlimit\n"
557          "       -i can be used instead of --inode-softlimit/--inode-grace\n"
558          "       -I can be used instead of --inode-hardlimit\n"
559          "       -d can be used instead of --default\n\n"
560          "Note: The total quota space will be split into many qunits and\n"
561          "      balanced over all server targets, the minimal qunit size is\n"
562          "      1M bytes for block space and 1K inodes for inode space.\n\n"
563          "      The maximum quota grace time is 2^48 - 1 seconds.\n\n"
564          "      Quota space rebalancing process will stop when this mininum\n"
565          "      value is reached. As a result, quota exceeded can be returned\n"
566          "      while many targets still have 1MB or 1K inodes of spare\n"
567          "      quota space.\n\n"
568          "      When setting the grace time, 'notify' can be used as grace to\n"
569          "      be notified after the quota is over soft limit but prevents\n"
570          "      the soft limit from becoming the hard limit."},
571         {"quota", lfs_quota, 0, "Display disk usage and limits.\n"
572          "usage: quota [-q] [-v] [-h] [-o OBD_UUID|-i MDT_IDX|-I OST_IDX]\n"
573          "             [{-u|-g|-p} UNAME|UID|GNAME|GID|PROJID] <filesystem>\n"
574          "       quota [-o OBD_UUID|-i MDT_IDX|-I OST_IDX] -t {-u|-g|-p} <filesystem>\n"
575         "        quota [-q] [-v] [h] {-U|-G|-P} <filesystem>"},
576         {"project", lfs_project, 0,
577          "Change or list project attribute for specified file or directory.\n"
578          "usage: project [-d|-r] <file|directory...>\n"
579          "         list project ID and flags on file(s) or directories\n"
580          "       project [-p id] [-s] [-r] <file|directory...>\n"
581          "         set project ID and/or inherit flag for specified file(s) or directories\n"
582          "       project -c [-d|-r [-p id] [-0]] <file|directory...>\n"
583          "         check project ID and flags on file(s) or directories, print outliers\n"
584          "       project -C [-r] [-k] <file|directory...>\n"
585          "         clear the project inherit flag and ID on the file or directory\n"
586         },
587 #endif
588         {"flushctx", lfs_flushctx, 0,
589          "Flush security context for current user.\n"
590          "usage: flushctx [-k] [-r] [mountpoint...]"},
591         {"changelog", lfs_changelog, 0,
592          "Show the metadata changes on an MDT."
593          "\nusage: changelog <mdtname> [startrec [endrec]]"},
594         {"changelog_clear", lfs_changelog_clear, 0,
595          "Indicate that old changelog records up to <endrec> are no longer of "
596          "interest to consumer <id>, allowing the system to free up space.\n"
597          "An <endrec> of 0 means all records.\n"
598          "usage: changelog_clear <mdtname> <id> <endrec>"},
599         {"fid2path", lfs_fid2path, 0,
600          "Resolve the full path(s) for given FID(s). For a specific hardlink "
601          "specify link number <linkno>.\n"
602          "usage: fid2path [--print-fid|-f] [--print-link|-c] [--link|-l <linkno>] "
603          "<fsname|root> <fid>..."},
604         {"path2fid", lfs_path2fid, 0, "Display the fid(s) for a given path(s).\n"
605          "usage: path2fid [--parents] <path> ..."},
606         {"rmfid", lfs_rmfid, 0, "Remove file(s) by FID(s)\n"
607          "usage: rmfid <fsname|rootpath> <fid> ..."},
608         {"data_version", lfs_data_version, 0, "Display file data version for "
609          "a given path.\n" "usage: data_version [-n|-r|-w] <path>"},
610         {"hsm_state", lfs_hsm_state, 0, "Display the HSM information (states, "
611          "undergoing actions) for given files.\n usage: hsm_state <file> ..."},
612         {"hsm_set", lfs_hsm_set, 0, "Set HSM user flag on specified files.\n"
613          "usage: hsm_set [--norelease] [--noarchive] [--dirty] [--exists] "
614          "[--archived] [--lost] [--archive-id NUM] <file> ..."},
615         {"hsm_clear", lfs_hsm_clear, 0, "Clear HSM user flag on specified "
616          "files.\n"
617          "usage: hsm_clear [--norelease] [--noarchive] [--dirty] [--exists] "
618          "[--archived] [--lost] <file> ..."},
619         {"hsm_action", lfs_hsm_action, 0, "Display current HSM request for "
620          "given files.\n" "usage: hsm_action <file> ..."},
621         {"hsm_archive", lfs_hsm_archive, 0,
622          "Archive file to external storage.\n"
623          "usage: hsm_archive [--filelist FILELIST] [--data DATA] [--archive NUM] "
624          "<file> ..."},
625         {"hsm_restore", lfs_hsm_restore, 0,
626          "Restore file from external storage.\n"
627          "usage: hsm_restore [--filelist FILELIST] [--data DATA] <file> ..."},
628         {"hsm_release", lfs_hsm_release, 0,
629          "Release files from Lustre.\n"
630          "usage: hsm_release [--filelist FILELIST] [--data DATA] <file> ..."},
631         {"hsm_remove", lfs_hsm_remove, 0,
632          "Remove file copy from external storage.\n"
633          "usage: hsm_remove [--filelist FILELIST] [--data DATA] "
634          "[--archive NUM]\n"
635          "                  (FILE [FILE ...] | "
636          "--mntpath MOUNTPATH FID [FID ...])\n"
637          "\n"
638          "Note: To remove an archived copy of a file already deleted from a "
639          "Lustre FS, the\n"
640          "--mntpath option and a list of FIDs must be specified"
641         },
642         {"hsm_cancel", lfs_hsm_cancel, 0,
643          "Cancel requests related to specified files.\n"
644          "usage: hsm_cancel [--filelist FILELIST] [--data DATA] <file> ..."},
645         {"swap_layouts", lfs_swap_layouts, 0, "Swap layouts between 2 files.\n"
646          "usage: swap_layouts <path1> <path2>"},
647         {"migrate", lfs_setstripe_migrate, 0,
648          "migrate a directory between MDTs.\n"
649          "usage: migrate [--mdt-count|-c STRIPE_COUNT]\n"
650          "               [--mdt-hash|-H HASH_TYPE]\n"
651          "               [--mdt-index|-m START_MDT_INDEX] [--verbose|-v]\n"
652          "               <directory>\n"
653          "\tmdt:        MDTs to stripe over, if only one MDT is specified\n"
654          "                      it's the MDT index of first stripe\n"
655          "\tmdt_count:  number of MDTs to stripe a directory over\n"
656          "\tmdt_hash:   hash type of the striped directory. mdt types:\n"
657          "              all_char  (type 1)sum of characters % MDT_COUNT\n"
658          "              fnv_1a_64 (type 2)FNV-1a hash algorithm (default)\n"
659          "              crush     (type 3)CRUSH hash algorithm\n"
660          "\n"
661          "migrate file objects from one OST "
662          "layout\nto another (may be not safe with concurent writes).\n"
663          "usage: migrate [--stripe-count|-c STRIPE_COUNT]\n"
664          "               [--overstripe-count|-C STRIPE_COUNT]\n"
665          "               [--stripe-index|-i START_OST_INDEX]\n"
666          "               [--stripe-size|-S STRIPE_SIZE]\n"
667          "               [--pool|-p <pool_name>] [--ost|-o OST_INDICES]\n"
668          "               [--block|-b] [--non-block|-n] [--non-direct|-D]\n"
669          "               <file|directory>\n"
670          "\tstripe_count:   number of OSTs to stripe a file over\n"
671          "\t                Using -C instead of -c allows overstriping, which\n"
672          "\t                will place more than one stripe per OST if\n"
673          "\t                stripe_count is greater than the number of OSTs\n"
674          "\tstripe_ost_index: index of the first OST to stripe a file over\n"
675          "\tstripe_size:      number of bytes to store before moving to the next OST\n"
676          "\tpool_name:        name of the predefined pool of OSTs\n"
677          "\tost_indices:      OSTs to stripe over, in order\n"
678          "\tblock:        Block file access during data migration (default)\n"
679          "\tnon-block:    Abort migrations if concurrent access is detected\n"
680          "\tnon-direct:       do not use direct I/O to copy file contents.\n"},
681         {"mv", lfs_mv, 0,
682          "To move directories between MDTs. This command is deprecated, "
683          "use \"migrate\" instead.\n"
684          "usage: mv <directory|filename> [--mdt-index|-m MDT_INDEX] "
685          "[--verbose|-v]\n"},
686         {"ladvise", lfs_ladvise, 0,
687          "Provide servers with advice about access patterns for a file.\n"
688          "usage: ladvise [--advice|-a ADVICE] [--start|-s START[kMGT]]\n"
689          "               [--background|-b] [--unset|-u]\n\n"
690          "               {--end|-e END[kMGT]|--length|-l LENGTH[kMGT]}\n"
691          "               {[--mode|-m [READ,WRITE]}\n"
692          "               <file> ...\n"},
693         {"mirror", lfs_mirror, mirror_cmdlist,
694          "lfs commands used to manage files with mirrored components:\n"
695          "lfs mirror create - create a mirrored file or directory\n"
696          "lfs mirror extend - add mirror(s) to an existing file\n"
697          "lfs mirror split  - split a mirror from an existing mirrored file\n"
698          "lfs mirror resync - resynchronize out-of-sync mirrored file(s)\n"
699          "lfs mirror read   - read a mirror content of a mirrored file\n"
700          "lfs mirror write  - write to a mirror of a mirrored file\n"
701          "lfs mirror copy   - copy a mirror to other mirror(s) of a file\n"
702          "lfs mirror verify - verify mirrored file(s)\n"},
703         {"getsom", lfs_getsom, 0, "To list the SOM info for a given file.\n"
704          "usage: getsom [-s] [-b] [-f] <path>\n"
705          "\t-s: Only show the size value of the SOM data for a given file\n"
706          "\t-b: Only show the blocks value of the SOM data for a given file\n"
707          "\t-f: Only show the flags value of the SOM data for a given file\n"},
708         {"heat_get", lfs_heat_get, 0,
709          "To get heat of files.\n"
710          "usage: heat_get <file> ...\n"},
711         {"heat_set", lfs_heat_set, 0,
712          "To set heat flags of files.\n"
713          "usage: heat_set [--clear|-c] [--off|-o] [--on|-O] <file> ...\n"
714          "\t--clear|-c: Clear file heat for given files\n"
715          "\t--off|-o:   Turn off file heat for given files\n"
716          "\t--on|-O:    Turn on file heat for given files\n"},
717         {"pcc", lfs_pcc, pcc_cmdlist,
718          "lfs commands used to interact with PCC features:\n"
719          "lfs pcc attach - attach given files to Persistent Client Cache\n"
720          "lfs pcc attach_fid - attach given files into PCC by FID(s)\n"
721          "lfs pcc state  - display the PCC state for given files\n"
722          "lfs pcc detach - detach given files from Persistent Client Cache\n"
723          "lfs pcc detach_fid - detach given files from PCC by FID(s)\n"},
724         {"help", Parser_help, 0, "help"},
725         {"exit", Parser_quit, 0, "quit"},
726         {"quit", Parser_quit, 0, "quit"},
727         {"--version", Parser_version, 0,
728          "output build version of the utility and exit"},
729         {"--list-commands", lfs_list_commands, 0,
730          "list commands supported by the utility and exit"},
731         { 0, 0, 0, NULL }
732 };
733
734 static int check_hashtype(const char *hashtype)
735 {
736         int type_num = atoi(hashtype);
737         int i;
738
739         /* numeric hash type */
740         if (hashtype && strlen(hashtype) == 1 &&
741             (type_num > 0 && type_num < LMV_HASH_TYPE_MAX))
742                 return type_num;
743         /* string hash type */
744         for (i = LMV_HASH_TYPE_ALL_CHARS; i < LMV_HASH_TYPE_MAX; i++)
745                 if (strcmp(hashtype, mdt_hash_name[i]) == 0)
746                         return i;
747
748         return 0;
749 }
750
751 static uint32_t check_foreign_type_name(const char *foreign_type_name)
752 {
753         uint32_t i;
754
755         for (i = 0; i < LU_FOREIGN_TYPE_UNKNOWN; i++) {
756                 if (!lu_foreign_types[i].lft_name)
757                         break;
758                 if (strcmp(foreign_type_name,
759                            lu_foreign_types[i].lft_name) == 0)
760                         return lu_foreign_types[i].lft_type;
761         }
762
763         return LU_FOREIGN_TYPE_UNKNOWN;
764 }
765
766 static const char *error_loc = "syserror";
767
768 enum {
769         MIGRATION_NONBLOCK      = 0x0001,
770         MIGRATION_MIRROR        = 0x0002,
771         MIGRATION_NONDIRECT     = 0x0004,
772         MIGRATION_VERBOSE       = 0x0008,
773 };
774
775 static int
776 migrate_open_files(const char *name, __u64 migration_flags,
777                    const struct llapi_stripe_param *param,
778                    struct llapi_layout *layout, int *fd_src, int *fd_tgt)
779 {
780         int                      fd = -1;
781         int                      fdv = -1;
782         int                      rflags;
783         int                      mdt_index;
784         int                      random_value;
785         char                     parent[PATH_MAX];
786         char                     volatile_file[PATH_MAX];
787         char                    *ptr;
788         int                      rc;
789         struct stat              st;
790         struct stat              stv;
791
792         if (!param && !layout) {
793                 error_loc = "layout information";
794                 return -EINVAL;
795         }
796
797         /* search for file directory pathname */
798         if (strlen(name) > sizeof(parent) - 1) {
799                 error_loc = "source file name";
800                 return -ERANGE;
801         }
802
803         strncpy(parent, name, sizeof(parent));
804         ptr = strrchr(parent, '/');
805         if (!ptr) {
806                 if (!getcwd(parent, sizeof(parent))) {
807                         error_loc = "getcwd";
808                         return -errno;
809                 }
810         } else {
811                 if (ptr == parent) /* leading '/' */
812                         ptr = parent + 1;
813                 *ptr = '\0';
814         }
815
816         /* open file, direct io */
817         /* even if the file is only read, WR mode is nedeed to allow
818          * layout swap on fd
819          */
820         rflags = O_RDWR | O_NOATIME;
821         if (!(migration_flags & MIGRATION_NONDIRECT))
822                 rflags |= O_DIRECT;
823         fd = open(name, rflags);
824         if (fd < 0) {
825                 rc = -errno;
826                 error_loc = "cannot open source file";
827                 return rc;
828         }
829
830         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
831         if (rc < 0) {
832                 error_loc = "cannot get MDT index";
833                 goto out;
834         }
835
836         do {
837                 int open_flags = O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW;
838                 mode_t open_mode = S_IRUSR | S_IWUSR;
839
840                 random_value = random();
841                 rc = snprintf(volatile_file, sizeof(volatile_file),
842                               "%s/%s:%.4X:%.4X:fd=%.2d", parent,
843                               LUSTRE_VOLATILE_HDR, mdt_index,
844                               random_value, fd);
845                 if (rc >= sizeof(volatile_file)) {
846                         rc = -ENAMETOOLONG;
847                         break;
848                 }
849
850                 /* create, open a volatile file, use caching (ie no directio) */
851                 if (layout) {
852                         /* Returns -1 and sets errno on error: */
853                         fdv = llapi_layout_file_open(volatile_file, open_flags,
854                                                      open_mode, layout);
855                         if (fdv < 0)
856                                 fdv = -errno;
857                 } else {
858                         /* Does the right thing on error: */
859                         fdv = llapi_file_open_param(volatile_file, open_flags,
860                                                     open_mode, param);
861                 }
862         } while (fdv < 0 && (rc = fdv) == -EEXIST);
863
864         if (rc < 0) {
865                 error_loc = "cannot create volatile file";
866                 goto out;
867         }
868
869         /*
870          * In case the MDT does not support creation of volatile files
871          * we should try to unlink it.
872          */
873         (void)unlink(volatile_file);
874
875         /*
876          * Not-owner (root?) special case.
877          * Need to set owner/group of volatile file like original.
878          * This will allow to pass related check during layout_swap.
879          */
880         rc = fstat(fd, &st);
881         if (rc != 0) {
882                 rc = -errno;
883                 error_loc = "cannot stat source file";
884                 goto out;
885         }
886
887         rc = fstat(fdv, &stv);
888         if (rc != 0) {
889                 rc = -errno;
890                 error_loc = "cannot stat volatile";
891                 goto out;
892         }
893
894         if (st.st_uid != stv.st_uid || st.st_gid != stv.st_gid) {
895                 rc = fchown(fdv, st.st_uid, st.st_gid);
896                 if (rc != 0) {
897                         rc = -errno;
898                         error_loc = "cannot change ownwership of volatile";
899                         goto out;
900                 }
901         }
902
903 out:
904         if (rc < 0) {
905                 if (fd > 0)
906                         close(fd);
907                 if (fdv > 0)
908                         close(fdv);
909         } else {
910                 *fd_src = fd;
911                 *fd_tgt = fdv;
912                 error_loc = NULL;
913         }
914         return rc;
915 }
916
917 static int migrate_copy_data(int fd_src, int fd_dst, int (*check_file)(int))
918 {
919         struct llapi_layout *layout;
920         size_t buf_size = 4 * 1024 * 1024;
921         void *buf = NULL;
922         off_t pos = 0;
923         off_t data_end = 0;
924         size_t page_size = sysconf(_SC_PAGESIZE);
925         bool sparse;
926         int rc;
927
928         layout = llapi_layout_get_by_fd(fd_src, 0);
929         if (layout) {
930                 uint64_t stripe_size;
931
932                 rc = llapi_layout_stripe_size_get(layout, &stripe_size);
933                 if (rc == 0)
934                         buf_size = stripe_size;
935
936                 llapi_layout_free(layout);
937         }
938
939         /* Use a page-aligned buffer for direct I/O */
940         rc = posix_memalign(&buf, page_size, buf_size);
941         if (rc != 0)
942                 return -rc;
943
944         sparse = llapi_file_is_sparse(fd_src);
945         if (sparse) {
946                 rc = ftruncate(fd_dst, pos);
947                 if (rc < 0) {
948                         rc = -errno;
949                         return rc;
950                 }
951         }
952
953         while (1) {
954                 off_t data_off;
955                 size_t to_read, to_write;
956                 ssize_t rsize;
957
958                 if (sparse && pos >= data_end) {
959                         size_t data_size;
960
961                         data_off = llapi_data_seek(fd_src, pos, &data_size);
962                         if (data_off < 0) {
963                                 /* Non-fatal, switch to full copy */
964                                 sparse = false;
965                                 continue;
966                         }
967                         /* hole at the end of file, truncate up to it */
968                         if (!data_size) {
969                                 rc = ftruncate(fd_dst, data_off);
970                                 if (rc < 0)
971                                         goto out;
972                         }
973                         pos = data_off & ~(page_size - 1);
974                         data_end = data_off + data_size;
975                         to_read = ((data_end - pos - 1) | (page_size - 1)) + 1;
976                         to_read = MIN(to_read, buf_size);
977                 } else {
978                         to_read = buf_size;
979                 }
980
981                 if (check_file) {
982                         rc = check_file(fd_src);
983                         if (rc < 0)
984                                 goto out;
985                 }
986
987                 rsize = pread(fd_src, buf, to_read, pos);
988                 if (rsize < 0) {
989                         rc = -errno;
990                         goto out;
991                 }
992                 /* EOF */
993                 if (rsize == 0)
994                         break;
995
996                 to_write = rsize;
997                 while (to_write > 0) {
998                         ssize_t written;
999
1000                         written = pwrite(fd_dst, buf, to_write, pos);
1001                         if (written < 0) {
1002                                 rc = -errno;
1003                                 goto out;
1004                         }
1005                         pos += written;
1006                         to_write -= written;
1007                 }
1008                 if (rc || rsize < to_read)
1009                         break;
1010         }
1011
1012         rc = fsync(fd_dst);
1013         if (rc < 0)
1014                 rc = -errno;
1015 out:
1016         /* Try to avoid page cache pollution after migration. */
1017         (void)posix_fadvise(fd_src, 0, 0, POSIX_FADV_DONTNEED);
1018         (void)posix_fadvise(fd_dst, 0, 0, POSIX_FADV_DONTNEED);
1019
1020         free(buf);
1021         return rc;
1022 }
1023
1024 static int migrate_set_timestamps(int fd, const struct stat *st)
1025 {
1026         struct timeval tv[2] = {
1027                 {.tv_sec = st->st_atime},
1028                 {.tv_sec = st->st_mtime}
1029         };
1030
1031         return futimes(fd, tv);
1032 }
1033
1034 static int migrate_block(int fd, int fdv)
1035 {
1036         struct stat st;
1037         __u64   dv1;
1038         int     gid;
1039         int     rc;
1040         int     rc2;
1041
1042         rc = fstat(fd, &st);
1043         if (rc < 0) {
1044                 error_loc = "cannot stat source file";
1045                 return -errno;
1046         }
1047
1048         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
1049         if (rc < 0) {
1050                 error_loc = "cannot get dataversion";
1051                 return rc;
1052         }
1053
1054         do
1055                 gid = random();
1056         while (gid == 0);
1057
1058         /*
1059          * The grouplock blocks all concurrent accesses to the file.
1060          * It has to be taken after llapi_get_data_version as it would
1061          * block it too.
1062          */
1063         rc = llapi_group_lock(fd, gid);
1064         if (rc < 0) {
1065                 error_loc = "cannot get group lock";
1066                 return rc;
1067         }
1068
1069         rc = migrate_copy_data(fd, fdv, NULL);
1070         if (rc < 0) {
1071                 error_loc = "data copy failed";
1072                 goto out_unlock;
1073         }
1074
1075         /* Make sure we keep original atime/mtime values */
1076         rc = migrate_set_timestamps(fdv, &st);
1077         if (rc < 0) {
1078                 error_loc = "set target file timestamp failed";
1079                 goto out_unlock;
1080         }
1081
1082         /*
1083          * swap layouts
1084          * for a migration we need to check data version on file did
1085          * not change.
1086          *
1087          * Pass in gid=0 since we already own grouplock.
1088          */
1089         rc = llapi_fswap_layouts_grouplock(fd, fdv, dv1, 0, 0,
1090                                            SWAP_LAYOUTS_CHECK_DV1);
1091         if (rc == -EAGAIN) {
1092                 error_loc = "file changed";
1093                 goto out_unlock;
1094         } else if (rc < 0) {
1095                 error_loc = "cannot swap layout";
1096                 goto out_unlock;
1097         }
1098
1099 out_unlock:
1100         rc2 = llapi_group_unlock(fd, gid);
1101         if (rc2 < 0 && rc == 0) {
1102                 error_loc = "unlock group lock";
1103                 rc = rc2;
1104         }
1105
1106         return rc;
1107 }
1108
1109 /**
1110  * Internal helper for migrate_copy_data(). Check lease and report error if
1111  * need be.
1112  *
1113  * \param[in]  fd           File descriptor on which to check the lease.
1114  *
1115  * \retval 0       Migration can keep on going.
1116  * \retval -errno  Error occurred, abort migration.
1117  */
1118 static int check_lease(int fd)
1119 {
1120         int rc;
1121
1122         rc = llapi_lease_check(fd);
1123         if (rc > 0)
1124                 return 0; /* llapi_check_lease returns > 0 on success. */
1125
1126         return -EBUSY;
1127 }
1128
1129 static int migrate_nonblock(int fd, int fdv)
1130 {
1131         struct stat st;
1132         __u64   dv1;
1133         __u64   dv2;
1134         int     rc;
1135
1136         rc = fstat(fd, &st);
1137         if (rc < 0) {
1138                 error_loc = "cannot stat source file";
1139                 return -errno;
1140         }
1141
1142         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
1143         if (rc < 0) {
1144                 error_loc = "cannot get data version";
1145                 return rc;
1146         }
1147
1148         rc = migrate_copy_data(fd, fdv, check_lease);
1149         if (rc < 0) {
1150                 error_loc = "data copy failed";
1151                 return rc;
1152         }
1153
1154         rc = llapi_get_data_version(fd, &dv2, LL_DV_RD_FLUSH);
1155         if (rc != 0) {
1156                 error_loc = "cannot get data version";
1157                 return rc;
1158         }
1159
1160         if (dv1 != dv2) {
1161                 rc = -EAGAIN;
1162                 error_loc = "source file changed";
1163                 return rc;
1164         }
1165
1166         /* Make sure we keep original atime/mtime values */
1167         rc = migrate_set_timestamps(fdv, &st);
1168         if (rc < 0) {
1169                 error_loc = "set target file timestamp failed";
1170                 return -errno;
1171         }
1172         return 0;
1173 }
1174
1175 static
1176 int lfs_layout_compid_by_pool(char *fname, const char *pool, int *comp_id)
1177 {
1178         struct pool_to_id_cbdata data = { .pool = pool };
1179         struct llapi_layout *layout = NULL;
1180         int rc;
1181
1182         layout = llapi_layout_get_by_path(fname, 0);
1183         if (!layout) {
1184                 fprintf(stderr,
1185                         "error %s: file '%s' couldn't get layout: rc=%d\n",
1186                         progname, fname, errno);
1187                 rc = -errno;
1188                 goto free_layout;
1189         }
1190         rc = llapi_layout_sanity(layout, fname, false, true);
1191         if (rc < 0) {
1192                 llapi_layout_sanity_perror(errno);
1193                 goto free_layout;
1194         }
1195         rc = llapi_layout_comp_iterate(layout, find_comp_id_by_pool, &data);
1196         if (rc < 0)
1197                 goto free_layout;
1198
1199         *comp_id = data.id;
1200         rc = 0;
1201
1202 free_layout:
1203         if (layout)
1204                 llapi_layout_free(layout);
1205         return rc;
1206 }
1207
1208 static int lfs_component_set(char *fname, int comp_id, const char *pool,
1209                              __u32 flags, __u32 neg_flags)
1210 {
1211         __u32 ids[2];
1212         __u32 flags_array[2];
1213         size_t count = 0;
1214         int rc;
1215
1216         if (!comp_id) {
1217                 if (pool == NULL) {
1218                         fprintf(stderr,
1219                                 "error %s: neither component id nor pool is specified\n",
1220                                 progname);
1221                         return -EINVAL;
1222                 }
1223                 rc = lfs_layout_compid_by_pool(fname, pool, &comp_id);
1224                 if (rc)
1225                         return rc;
1226         }
1227
1228         if (flags) {
1229                 ids[count] = comp_id;
1230                 flags_array[count] = flags;
1231                 ++count;
1232         }
1233
1234         if (neg_flags) {
1235                 if (neg_flags & LCME_FL_STALE) {
1236                         fprintf(stderr,
1237                                 "%s: cannot clear 'stale' flags from component. Please use lfs-mirror-resync(1) instead\n",
1238                                 progname);
1239                         return -EINVAL;
1240                 }
1241
1242                 ids[count] = comp_id;
1243                 flags_array[count] = neg_flags | LCME_FL_NEG;
1244                 ++count;
1245         }
1246
1247         rc = llapi_layout_file_comp_set(fname, ids, flags_array, count);
1248         if (rc) {
1249                 if (errno == EUCLEAN) {
1250                         rc = -errno;
1251                         fprintf(stderr,
1252                                 "%s: cannot set 'stale' flag on component '%#x' of the last non-stale mirror of '%s'\n",
1253                                 progname, comp_id, fname);
1254                 } else {
1255                         fprintf(stderr,
1256                                 "%s: cannot change the flags of component '%#x' of file '%s': %x / ^(%x)\n",
1257                                 progname, comp_id, fname, flags, neg_flags);
1258                 }
1259         }
1260
1261         return rc;
1262 }
1263
1264 static int lfs_component_del(char *fname, __u32 comp_id,
1265                              __u32 flags, __u32 neg_flags)
1266 {
1267         int     rc = 0;
1268
1269         if (flags && neg_flags)
1270                 return -EINVAL;
1271
1272         if (!flags && neg_flags)
1273                 flags = neg_flags | LCME_FL_NEG;
1274
1275         if ((flags && comp_id) || (!flags && !comp_id))
1276                 return -EINVAL;
1277
1278         if (flags) {
1279                 if (flags & ~LCME_KNOWN_FLAGS) {
1280                         fprintf(stderr,
1281                                 "%s setstripe: unknown flags %#x\n",
1282                                 progname, flags);
1283                         return -EINVAL;
1284                 }
1285         } else if (comp_id > LCME_ID_MAX) {
1286                 fprintf(stderr, "%s setstripe: invalid component id %u\n",
1287                         progname, comp_id);
1288                 return -EINVAL;
1289         }
1290
1291         rc = llapi_layout_file_comp_del(fname, comp_id, flags);
1292         if (rc)
1293                 fprintf(stderr,
1294                         "%s setstripe: cannot delete component %#x from '%s': %s\n",
1295                         progname, comp_id, fname, strerror(errno));
1296         return rc;
1297 }
1298
1299 static int lfs_component_add(char *fname, struct llapi_layout *layout)
1300 {
1301         int     rc;
1302
1303         if (!layout)
1304                 return -EINVAL;
1305
1306         rc = llapi_layout_file_comp_add(fname, layout);
1307         if (rc)
1308                 fprintf(stderr, "Add layout component(s) to %s failed. %s\n",
1309                         fname, strerror(errno));
1310         return rc;
1311 }
1312
1313 static int lfs_component_create(char *fname, int open_flags, mode_t open_mode,
1314                                 struct llapi_layout *layout)
1315 {
1316         struct stat     st;
1317         int     fd;
1318
1319         if (!layout)
1320                 return -EINVAL;
1321
1322         fd = lstat(fname, &st);
1323         if (fd == 0 && S_ISDIR(st.st_mode))
1324                 open_flags = O_DIRECTORY | O_RDONLY;
1325
1326         fd = llapi_layout_file_open(fname, open_flags, open_mode, layout);
1327         if (fd < 0)
1328                 fprintf(stderr, "%s: cannot %s '%s': %s\n", progname,
1329                         S_ISDIR(st.st_mode) ?
1330                                 "set default composite layout for" :
1331                                 "create composite file",
1332                         fname, strerror(errno));
1333         return fd;
1334 }
1335
1336 static int lfs_migrate(char *name, __u64 migration_flags,
1337                        struct llapi_stripe_param *param,
1338                        struct llapi_layout *layout)
1339 {
1340         struct llapi_layout *existing;
1341         uint64_t dom_new, dom_cur;
1342         int fd = -1;
1343         int fdv = -1;
1344         int rc;
1345
1346         rc = migrate_open_files(name, migration_flags, param, layout,
1347                                 &fd, &fdv);
1348         if (rc < 0)
1349                 goto out;
1350
1351         rc = llapi_layout_dom_size(layout, &dom_new);
1352         if (rc) {
1353                 error_loc = "cannot get new layout DoM size";
1354                 goto out;
1355         }
1356         /* special case for migration to DOM layout*/
1357         existing = llapi_layout_get_by_fd(fd, 0);
1358         if (!existing) {
1359                 error_loc = "cannot get existing layout";
1360                 goto out;
1361         }
1362
1363         rc = llapi_layout_dom_size(existing, &dom_cur);
1364         if (rc) {
1365                 error_loc = "cannot get current layout DoM size";
1366                 goto out;
1367         }
1368
1369         /*
1370          * if file has DoM layout already then migration is possible to
1371          * the new layout with the same DoM component via swap layout,
1372          * if new layout used bigger DOM size, then mirroring is used
1373          */
1374         if (dom_new > dom_cur) {
1375                 rc = lfs_migrate_to_dom(fd, fdv, name, migration_flags, param,
1376                                         layout);
1377                 if (rc)
1378                         error_loc = "cannot migrate to DOM layout";
1379                 goto out_closed;
1380         }
1381
1382         if (!(migration_flags & MIGRATION_NONBLOCK)) {
1383                 /*
1384                  * Blocking mode (forced if servers do not support file lease).
1385                  * It is also the default mode, since we cannot distinguish
1386                  * between a broken lease and a server that does not support
1387                  * atomic swap/close (LU-6785)
1388                  */
1389                 rc = migrate_block(fd, fdv);
1390                 goto out;
1391         }
1392
1393         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1394         if (rc < 0) {
1395                 error_loc = "cannot get lease";
1396                 goto out;
1397         }
1398
1399         rc = migrate_nonblock(fd, fdv);
1400         if (rc < 0) {
1401                 llapi_lease_release(fd);
1402                 goto out;
1403         }
1404
1405         /*
1406          * Atomically put lease, swap layouts and close.
1407          * for a migration we need to check data version on file did
1408          * not change.
1409          */
1410         rc = llapi_fswap_layouts(fd, fdv, 0, 0, SWAP_LAYOUTS_CLOSE);
1411         if (rc < 0) {
1412                 error_loc = "cannot swap layout";
1413                 goto out;
1414         }
1415
1416 out:
1417         if (fd >= 0)
1418                 close(fd);
1419
1420         if (fdv >= 0)
1421                 close(fdv);
1422 out_closed:
1423         if (rc < 0)
1424                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1425                         progname, name, error_loc, strerror(-rc));
1426         else if (migration_flags & MIGRATION_VERBOSE)
1427                 printf("%s\n", name);
1428
1429         return rc;
1430 }
1431
1432 static int comp_str2flags(char *string, __u32 *flags, __u32 *neg_flags)
1433 {
1434         char *name;
1435         char *dup_string = NULL;
1436         int rc = 0;
1437
1438         *flags = 0;
1439         *neg_flags = 0;
1440
1441         if (!string || !string[0])
1442                 return -EINVAL;
1443
1444         dup_string = strdup(string);
1445         if (!dup_string) {
1446                 llapi_printf(LLAPI_MSG_ERROR,
1447                              "%s: insufficient memory\n",
1448                              progname);
1449                 return -ENOMEM;
1450         }
1451
1452         for (name = strtok(dup_string, ","); name; name = strtok(NULL, ",")) {
1453                 bool found = false;
1454                 int i;
1455
1456                 for (i = 0; i < ARRAY_SIZE(comp_flags_table); i++) {
1457                         __u32 comp_flag = comp_flags_table[i].cfn_flag;
1458                         const char *comp_name = comp_flags_table[i].cfn_name;
1459
1460                         if (strcmp(name, comp_name) == 0) {
1461                                 *flags |= comp_flag;
1462                                 found = true;
1463                         } else if (strncmp(name, "^", 1) == 0 &&
1464                                    strcmp(name + 1, comp_name) == 0) {
1465                                 *neg_flags |= comp_flag;
1466                                 found = true;
1467                         }
1468                 }
1469                 if (!found) {
1470                         llapi_printf(LLAPI_MSG_ERROR,
1471                                      "%s: component flag '%s' not supported\n",
1472                                      progname, name);
1473                         rc = -EINVAL;
1474                         goto out_free;
1475                 }
1476         }
1477
1478         if (!*flags && !*neg_flags)
1479                 rc = -EINVAL;
1480
1481         /* don't allow to set and exclude the same flag */
1482         if (*flags & *neg_flags)
1483                 rc = -EINVAL;
1484
1485 out_free:
1486         free(dup_string);
1487         return rc;
1488 }
1489
1490 static int mdthash_input(char *string, __u32 *inflags,
1491                          __u32 *exflags, __u32 *type)
1492 {
1493         char *name;
1494         struct mhf_list {
1495                 char *name;
1496                 __u32 flag;
1497         } mhflist[] = {
1498                 {"migrating", LMV_HASH_FLAG_MIGRATION},
1499                 {"badtype", LMV_HASH_FLAG_BAD_TYPE},
1500                 {"lostlmv", LMV_HASH_FLAG_LOST_LMV},
1501         };
1502
1503         if (string == NULL)
1504                 return -EINVAL;
1505
1506         *inflags = 0;
1507         *exflags = 0;
1508         *type = 0;
1509         for (name = strtok(string, ","); name; name = strtok(NULL, ",")) {
1510                 bool found = false;
1511                 int i;
1512
1513                 for (i = 0; i < ARRAY_SIZE(mhflist); i++) {
1514                         if (strcmp(name, mhflist[i].name) == 0 ||
1515                             name[0] == mhflist[i].name[0]) {
1516                                 *inflags |= mhflist[i].flag;
1517                                 found = true;
1518                         } else if (name[0] == '^' &&
1519                                    (strcmp(name + 1, mhflist[i].name) == 0 ||
1520                                     name[1] == mhflist[i].name[0])) {
1521                                 *exflags |= mhflist[i].flag;
1522                                 found = true;
1523                         }
1524                 }
1525                 if (!found) {
1526                         i = check_hashtype(name);
1527                         if (i > 0) {
1528                                 *type |= 1 << i;
1529                                 continue;
1530                         }
1531                         llapi_printf(LLAPI_MSG_ERROR,
1532                                      "%s: invalid mdt_hash value '%s'\n",
1533                                      progname, name);
1534                         return -EINVAL;
1535                 }
1536         }
1537
1538         /* don't allow to include and exclude the same flag */
1539         if (*inflags & *exflags) {
1540                 llapi_printf(LLAPI_MSG_ERROR,
1541                              "%s: include and exclude same flag '%s'\n",
1542                              progname, string);
1543                 return -EINVAL;
1544         }
1545
1546         return 0;
1547 }
1548
1549 static int mirror_str2state(char *string, __u16 *state, __u16 *neg_state)
1550 {
1551         if (!string)
1552                 return -EINVAL;
1553
1554         *state = 0;
1555         *neg_state = 0;
1556
1557         if (strncmp(string, "^", 1) == 0) {
1558                 *neg_state = llapi_layout_string_flags(string + 1);
1559                 if (*neg_state != 0)
1560                         return 0;
1561         } else {
1562                 *state = llapi_layout_string_flags(string);
1563                 if (*state != 0)
1564                         return 0;
1565         }
1566
1567         llapi_printf(LLAPI_MSG_ERROR,
1568                      "%s: mirrored file state '%s' not supported\n",
1569                      progname, string);
1570         return -EINVAL;
1571 }
1572
1573 /**
1574  * struct mirror_args - Command-line arguments for mirror(s).
1575  * @m_count:  Number of mirrors to be created with this layout.
1576  * @m_flags:  Mirror level flags, only 'prefer' is supported.
1577  * @m_layout: Mirror layout.
1578  * @m_file:   A victim file. Its layout will be split and used as a mirror.
1579  * @m_next:   Point to the next node of the list.
1580  *
1581  * Command-line arguments for mirror(s) will be parsed and stored in
1582  * a linked list that consists of this structure.
1583  */
1584 struct mirror_args {
1585         __u32                   m_count;
1586         __u32                   m_flags;
1587         struct llapi_layout     *m_layout;
1588         const char              *m_file;
1589         struct mirror_args      *m_next;
1590         bool                    m_inherit;
1591 };
1592
1593 /**
1594  * enum mirror_flags - Flags for extending a mirrored file.
1595  * @MF_NO_VERIFY: Indicates not to verify the mirror(s) from victim file(s)
1596  *             in case the victim file(s) contains the same data as the
1597  *             original mirrored file.
1598  * @MF_DESTROY: Indicates to delete the mirror from the mirrored file.
1599  * @MF_COMP_ID: specified component id instead of mirror id
1600  *
1601  * Flags for extending a mirrored file.
1602  */
1603 enum mirror_flags {
1604         MF_NO_VERIFY    = 0x1,
1605         MF_DESTROY      = 0x2,
1606         MF_COMP_ID      = 0x4,
1607         MF_COMP_POOL    = 0x8,
1608 };
1609
1610 /**
1611  * mirror_create_sanity_check() - Check mirror list.
1612  * @list:  A linked list that stores the mirror arguments.
1613  *
1614  * This function does a sanity check on @list for creating
1615  * a mirrored file.
1616  *
1617  * Return: 0 on success or a negative error code on failure.
1618  */
1619 static int mirror_create_sanity_check(const char *fname,
1620                                       struct mirror_args *list,
1621                                       bool check_fname)
1622 {
1623         int rc = 0;
1624         bool has_m_file = false;
1625         bool has_m_layout = false;
1626
1627         if (!list)
1628                 return -EINVAL;
1629
1630         if (fname && check_fname) {
1631                 struct llapi_layout *layout;
1632
1633                 layout = llapi_layout_get_by_path(fname, 0);
1634                 if (!layout) {
1635                         fprintf(stderr,
1636                                 "error: %s: file '%s' couldn't get layout\n",
1637                                 progname, fname);
1638                         return -ENODATA;
1639                 }
1640
1641                 rc = llapi_layout_sanity(layout, fname, false, true);
1642
1643                 llapi_layout_free(layout);
1644
1645                 if (rc) {
1646                         llapi_layout_sanity_perror(rc);
1647                         return rc;
1648                 }
1649         }
1650
1651         while (list) {
1652                 if (list->m_file) {
1653                         has_m_file = true;
1654                         llapi_layout_free(list->m_layout);
1655
1656                         list->m_layout =
1657                                 llapi_layout_get_by_path(list->m_file, 0);
1658                         if (!list->m_layout) {
1659                                 fprintf(stderr,
1660                                         "error: %s: file '%s' has no layout\n",
1661                                         progname, list->m_file);
1662                                 return -ENODATA;
1663                         }
1664                 } else {
1665                         has_m_layout = true;
1666                         if (!list->m_layout) {
1667                                 fprintf(stderr, "error: %s: no mirror layout\n",
1668                                         progname);
1669                                 return -EINVAL;
1670                         }
1671                 }
1672
1673                 rc = llapi_layout_sanity(list->m_layout, fname, false, true);
1674                 if (rc) {
1675                         llapi_layout_sanity_perror(rc);
1676                         return rc;
1677                 }
1678
1679                 list = list->m_next;
1680         }
1681
1682         if (has_m_file && has_m_layout) {
1683                 fprintf(stderr,
1684                         "error: %s: -f <victim_file> option should not be specified with setstripe options\n",
1685                         progname);
1686                 return -EINVAL;
1687         }
1688
1689         return 0;
1690 }
1691
1692 static int mirror_set_flags(struct llapi_layout *layout, void *cbdata)
1693 {
1694         __u32 mirror_flags = *(__u32 *)cbdata;
1695         uint32_t flags;
1696         int rc;
1697
1698         rc = llapi_layout_comp_flags_get(layout, &flags);
1699         if (rc < 0)
1700                 return rc;
1701
1702         if (!flags) {
1703                 rc = llapi_layout_comp_flags_set(layout, mirror_flags);
1704                 if (rc)
1705                         return rc;
1706         }
1707
1708         return LLAPI_LAYOUT_ITER_CONT;
1709 }
1710
1711 /**
1712  * mirror_create() - Create a mirrored file.
1713  * @fname:        The file to be created.
1714  * @mirror_list:  A linked list that stores the mirror arguments.
1715  *
1716  * This function creates a mirrored file @fname with the mirror(s)
1717  * from @mirror_list.
1718  *
1719  * Return: 0 on success or a negative error code on failure.
1720  */
1721 static int mirror_create(char *fname, struct mirror_args *mirror_list)
1722 {
1723         struct llapi_layout *layout = NULL;
1724         struct mirror_args *cur_mirror = NULL;
1725         uint16_t mirror_count = 0;
1726         int i = 0;
1727         int rc = 0;
1728
1729         rc = mirror_create_sanity_check(fname, mirror_list, false);
1730         if (rc)
1731                 return rc;
1732
1733         cur_mirror = mirror_list;
1734         while (cur_mirror) {
1735                 rc = llapi_layout_comp_iterate(cur_mirror->m_layout,
1736                                                mirror_set_flags,
1737                                                &cur_mirror->m_flags);
1738                 if (rc) {
1739                         rc = -errno;
1740                         fprintf(stderr, "%s: failed to set mirror flags\n",
1741                                 progname);
1742                         goto error;
1743                 }
1744
1745                 for (i = 0; i < cur_mirror->m_count; i++) {
1746                         rc = llapi_layout_merge(&layout, cur_mirror->m_layout);
1747                         if (rc) {
1748                                 rc = -errno;
1749                                 fprintf(stderr,
1750                                         "error: %s: merge layout failed: %s\n",
1751                                         progname, strerror(errno));
1752                                 goto error;
1753                         }
1754                 }
1755                 mirror_count += cur_mirror->m_count;
1756                 cur_mirror = cur_mirror->m_next;
1757         }
1758
1759         if (!layout) {
1760                 fprintf(stderr, "error: %s: layout is NULL\n", progname);
1761                 return -EINVAL;
1762         }
1763
1764         rc = llapi_layout_mirror_count_set(layout, mirror_count);
1765         if (rc) {
1766                 rc = -errno;
1767                 fprintf(stderr, "error: %s: set mirror count failed: %s\n",
1768                         progname, strerror(errno));
1769                 goto error;
1770         }
1771
1772         rc = lfs_component_create(fname, O_CREAT | O_WRONLY, 0666,
1773                                   layout);
1774         if (rc >= 0) {
1775                 close(rc);
1776                 rc = 0;
1777         }
1778
1779 error:
1780         llapi_layout_free(layout);
1781         return rc;
1782 }
1783
1784 /**
1785  * Compare files and check lease on @fd.
1786  *
1787  * \retval bytes number of bytes are the same
1788  */
1789 static ssize_t mirror_file_compare(int fd, int fdv)
1790 {
1791         const size_t buflen = 4 * 1024 * 1024; /* 4M */
1792         void *buf;
1793         ssize_t bytes_done = 0;
1794         ssize_t bytes_read = 0;
1795
1796         buf = malloc(buflen * 2);
1797         if (!buf)
1798                 return -ENOMEM;
1799
1800         while (1) {
1801                 if (!llapi_lease_check(fd)) {
1802                         bytes_done = -EBUSY;
1803                         break;
1804                 }
1805
1806                 bytes_read = read(fd, buf, buflen);
1807                 if (bytes_read <= 0)
1808                         break;
1809
1810                 if (bytes_read != read(fdv, buf + buflen, buflen))
1811                         break;
1812
1813                 /*
1814                  * XXX: should compute the checksum on each buffer and then
1815                  * compare checksum to avoid cache collision
1816                  */
1817                 if (memcmp(buf, buf + buflen, bytes_read))
1818                         break;
1819
1820                 bytes_done += bytes_read;
1821         }
1822
1823         free(buf);
1824
1825         return bytes_done;
1826 }
1827
1828 static int mirror_extend_file(const char *fname, const char *victim_file,
1829                               enum mirror_flags mirror_flags)
1830 {
1831         int fd = -1;
1832         int fdv = -1;
1833         struct stat stbuf;
1834         struct stat stbuf_v;
1835         struct ll_ioc_lease *data = NULL;
1836         int rc;
1837
1838         fd = open(fname, O_RDWR);
1839         if (fd < 0) {
1840                 error_loc = "open source file";
1841                 rc = -errno;
1842                 goto out;
1843         }
1844
1845         fdv = open(victim_file, O_RDWR);
1846         if (fdv < 0) {
1847                 error_loc = "open target file";
1848                 rc = -errno;
1849                 goto out;
1850         }
1851
1852         if (fstat(fd, &stbuf) || fstat(fdv, &stbuf_v)) {
1853                 error_loc = "stat source or target file";
1854                 rc = -errno;
1855                 goto out;
1856         }
1857
1858         if (stbuf.st_dev != stbuf_v.st_dev) {
1859                 error_loc = "stat source and target file";
1860                 rc = -EXDEV;
1861                 goto out;
1862         }
1863
1864         /* mirrors should be of the same size */
1865         if (stbuf.st_size != stbuf_v.st_size) {
1866                 error_loc = "file sizes don't match";
1867                 rc = -EINVAL;
1868                 goto out;
1869         }
1870
1871         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1872         if (rc < 0) {
1873                 error_loc = "cannot get lease";
1874                 goto out;
1875         }
1876
1877         if (!(mirror_flags & MF_NO_VERIFY)) {
1878                 ssize_t ret;
1879                 /* mirrors should have the same contents */
1880                 ret = mirror_file_compare(fd, fdv);
1881                 if (ret != stbuf.st_size) {
1882                         error_loc = "file busy or contents don't match";
1883                         rc = ret < 0 ? ret : -EINVAL;
1884                         goto out;
1885                 }
1886         }
1887
1888         /* Get rid of caching pages from clients */
1889         rc = llapi_file_flush(fd);
1890         if (rc < 0) {
1891                 error_loc = "cannot get data version";
1892                 goto out;
1893         }
1894
1895         rc = llapi_file_flush(fdv);
1896         if (rc < 0) {
1897                 error_loc = "cannot get data version";
1898                 goto out;
1899         }
1900
1901         rc = migrate_set_timestamps(fd, &stbuf);
1902         if (rc < 0) {
1903                 error_loc = "cannot set source file timestamp";
1904                 goto out;
1905         }
1906
1907         /* Atomically put lease, merge layouts and close. */
1908         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1909         if (!data) {
1910                 error_loc = "memory allocation";
1911                 goto out;
1912         }
1913         data->lil_mode = LL_LEASE_UNLCK;
1914         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1915         data->lil_count = 1;
1916         data->lil_ids[0] = fdv;
1917         rc = llapi_lease_set(fd, data);
1918         if (rc < 0) {
1919                 error_loc = "cannot merge layout";
1920                 goto out;
1921         } else if (rc == 0) {
1922                 rc = -EBUSY;
1923                 error_loc = "lost lease lock";
1924                 goto out;
1925         }
1926         rc = 0;
1927
1928 out:
1929         if (data)
1930                 free(data);
1931         if (fd >= 0)
1932                 close(fd);
1933         if (fdv >= 0)
1934                 close(fdv);
1935         if (!rc)
1936                 (void) unlink(victim_file);
1937         if (rc < 0)
1938                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1939                         progname, fname, error_loc, strerror(-rc));
1940         return rc;
1941 }
1942
1943 static int mirror_extend_layout(char *name, struct llapi_layout *m_layout,
1944                                 bool inherit, uint32_t flags)
1945 {
1946         struct llapi_layout *f_layout = NULL;
1947         struct ll_ioc_lease *data = NULL;
1948         struct stat st;
1949         int fd = -1;
1950         int fdv = -1;
1951         int rc = 0;
1952
1953         if (inherit) {
1954                 f_layout = llapi_layout_get_by_path(name, 0);
1955                 if (!f_layout) {
1956                         rc = -EINVAL;
1957                         fprintf(stderr, "%s: cannot get layout\n", progname);
1958                         goto out;
1959                 }
1960                 rc = llapi_layout_get_last_init_comp(f_layout);
1961                 if (rc) {
1962                         fprintf(stderr, "%s: cannot get the last init comp\n",
1963                                 progname);
1964                         goto out;
1965                 }
1966                 rc = llapi_layout_mirror_inherit(f_layout, m_layout);
1967                 if (rc) {
1968                         fprintf(stderr,
1969                                 "%s: cannot inherit from the last init comp\n",
1970                                 progname);
1971                         goto out;
1972                 }
1973         }
1974         llapi_layout_comp_flags_set(m_layout, flags);
1975         rc = migrate_open_files(name, MIGRATION_NONDIRECT, NULL, m_layout, &fd,
1976                                 &fdv);
1977         if (rc < 0)
1978                 goto out;
1979
1980         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1981         if (rc < 0) {
1982                 error_loc = "cannot get lease";
1983                 goto out;
1984         }
1985
1986         rc = fstat(fd, &st);
1987         if (rc < 0) {
1988                 error_loc = "cannot stat source file";
1989                 goto out;
1990         }
1991
1992         rc = migrate_nonblock(fd, fdv);
1993         if (rc < 0) {
1994                 llapi_lease_release(fd);
1995                 goto out;
1996         }
1997
1998         rc = migrate_set_timestamps(fd, &st);
1999         if (rc < 0) {
2000                 error_loc = "cannot set source file timestamp";
2001                 goto out;
2002         }
2003
2004         /* Atomically put lease, merge layouts and close. */
2005         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
2006         if (!data) {
2007                 error_loc = "memory allocation";
2008                 goto out;
2009         }
2010         data->lil_mode = LL_LEASE_UNLCK;
2011         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
2012         data->lil_count = 1;
2013         data->lil_ids[0] = fdv;
2014         rc = llapi_lease_set(fd, data);
2015         if (rc < 0) {
2016                 error_loc = "cannot merge layout";
2017                 goto out;
2018         } else if (rc == 0) {
2019                 rc = -EBUSY;
2020                 error_loc = "lost lease lock";
2021                 goto out;
2022         }
2023         rc = 0;
2024
2025 out:
2026         if (data)
2027                 free(data);
2028         if (fd >= 0)
2029                 close(fd);
2030         if (fdv >= 0)
2031                 close(fdv);
2032         if (rc < 0)
2033                 fprintf(stderr, "error: %s: %s: %s: %s\n",
2034                         progname, name, error_loc, strerror(-rc));
2035         return rc;
2036 }
2037
2038 static int mirror_extend(char *fname, struct mirror_args *mirror_list,
2039                          enum mirror_flags mirror_flags)
2040 {
2041         int rc = 0;
2042
2043         while (mirror_list) {
2044                 if (mirror_list->m_file) {
2045                         rc = mirror_extend_file(fname, mirror_list->m_file,
2046                                                 mirror_flags);
2047                 } else {
2048                         __u32 mirror_count = mirror_list->m_count;
2049
2050                         while (mirror_count > 0) {
2051                                 rc = mirror_extend_layout(fname,
2052                                                         mirror_list->m_layout,
2053                                                         mirror_list->m_inherit,
2054                                                         mirror_list->m_flags);
2055                                 if (rc)
2056                                         break;
2057
2058                                 --mirror_count;
2059                         }
2060                 }
2061                 if (rc)
2062                         break;
2063
2064                 mirror_list = mirror_list->m_next;
2065         }
2066
2067         return rc;
2068 }
2069
2070 static int find_mirror_id(struct llapi_layout *layout, void *cbdata)
2071 {
2072         uint32_t id;
2073         int rc;
2074
2075         rc = llapi_layout_mirror_id_get(layout, &id);
2076         if (rc < 0)
2077                 return rc;
2078
2079         if ((__u16)id == *(__u16 *)cbdata)
2080                 return LLAPI_LAYOUT_ITER_STOP;
2081
2082         return LLAPI_LAYOUT_ITER_CONT;
2083 }
2084
2085 static int find_comp_id(struct llapi_layout *layout, void *cbdata)
2086 {
2087         uint32_t id;
2088         int rc;
2089
2090         rc = llapi_layout_comp_id_get(layout, &id);
2091         if (rc < 0)
2092                 return rc;
2093
2094         if (id == *(__u32 *)cbdata)
2095                 return LLAPI_LAYOUT_ITER_STOP;
2096
2097         return LLAPI_LAYOUT_ITER_CONT;
2098 }
2099
2100 static int find_mirror_id_by_pool(struct llapi_layout *layout, void *cbdata)
2101 {
2102         char buf[LOV_MAXPOOLNAME + 1];
2103         struct pool_to_id_cbdata *d = (void *)cbdata;
2104         uint32_t id;
2105         int rc;
2106
2107         rc = llapi_layout_pool_name_get(layout, buf, sizeof(buf));
2108         if (rc < 0)
2109                 return rc;
2110         if (strcmp(d->pool, buf))
2111                 return LLAPI_LAYOUT_ITER_CONT;
2112
2113         rc = llapi_layout_mirror_id_get(layout, &id);
2114         if (rc < 0)
2115                 return rc;
2116         d->id = id;
2117
2118         return LLAPI_LAYOUT_ITER_STOP;
2119 }
2120
2121 static int find_comp_id_by_pool(struct llapi_layout *layout, void *cbdata)
2122 {
2123         char buf[LOV_MAXPOOLNAME + 1];
2124         struct pool_to_id_cbdata *d = (void *)cbdata;
2125         uint32_t id;
2126         int rc;
2127
2128         rc = llapi_layout_pool_name_get(layout, buf, sizeof(buf));
2129         if (rc < 0)
2130                 return rc;
2131         if (strcmp(d->pool, buf))
2132                 return LLAPI_LAYOUT_ITER_CONT;
2133
2134         rc = llapi_layout_comp_id_get(layout, &id);
2135         if (rc < 0)
2136                 return rc;
2137         d->id = id;
2138
2139         return LLAPI_LAYOUT_ITER_STOP;
2140 }
2141
2142 struct collect_ids_data {
2143         __u16   *cid_ids;
2144         int     cid_count;
2145         __u16   cid_exclude;
2146 };
2147
2148 static int collect_mirror_id(struct llapi_layout *layout, void *cbdata)
2149 {
2150         struct collect_ids_data *cid = cbdata;
2151         uint32_t id;
2152         int rc;
2153
2154         rc = llapi_layout_mirror_id_get(layout, &id);
2155         if (rc < 0)
2156                 return rc;
2157
2158         if ((__u16)id != cid->cid_exclude) {
2159                 int i;
2160
2161                 for (i = 0; i < cid->cid_count; i++) {
2162                         /* already collected the mirror id */
2163                         if (id == cid->cid_ids[i])
2164                                 return LLAPI_LAYOUT_ITER_CONT;
2165                 }
2166                 cid->cid_ids[cid->cid_count] = id;
2167                 cid->cid_count++;
2168         }
2169
2170         return LLAPI_LAYOUT_ITER_CONT;
2171 }
2172
2173 /**
2174  * last_non_stale_mirror() - Check if a mirror is the last non-stale mirror.
2175  * @mirror_id: Mirror id to be checked.
2176  * @layout:    Mirror component list.
2177  *
2178  * This function checks if a mirror with specified @mirror_id is the last
2179  * non-stale mirror of a layout @layout.
2180  *
2181  * Return: true or false.
2182  */
2183 static inline
2184 bool last_non_stale_mirror(__u16 mirror_id, struct llapi_layout *layout)
2185 {
2186         __u16 mirror_ids[128] = { 0 };
2187         struct collect_ids_data cid = { .cid_ids = mirror_ids,
2188                                         .cid_count = 0,
2189                                         .cid_exclude = mirror_id, };
2190         int i;
2191
2192         llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
2193
2194         for (i = 0; i < cid.cid_count; i++) {
2195                 struct llapi_resync_comp comp_array[1024] = { { 0 } };
2196                 int comp_size = 0;
2197
2198                 comp_size = llapi_mirror_find_stale(layout, comp_array,
2199                                                     ARRAY_SIZE(comp_array),
2200                                                     &mirror_ids[i], 1);
2201                 if (comp_size == 0)
2202                         return false;
2203         }
2204
2205         return true;
2206 }
2207
2208 static int mirror_split(const char *fname, __u32 id, const char *pool,
2209                         enum mirror_flags mflags, const char *victim_file)
2210 {
2211         struct llapi_layout *layout;
2212         char parent[PATH_MAX];
2213         char victim[PATH_MAX];
2214         int flags = O_CREAT | O_EXCL | O_LOV_DELAY_CREATE | O_NOFOLLOW;
2215         char *ptr;
2216         struct ll_ioc_lease *data;
2217         uint16_t mirror_count;
2218         __u32 mirror_id;
2219         int mdt_index;
2220         int fd, fdv;
2221         bool purge = true; /* delete mirror by setting fdv=fd */
2222         bool is_encrypted;
2223         int rc;
2224
2225         if (victim_file && (strcmp(fname, victim_file) == 0)) {
2226                 fprintf(stderr,
2227                         "error %s: the source file '%s' and -f file are the same\n",
2228                         progname, fname);
2229                 return -EINVAL;
2230         }
2231
2232         /* check fname contains mirror with mirror_id/comp_id */
2233         layout = llapi_layout_get_by_path(fname, 0);
2234         if (!layout) {
2235                 fprintf(stderr,
2236                         "error %s: file '%s' couldn't get layout\n",
2237                         progname, fname);
2238                 return -EINVAL;
2239         }
2240
2241         rc = llapi_layout_sanity(layout, fname, false, true);
2242         if (rc) {
2243                 llapi_layout_sanity_perror(rc);
2244                 goto free_layout;
2245         }
2246
2247         rc = llapi_layout_mirror_count_get(layout, &mirror_count);
2248         if (rc) {
2249                 fprintf(stderr,
2250                         "error %s: file '%s' couldn't get mirror count\n",
2251                         progname, fname);
2252                 goto free_layout;
2253         }
2254         if (mirror_count < 2) {
2255                 fprintf(stderr,
2256                         "error %s: file '%s' has %d component, cannot split\n",
2257                         progname, fname, mirror_count);
2258                 goto free_layout;
2259         }
2260
2261         if (mflags & MF_COMP_POOL) {
2262                 struct pool_to_id_cbdata data = { .pool = pool };
2263
2264                 rc = llapi_layout_comp_iterate(layout, find_mirror_id_by_pool,
2265                                                &data);
2266                 mirror_id = data.id;
2267         } else if (mflags & MF_COMP_ID) {
2268                 rc = llapi_layout_comp_iterate(layout, find_comp_id, &id);
2269                 mirror_id = mirror_id_of(id);
2270         } else {
2271                 rc = llapi_layout_comp_iterate(layout, find_mirror_id, &id);
2272                 mirror_id = id;
2273         }
2274         if (rc < 0) {
2275                 fprintf(stderr, "error %s: failed to iterate layout of '%s'\n",
2276                         progname, fname);
2277                 goto free_layout;
2278         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
2279                 if (mflags & MF_COMP_POOL) {
2280                         fprintf(stderr,
2281                                 "error %s: file '%s' does not contain mirror with pool '%s'\n",
2282                                 progname, fname, pool);
2283                         goto free_layout;
2284                 } else if (mflags & MF_COMP_ID) {
2285                         fprintf(stderr,
2286                                 "error %s: file '%s' does not contain mirror with comp-id %u\n",
2287                                 progname, fname, id);
2288                         goto free_layout;
2289                 } else {
2290                         fprintf(stderr,
2291                                 "error %s: file '%s' does not contain mirror with id %u\n",
2292                                 progname, fname, id);
2293                         goto free_layout;
2294                 }
2295         }
2296
2297         fd = open(fname, O_RDWR);
2298         if (fd < 0) {
2299                 fprintf(stderr,
2300                         "error %s: open file '%s' failed: %s\n",
2301                         progname, fname, strerror(errno));
2302                 goto free_layout;
2303         }
2304
2305         /* get victim file directory pathname */
2306         if (strlen(fname) > sizeof(parent) - 1) {
2307                 fprintf(stderr, "error %s: file name of '%s' too long\n",
2308                         progname, fname);
2309                 rc = -ERANGE;
2310                 goto close_fd;
2311         }
2312         strncpy(parent, fname, sizeof(parent));
2313         ptr = strrchr(parent, '/');
2314         if (!ptr) {
2315                 if (!getcwd(parent, sizeof(parent))) {
2316                         fprintf(stderr, "error %s: getcwd failed: %s\n",
2317                                 progname, strerror(errno));
2318                         rc = -errno;
2319                         goto close_fd;
2320                 }
2321         } else {
2322                 if (ptr == parent)
2323                         ptr = parent + 1;
2324                 *ptr = '\0';
2325         }
2326
2327         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
2328         if (rc < 0) {
2329                 fprintf(stderr, "%s: cannot get MDT index of '%s'\n",
2330                         progname, fname);
2331                 goto close_fd;
2332         }
2333
2334         rc = llapi_file_is_encrypted(fd);
2335         if (rc < 0) {
2336                 fprintf(stderr, "%s: cannot get flags of '%s': %d\n",
2337                         progname, fname, rc);
2338                 goto close_fd;
2339         }
2340         is_encrypted = rc;
2341
2342 again:
2343         if (!victim_file) {
2344                 /* use a temp file to store the splitted layout */
2345                 if (mflags & MF_DESTROY) {
2346                         char file_path[PATH_MAX];
2347                         unsigned int rnumber;
2348                         int open_flags;
2349
2350                         if (last_non_stale_mirror(mirror_id, layout)) {
2351                                 rc = -EUCLEAN;
2352                                 fprintf(stderr,
2353                                         "%s: cannot destroy the last non-stale mirror of file '%s'\n",
2354                                         progname, fname);
2355                                 goto close_fd;
2356                         }
2357
2358                         if (purge) {
2359                                 /* don't use volatile file for mirror destroy */
2360                                 fdv = fd;
2361                         } else {
2362                                 /**
2363                                  * try the old way to delete mirror using
2364                                  * volatile file.
2365                                  */
2366                                 do {
2367                                         rnumber = random();
2368                                         rc = snprintf(file_path,
2369                                                       sizeof(file_path),
2370                                                       "%s/" LUSTRE_VOLATILE_HDR ":%.4X:%.4X:fd=%.2d",
2371                                                       parent, mdt_index,
2372                                                       rnumber, fd);
2373                                         if (rc < 0 ||
2374                                             rc >= sizeof(file_path)) {
2375                                                 fdv = -ENAMETOOLONG;
2376                                                 break;
2377                                         }
2378
2379                                         open_flags = O_RDWR |
2380                                              (O_LOV_DELAY_CREATE & ~O_ACCMODE) |
2381                                              O_CREAT | O_EXCL | O_NOFOLLOW;
2382                                         fdv = open(file_path, open_flags,
2383                                                    S_IRUSR | S_IWUSR);
2384                                         if (fdv < 0)
2385                                                 rc = -errno;
2386                                 } while (fdv < 0 && rc == -EEXIST);
2387                         }
2388                 } else {
2389                         if (is_encrypted) {
2390                                 rc = -1;
2391                                 fprintf(stderr,
2392                                         "error %s: not permitted on encrypted file '%s': %d\n",
2393                                         progname, fname, rc);
2394                                 goto close_fd;
2395                         }
2396
2397                         snprintf(victim, sizeof(victim), "%s.mirror~%u",
2398                                  fname, mirror_id);
2399                         fdv = open(victim, flags, S_IRUSR | S_IWUSR);
2400                 }
2401         } else {
2402                 /* user specified victim file */
2403                 if (is_encrypted) {
2404                         rc = -1;
2405                         fprintf(stderr,
2406                                 "error %s: not permitted on encrypted file '%s': %d\n",
2407                                 progname, fname, rc);
2408                         goto close_fd;
2409                 }
2410                 fdv = open(victim_file, flags, S_IRUSR | S_IWUSR);
2411         }
2412
2413         if (fdv < 0) {
2414                 fprintf(stderr,
2415                         "error %s: create victim file failed: %s\n",
2416                         progname, strerror(errno));
2417                 goto close_fd;
2418         }
2419
2420         /* get lease lock of fname */
2421         rc = llapi_lease_acquire(fd, LL_LEASE_WRLCK);
2422         if (rc < 0) {
2423                 fprintf(stderr,
2424                         "error %s: cannot get lease of file '%s': %d\n",
2425                         progname, fname, rc);
2426                 goto close_victim;
2427         }
2428
2429         /* Atomatically put lease, split layouts and close. */
2430         data = malloc(offsetof(typeof(*data), lil_ids[2]));
2431         if (!data) {
2432                 rc = -ENOMEM;
2433                 goto close_victim;
2434         }
2435
2436         data->lil_mode = LL_LEASE_UNLCK;
2437         data->lil_flags = LL_LEASE_LAYOUT_SPLIT;
2438         data->lil_count = 2;
2439         data->lil_ids[0] = fdv;
2440         data->lil_ids[1] = mirror_id;
2441         rc = llapi_lease_set(fd, data);
2442         if (rc <= 0) {
2443                 if (rc == -EINVAL && purge) {
2444                         /* could be old MDS which prohibit fd==fdv */
2445                         purge = false;
2446                         goto again;
2447
2448                 }
2449                 if (rc == 0) /* lost lease lock */
2450                         rc = -EBUSY;
2451                 fprintf(stderr,
2452                         "error %s: cannot split '%s': %s\n",
2453                         progname, fname, strerror(-rc));
2454         } else {
2455                 rc = 0;
2456         }
2457         free(data);
2458
2459 close_victim:
2460         if (!purge)
2461                 close(fdv);
2462 close_fd:
2463         close(fd);
2464 free_layout:
2465         llapi_layout_free(layout);
2466         return rc;
2467 }
2468
2469 static inline
2470 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
2471                            __u16 *mirror_ids, int ids_nr);
2472
2473 static int lfs_migrate_to_dom(int fd, int fdv, char *name,
2474                               __u64 migration_flags,
2475                               struct llapi_stripe_param *param,
2476                               struct llapi_layout *layout)
2477 {
2478         struct ll_ioc_lease *data = NULL;
2479         int rc;
2480
2481         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
2482         if (rc < 0) {
2483                 error_loc = "cannot get lease";
2484                 goto out_close;
2485         }
2486
2487         /* Atomically put lease, merge layouts, resync and close. */
2488         data = calloc(1, offsetof(typeof(*data), lil_ids[1024]));
2489         if (!data) {
2490                 error_loc = "memory allocation";
2491                 goto out_close;
2492         }
2493         data->lil_mode = LL_LEASE_UNLCK;
2494         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
2495         data->lil_count = 1;
2496         data->lil_ids[0] = fdv;
2497         rc = llapi_lease_set(fd, data);
2498         if (rc < 0) {
2499                 error_loc = "cannot merge layout";
2500                 goto out_close;
2501         } else if (rc == 0) {
2502                 rc = -EBUSY;
2503                 error_loc = "lost lease lock";
2504                 goto out_close;
2505         }
2506         close(fd);
2507         close(fdv);
2508
2509         rc = lfs_mirror_resync_file(name, data, NULL, 0);
2510         if (rc) {
2511                 error_loc = "cannot resync file";
2512                 goto out;
2513         }
2514
2515         /* delete first mirror now */
2516         rc = mirror_split(name, 1, NULL, MF_DESTROY, NULL);
2517         if (rc < 0)
2518                 error_loc = "cannot delete old layout";
2519         goto out;
2520
2521 out_close:
2522         close(fd);
2523         close(fdv);
2524 out:
2525         if (rc < 0)
2526                 fprintf(stderr, "error: %s: %s: %s: %s\n",
2527                         progname, name, error_loc, strerror(-rc));
2528         else if (migration_flags & MIGRATION_VERBOSE)
2529                 printf("%s\n", name);
2530         if (data)
2531                 free(data);
2532         return rc;
2533 }
2534
2535 /**
2536  * Parse a string containing an target index list into an array of integers.
2537  *
2538  * The input string contains a comma delimited list of individual
2539  * indices and ranges, for example "1,2-4,7". Add the indices into the
2540  * \a tgts array and remove duplicates.
2541  *
2542  * \param[out] tgts             array to store indices in
2543  * \param[in] size              size of \a tgts array
2544  * \param[in] offset            starting index in \a tgts
2545  * \param[in] arg               string containing OST index list
2546  * \param[in/out] overstriping  index list may contain duplicates
2547  *
2548  * \retval positive    number of indices in \a tgts
2549  * \retval -EINVAL     unable to parse \a arg
2550  */
2551 static int parse_targets(__u32 *tgts, int size, int offset, char *arg,
2552                          unsigned long long *pattern)
2553 {
2554         int rc;
2555         int nr = offset;
2556         int slots = size - offset;
2557         char *ptr = NULL;
2558         bool overstriped = false;
2559         bool end_of_loop;
2560
2561         if (!arg)
2562                 return -EINVAL;
2563
2564         end_of_loop = false;
2565         while (!end_of_loop) {
2566                 int start_index = 0;
2567                 int end_index = 0;
2568                 int i;
2569                 char *endptr = NULL;
2570
2571                 rc = -EINVAL;
2572
2573                 ptr = strchrnul(arg, ',');
2574
2575                 end_of_loop = *ptr == '\0';
2576                 *ptr = '\0';
2577
2578                 errno = 0;
2579                 start_index = strtol(arg, &endptr, 0);
2580                 if (endptr == arg) /* no data at all */
2581                         break;
2582                 if (errno != 0 || start_index < -1 ||
2583                     (*endptr != '-' && *endptr != '\0'))
2584                         break;
2585
2586                 end_index = start_index;
2587                 if (*endptr == '-') {
2588                         errno = 0;
2589                         end_index = strtol(endptr + 1, &endptr, 0);
2590                         if (errno != 0 || *endptr != '\0' || end_index < -1)
2591                                 break;
2592                         if (end_index < start_index)
2593                                 break;
2594                 }
2595
2596                 for (i = start_index; i <= end_index && slots > 0; i++) {
2597                         int j;
2598
2599                         /* remove duplicate */
2600                         for (j = 0; j < offset; j++) {
2601                                 if (tgts[j] == i && pattern &&
2602                                     *pattern == LLAPI_LAYOUT_OVERSTRIPING)
2603                                         overstriped = true;
2604                                 else if (tgts[j] == i)
2605                                         return -EINVAL;
2606                         }
2607
2608                         j = offset;
2609
2610                         if (j == offset) { /* check complete */
2611                                 tgts[nr++] = i;
2612                                 --slots;
2613                         }
2614                 }
2615
2616                 if (slots == 0 && i < end_index)
2617                         break;
2618
2619                 *ptr = ',';
2620                 arg = ++ptr;
2621                 offset = nr;
2622                 rc = 0;
2623         }
2624         if (!end_of_loop && ptr)
2625                 *ptr = ',';
2626
2627         if (!overstriped && pattern)
2628                 *pattern = LLAPI_LAYOUT_DEFAULT;
2629
2630         return rc < 0 ? rc : nr;
2631 }
2632
2633 struct lfs_setstripe_args {
2634         unsigned long long       lsa_comp_end;
2635         unsigned long long       lsa_stripe_size;
2636         unsigned long long       lsa_extension_size;
2637         long long                lsa_stripe_count;
2638         long long                lsa_stripe_off;
2639         __u32                    lsa_comp_flags;
2640         __u32                    lsa_comp_neg_flags;
2641         unsigned long long       lsa_pattern;
2642         unsigned int             lsa_mirror_count;
2643         int                      lsa_nr_tgts;
2644         bool                     lsa_first_comp;
2645         bool                     lsa_extension_comp;
2646         __u32                   *lsa_tgts;
2647         char                    *lsa_pool_name;
2648 };
2649
2650 static inline void setstripe_args_init(struct lfs_setstripe_args *lsa)
2651 {
2652         unsigned int mirror_count = lsa->lsa_mirror_count;
2653         bool first_comp = lsa->lsa_first_comp;
2654
2655         memset(lsa, 0, sizeof(*lsa));
2656
2657         lsa->lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
2658         lsa->lsa_stripe_count = LLAPI_LAYOUT_DEFAULT;
2659         lsa->lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2660         lsa->lsa_pattern = LLAPI_LAYOUT_RAID0;
2661         lsa->lsa_pool_name = NULL;
2662
2663         lsa->lsa_mirror_count = mirror_count;
2664         lsa->lsa_first_comp = first_comp;
2665 }
2666
2667 /**
2668  * setstripe_args_init_inherit() - Initialize and inherit stripe options.
2669  * @lsa: Stripe options to be initialized and inherited.
2670  *
2671  * This function initializes stripe options in @lsa and inherit
2672  * stripe_size, stripe_count and OST pool_name options.
2673  *
2674  * Return: void.
2675  */
2676 static inline void setstripe_args_init_inherit(struct lfs_setstripe_args *lsa)
2677 {
2678         unsigned long long stripe_size;
2679         long long stripe_count;
2680         char *pool_name = NULL;
2681
2682         stripe_size = lsa->lsa_stripe_size;
2683         stripe_count = lsa->lsa_stripe_count;
2684         pool_name = lsa->lsa_pool_name;
2685
2686         setstripe_args_init(lsa);
2687
2688         lsa->lsa_stripe_size = stripe_size;
2689         lsa->lsa_stripe_count = stripe_count;
2690         lsa->lsa_pool_name = pool_name;
2691 }
2692
2693 static inline bool setstripe_args_specified(struct lfs_setstripe_args *lsa)
2694 {
2695         return (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT ||
2696                 lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ||
2697                 lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
2698                 lsa->lsa_pattern != LLAPI_LAYOUT_RAID0 ||
2699                 lsa->lsa_comp_end != 0);
2700 }
2701
2702 static int lsa_args_stripe_count_check(struct lfs_setstripe_args *lsa)
2703 {
2704         if (lsa->lsa_nr_tgts) {
2705                 if (lsa->lsa_nr_tgts < 0 ||
2706                     lsa->lsa_nr_tgts >= LOV_MAX_STRIPE_COUNT) {
2707                         fprintf(stderr, "Invalid nr_tgts(%d)\n",
2708                                 lsa->lsa_nr_tgts);
2709                         errno = EINVAL;
2710                         return -1;
2711                 }
2712
2713                 if (lsa->lsa_stripe_count > 0 &&
2714                     lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
2715                     lsa->lsa_stripe_count != LLAPI_LAYOUT_WIDE &&
2716                     lsa->lsa_nr_tgts != lsa->lsa_stripe_count) {
2717                         fprintf(stderr, "stripe_count(%lld) != nr_tgts(%d)\n",
2718                                 lsa->lsa_stripe_count,
2719                                 lsa->lsa_nr_tgts);
2720                         errno = EINVAL;
2721                         return -1;
2722                 }
2723         }
2724
2725         return 0;
2726
2727 }
2728
2729 /**
2730  * comp_args_to_layout() - Create or extend a composite layout.
2731  * @composite:       Pointer to the composite layout.
2732  * @lsa:             Stripe options for the new component.
2733  *
2734  * This function creates or extends a composite layout by adding a new
2735  * component with stripe options from @lsa.
2736  *
2737  * When modified, adjust llapi_stripe_param_verify() if needed as well.
2738  *
2739  * Return: 0 on success or an error code on failure.
2740  */
2741 static int comp_args_to_layout(struct llapi_layout **composite,
2742                                struct lfs_setstripe_args *lsa,
2743                                bool set_extent)
2744 {
2745         struct llapi_layout *layout = *composite;
2746         uint64_t prev_end = 0;
2747         uint64_t size;
2748         int i = 0, rc;
2749
2750 new_comp:
2751         if (!layout) {
2752                 layout = llapi_layout_alloc();
2753                 if (!layout) {
2754                         fprintf(stderr, "Alloc llapi_layout failed. %s\n",
2755                                 strerror(errno));
2756                         errno = ENOMEM;
2757                         return -1;
2758                 }
2759                 *composite = layout;
2760                 lsa->lsa_first_comp = true;
2761         } else {
2762                 uint64_t start;
2763
2764                 /*
2765                  * Get current component extent, current component
2766                  * must be the tail component.
2767                  */
2768                 rc = llapi_layout_comp_extent_get(layout, &start, &prev_end);
2769                 if (rc) {
2770                         fprintf(stderr, "Get comp extent failed. %s\n",
2771                                 strerror(errno));
2772                         return rc;
2773                 }
2774
2775                 if (lsa->lsa_first_comp) {
2776                         prev_end = 0;
2777                         rc = llapi_layout_add_first_comp(layout);
2778                 } else {
2779                         rc = llapi_layout_comp_add(layout);
2780                 }
2781                 if (rc) {
2782                         fprintf(stderr, "Add component failed. %s\n",
2783                                 strerror(errno));
2784                         return rc;
2785                 }
2786         }
2787
2788         rc = llapi_layout_comp_flags_set(layout, lsa->lsa_comp_flags);
2789         if (rc) {
2790                 fprintf(stderr, "Set flags 0x%x failed: %s\n",
2791                         lsa->lsa_comp_flags, strerror(errno));
2792                 return rc;
2793         }
2794
2795         if (set_extent) {
2796                 uint64_t comp_end = lsa->lsa_comp_end;
2797
2798                 /*
2799                  * The extendable component is 0-length, so it can be removed
2800                  * if there is insufficient space to extend it.
2801                  */
2802                 if (lsa->lsa_extension_comp)
2803                         comp_end = prev_end;
2804
2805                 rc = llapi_layout_comp_extent_set(layout, prev_end,
2806                                                   comp_end);
2807                 if (rc) {
2808                         fprintf(stderr, "Set extent [%lu, %lu) failed. %s\n",
2809                                 prev_end, comp_end, strerror(errno));
2810                         return rc;
2811                 }
2812         }
2813         /* reset lsa_first_comp */
2814         lsa->lsa_first_comp = false;
2815
2816         /* Data-on-MDT component setting */
2817         if (lsa->lsa_pattern == LLAPI_LAYOUT_MDT) {
2818                 /* Yaml support */
2819                 if (lsa->lsa_stripe_count == 0)
2820                         lsa->lsa_stripe_count = LLAPI_LAYOUT_DEFAULT;
2821                 if (lsa->lsa_stripe_size == lsa->lsa_comp_end)
2822                         lsa->lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
2823                 if (lsa->lsa_stripe_off == -1 ||
2824                     lsa->lsa_stripe_off == 0)
2825                         lsa->lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2826                 /*
2827                  * In case of Data-on-MDT patterns the only extra option
2828                  * applicable is stripe size option.
2829                  */
2830                 if (lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
2831                         fprintf(stderr,
2832                                 "Option 'stripe-count' can't be specified with Data-on-MDT component: %lld\n",
2833                                 lsa->lsa_stripe_count);
2834                         errno = EINVAL;
2835                         return -1;
2836                 }
2837                 if (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT &&
2838                     lsa->lsa_stripe_size != lsa->lsa_comp_end - prev_end) {
2839                         fprintf(stderr,
2840                                 "Option 'stripe-size' can't be specified with Data-on-MDT component: %llu\n",
2841                                 lsa->lsa_stripe_size);
2842                         errno = EINVAL;
2843                         return -1;
2844                 }
2845                 if (lsa->lsa_nr_tgts != 0) {
2846                         fprintf(stderr,
2847                                 "Option 'ost-list' can't be specified with Data-on-MDT component: '%i'\n",
2848                                 lsa->lsa_nr_tgts);
2849                         errno = EINVAL;
2850                         return -1;
2851                 }
2852                 if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT) {
2853                         fprintf(stderr,
2854                                 "Option 'stripe-offset' can't be specified with Data-on-MDT component: %lld\n",
2855                                 lsa->lsa_stripe_off);
2856                         errno = EINVAL;
2857                         return -1;
2858                 }
2859                 if (lsa->lsa_pool_name != 0) {
2860                         fprintf(stderr,
2861                                 "Option 'pool' can't be specified with Data-on-MDT component: '%s'\n",
2862                                 lsa->lsa_pool_name);
2863                         errno = EINVAL;
2864                         return -1;
2865                 }
2866
2867                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2868                 if (rc) {
2869                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2870                                 lsa->lsa_pattern,
2871                                 strerror(errno));
2872                         return rc;
2873                 }
2874                 /* Data-on-MDT component has always single stripe up to end */
2875                 lsa->lsa_stripe_size = lsa->lsa_comp_end;
2876         } else if (lsa->lsa_pattern == LLAPI_LAYOUT_OVERSTRIPING) {
2877                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2878                 if (rc) {
2879                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2880                                 lsa->lsa_pattern,
2881                                 strerror(errno));
2882                         return rc;
2883                 }
2884         }
2885
2886         size = lsa->lsa_comp_flags & LCME_FL_EXTENSION ?
2887                 lsa->lsa_extension_size : lsa->lsa_stripe_size;
2888
2889         if (lsa->lsa_comp_flags & LCME_FL_EXTENSION)
2890                 rc = llapi_layout_extension_size_set(layout, size);
2891         else
2892                 rc = llapi_layout_stripe_size_set(layout, size);
2893
2894         if (rc) {
2895                 fprintf(stderr, "Set stripe size %lu failed: %s\n",
2896                         size, strerror(errno));
2897                 return rc;
2898         }
2899
2900         rc = llapi_layout_stripe_count_set(layout, lsa->lsa_stripe_count);
2901         if (rc) {
2902                 fprintf(stderr, "Set stripe count %lld failed: %s\n",
2903                         lsa->lsa_stripe_count, strerror(errno));
2904                 return rc;
2905         }
2906
2907         if (lsa->lsa_pool_name) {
2908                 rc = llapi_layout_pool_name_set(layout, lsa->lsa_pool_name);
2909                 if (rc) {
2910                         fprintf(stderr, "Set pool name: %s failed. %s\n",
2911                                 lsa->lsa_pool_name, strerror(errno));
2912                         return rc;
2913                 }
2914         } else {
2915                 rc = llapi_layout_pool_name_set(layout, "");
2916                 if (rc) {
2917                         fprintf(stderr, "Clear pool name failed: %s\n",
2918                                 strerror(errno));
2919                         return rc;
2920                 }
2921         }
2922
2923         rc = lsa_args_stripe_count_check(lsa);
2924         if (rc)
2925                 return rc;
2926
2927         if (lsa->lsa_nr_tgts > 0) {
2928                 bool found = false;
2929
2930                 for (i = 0; i < lsa->lsa_nr_tgts; i++) {
2931                         rc = llapi_layout_ost_index_set(layout, i,
2932                                                         lsa->lsa_tgts[i]);
2933                         if (rc)
2934                                 break;
2935
2936                         /* Make sure stripe offset is in OST list. */
2937                         if (lsa->lsa_tgts[i] == lsa->lsa_stripe_off)
2938                                 found = true;
2939                 }
2940                 if (!found) {
2941                         fprintf(stderr, "Invalid stripe offset '%lld', not in the target list",
2942                                 lsa->lsa_stripe_off);
2943                         errno = EINVAL;
2944                         return -1;
2945                 }
2946         } else if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT &&
2947                    lsa->lsa_stripe_off != -1) {
2948                 rc = llapi_layout_ost_index_set(layout, 0, lsa->lsa_stripe_off);
2949         }
2950         if (rc) {
2951                 fprintf(stderr, "Set ost index %d failed. %s\n",
2952                         i, strerror(errno));
2953                 return rc;
2954         }
2955
2956         /* Create the second, virtual component of extension space */
2957         if (lsa->lsa_extension_comp) {
2958                 lsa->lsa_comp_flags |= LCME_FL_EXTENSION;
2959                 lsa->lsa_extension_comp = false;
2960                 goto new_comp;
2961         }
2962
2963         return rc;
2964 }
2965
2966 static int build_component(struct llapi_layout **layout,
2967                            struct lfs_setstripe_args *lsa, bool set_extent)
2968 {
2969         int rc;
2970
2971         rc = comp_args_to_layout(layout, lsa, set_extent);
2972         if (rc)
2973                 return rc;
2974
2975         if (lsa->lsa_mirror_count > 0) {
2976                 rc = llapi_layout_mirror_count_set(*layout,
2977                                                    lsa->lsa_mirror_count);
2978                 if (rc)
2979                         return rc;
2980
2981                 rc = llapi_layout_flags_set(*layout, LCM_FL_RDONLY);
2982                 if (rc)
2983                         return rc;
2984                 lsa->lsa_mirror_count = 0;
2985         }
2986
2987         return rc;
2988 }
2989
2990 static int build_prev_component(struct llapi_layout **layout,
2991                                 struct lfs_setstripe_args *prev,
2992                                 struct lfs_setstripe_args *lsa,
2993                                 bool set_extent)
2994 {
2995         int extension = lsa->lsa_comp_flags & LCME_FL_EXTENSION;
2996         int rc;
2997
2998         if (prev->lsa_stripe_size) {
2999                 if (extension) {
3000                         prev->lsa_comp_end = lsa->lsa_comp_end;
3001                         prev->lsa_extension_size = lsa->lsa_extension_size;
3002                         prev->lsa_extension_comp = true;
3003                 }
3004
3005                 rc = build_component(layout, prev, true);
3006                 if (rc)
3007                         return rc;
3008         }
3009
3010         /*
3011          * Copy lsa to previous lsa;
3012          * if this is an extension component, make the previous invalid;
3013          */
3014         if (extension)
3015                 prev->lsa_stripe_size = 0;
3016         else
3017                 *prev = *lsa;
3018
3019         return 0;
3020 }
3021
3022 #ifndef LCME_TEMPLATE_FLAGS
3023 #define LCME_TEMPLATE_FLAGS     (LCME_FL_PREF_RW | LCME_FL_NOSYNC | \
3024                                  LCME_FL_EXTENSION)
3025 #endif
3026
3027 static int build_layout_from_yaml_node(struct cYAML *node,
3028                                        struct llapi_layout **layout,
3029                                        struct lfs_setstripe_args *lsa,
3030                                        struct lfs_setstripe_args *prevp)
3031 {
3032         struct lfs_setstripe_args prev = { 0 };
3033         __u32 *osts = lsa->lsa_tgts;
3034         char *string;
3035         int rc = 0;
3036
3037         if (!prevp)
3038                 prevp = &prev;
3039
3040         while (node) {
3041                 string = node->cy_string;
3042
3043                 if (node->cy_type == CYAML_TYPE_OBJECT) {
3044                         /* go deep to sub blocks */
3045                         if (string && !strncmp(string, "component", 9) &&
3046                             strncmp(string, "component0", 10) &&
3047                             strncmp(string, "components", 10)) {
3048                                 rc = build_prev_component(layout, prevp, lsa,
3049                                                           true);
3050                                 if (rc)
3051                                         return rc;
3052
3053                                 /* initialize lsa. */
3054                                 setstripe_args_init(lsa);
3055                                 lsa->lsa_first_comp = false;
3056                                 lsa->lsa_tgts = osts;
3057                         }
3058
3059                         rc = build_layout_from_yaml_node(node->cy_child, layout,
3060                                                          lsa, prevp);
3061                         if (rc)
3062                                 return rc;
3063                 } else {
3064                         if (!node->cy_string)
3065                                 return -EINVAL;
3066
3067                         /* skip leading lmm_ if present, to simplify parsing */
3068                         if (strncmp(string, "lmm_", 4) == 0)
3069                                 string += 4;
3070
3071                         if (node->cy_type == CYAML_TYPE_STRING) {
3072                                 if (!strcmp(string, "lcme_extent.e_end")) {
3073                                         if (!strcmp(node->cy_valuestring, "EOF") ||
3074                                             !strcmp(node->cy_valuestring, "eof"))
3075                                                 lsa->lsa_comp_end = LUSTRE_EOF;
3076                                 } else if (!strcmp(string, "pool")) {
3077                                         lsa->lsa_pool_name = node->cy_valuestring;
3078                                 } else if (!strcmp(string, "pattern")) {
3079                                         if (!strcmp(node->cy_valuestring, "mdt"))
3080                                                 lsa->lsa_pattern = LLAPI_LAYOUT_MDT;
3081                                         if (!strcmp(node->cy_valuestring,
3082                                                     "raid0,overstriped"))
3083                                                 lsa->lsa_pattern =
3084                                                         LLAPI_LAYOUT_OVERSTRIPING;
3085                                 } else if (!strcmp(string, "lcme_flags")) {
3086                                         rc = comp_str2flags(node->cy_valuestring,
3087                                                             &lsa->lsa_comp_flags,
3088                                                             &lsa->lsa_comp_neg_flags);
3089                                         if (rc)
3090                                                 return rc;
3091                                         /*
3092                                          * Only template flags have meaning in
3093                                          * the layout for a new file
3094                                          */
3095                                         lsa->lsa_comp_flags &= LCME_TEMPLATE_FLAGS;
3096                                 }
3097                         } else if (node->cy_type == CYAML_TYPE_NUMBER) {
3098                                 if (!strcmp(string, "lcm_mirror_count")) {
3099                                         lsa->lsa_mirror_count = node->cy_valueint;
3100                                 } else if (!strcmp(string, "lcme_extent.e_start")) {
3101                                         if (node->cy_valueint == 0)
3102                                                 lsa->lsa_first_comp = true;
3103                                 } else if (!strcmp(string, "lcme_extent.e_end")) {
3104                                         if (node->cy_valueint == -1)
3105                                                 lsa->lsa_comp_end = LUSTRE_EOF;
3106                                         else
3107                                                 lsa->lsa_comp_end = node->cy_valueint;
3108                                 } else if (!strcmp(string, "stripe_count")) {
3109                                         lsa->lsa_stripe_count = node->cy_valueint;
3110                                 } else if (!strcmp(string, "stripe_size")) {
3111                                         lsa->lsa_stripe_size = node->cy_valueint;
3112                                 } else if (!strcmp(string, "extension_size")) {
3113                                         lsa->lsa_extension_size = node->cy_valueint;
3114                                         lsa->lsa_extension_comp = true;
3115                                 } else if (!strcmp(string, "stripe_offset")) {
3116                                         lsa->lsa_stripe_off = node->cy_valueint;
3117                                 } else if (!strcmp(string, "l_ost_idx")) {
3118                                         osts[lsa->lsa_nr_tgts] = node->cy_valueint;
3119                                         lsa->lsa_nr_tgts++;
3120                                 }
3121                         }
3122                 }
3123                 node = node->cy_next;
3124         }
3125
3126         if (prevp == &prev) {
3127                 rc = build_prev_component(layout, prevp, lsa, true);
3128                 if (rc)
3129                         return rc;
3130
3131                 if (!(lsa->lsa_comp_flags & LCME_FL_EXTENSION))
3132                         rc = build_component(layout, lsa, *layout != NULL);
3133         }
3134
3135         return rc;
3136 }
3137
3138 static int lfs_comp_create_from_yaml(char *template,
3139                                      struct llapi_layout **layout,
3140                                      struct lfs_setstripe_args *lsa,
3141                                      __u32 *osts)
3142 {
3143         struct cYAML *tree = NULL, *err_rc = NULL;
3144         int rc = 0;
3145
3146         tree = cYAML_build_tree(template, NULL, 0, &err_rc, false);
3147         if (!tree) {
3148                 fprintf(stderr, "%s: cannot parse YAML file %s\n",
3149                         progname, template);
3150                 cYAML_build_error(-EINVAL, -1, "yaml", "from comp yaml",
3151                                   "can't parse", &err_rc);
3152                 cYAML_print_tree2file(stderr, err_rc);
3153                 cYAML_free_tree(err_rc);
3154                 rc = -EINVAL;
3155                 goto err;
3156         }
3157
3158         /* initialize lsa for plain file */
3159         setstripe_args_init(lsa);
3160         lsa->lsa_tgts = osts;
3161
3162         rc = build_layout_from_yaml_node(tree, layout, lsa, NULL);
3163         if (rc) {
3164                 fprintf(stderr, "%s: cannot build layout from YAML file %s.\n",
3165                         progname, template);
3166                 goto err;
3167         }
3168         /* clean clean lsa */
3169         setstripe_args_init(lsa);
3170
3171 err:
3172         if (tree)
3173                 cYAML_free_tree(tree);
3174         return rc;
3175 }
3176
3177 /**
3178  * Get the extension size from the next (SEL) component and extend the
3179  * current component on it. The start of the next component is to be
3180  * adjusted as well.
3181  *
3182  * \param[in] layout    the current layout
3183  * \param[in] start     the start of the current component
3184  * \param[in,out] end   the end of the current component
3185  * \param[in] offset    the offset to adjust the end position to instead of
3186  *                      extension size
3187  *
3188  * \retval 0            - extended successfully
3189  * \retval < 0          - error
3190  */
3191 static int layout_extend_comp(struct llapi_layout *layout,
3192                               uint64_t start, uint64_t *end,
3193                               uint64_t offset)
3194 {
3195         uint64_t size, next_start, next_end;
3196         int rc;
3197
3198         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_NEXT);
3199         if (rc < 0) {
3200                 fprintf(stderr,
3201                         "%s setstripe: cannot move component cursor: %s\n",
3202                         progname, strerror(errno));
3203                 return rc;
3204         }
3205
3206         /*
3207          * Even if the @size will not be used below, this will fail if
3208          * this is not a SEL component - a good confirmation we are
3209          * working on right components.
3210          */
3211         rc = llapi_layout_extension_size_get(layout, &size);
3212         if (rc < 0) {
3213                 fprintf(stderr,
3214                         "%s setstripe: cannot get component ext size: %s\n",
3215                         progname, strerror(errno));
3216                 return rc;
3217         }
3218
3219         rc = llapi_layout_comp_extent_get(layout, &next_start, &next_end);
3220         if (rc) {
3221                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
3222                         progname, strerror(errno));
3223                 return rc;
3224         }
3225
3226         next_start += offset ?: size;
3227         rc = llapi_layout_comp_extent_set(layout, next_start, next_end);
3228         if (rc) {
3229                 fprintf(stderr, "%s setstripe: cannot set extent: %s\n",
3230                         progname, strerror(errno));
3231                 return rc;
3232         }
3233
3234         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_PREV);
3235         if (rc < 0) {
3236                 fprintf(stderr,
3237                         "%s setstripe: cannot move component cursor: %s\n",
3238                         progname, strerror(errno));
3239                 return rc;
3240         }
3241
3242         *end += offset ?: size;
3243         rc = llapi_layout_comp_extent_set(layout, start, *end);
3244         if (rc) {
3245                 fprintf(stderr, "%s setstripe: cannot set extent: %s\n",
3246                         progname, strerror(errno));
3247                 return rc;
3248         }
3249
3250         return 0;
3251 }
3252
3253 /**
3254  * In 'lfs setstripe --component-add' mode, we need to fetch the extent
3255  * end of the last component in the existing file, and adjust the
3256  * first extent start of the components to be added accordingly.
3257  *
3258  * In the create mode, we need to check if the first component is an extendable
3259  * SEL component and extend its length to the extension size (first component
3260  * of the PFL file is initialised at the create time, cannot be 0-lenght.
3261  */
3262 static int layout_adjust_first_extent(char *fname, struct llapi_layout *layout,
3263                                       bool comp_add)
3264 {
3265         struct llapi_layout *head;
3266         uint64_t start = 0, prev_end = 0;
3267         uint64_t end;
3268         int rc, ret = 0;
3269
3270         if (!layout || !(comp_add || llapi_layout_is_composite(layout)))
3271                 return 0;
3272
3273         errno = 0;
3274         while (comp_add) {
3275                 head = llapi_layout_get_by_path(fname, 0);
3276                 if (!head) {
3277                         fprintf(stderr,
3278                                 "%s setstripe: cannot read layout from '%s': %s\n",
3279                                 progname, fname, strerror(errno));
3280                         return -EINVAL;
3281                 } else if (errno == ENODATA) {
3282                         /*
3283                          * file without LOVEA, this component-add will be turned
3284                          * into a component-create.
3285                          */
3286                         llapi_layout_free(head);
3287                         ret = -ENODATA;
3288
3289                         /*
3290                          * the new layout will be added to an empty one, it
3291                          * still needs to be adjusted below
3292                          */
3293                         comp_add = 0;
3294                         break;
3295                 } else if (!llapi_layout_is_composite(head)) {
3296                         fprintf(stderr,
3297                                 "%s setstripe: '%s' not a composite file\n",
3298                                 progname, fname);
3299                         llapi_layout_free(head);
3300                         return -EINVAL;
3301                 }
3302
3303                 rc = llapi_layout_comp_extent_get(head, &start, &prev_end);
3304                 if (rc) {
3305                         fprintf(stderr,
3306                                 "%s setstripe: cannot get prev extent: %s\n",
3307                                 progname, strerror(errno));
3308                         llapi_layout_free(head);
3309                         return rc;
3310                 }
3311
3312                 llapi_layout_free(head);
3313                 break;
3314         }
3315
3316         /* Make sure we use the first component of the layout to be added. */
3317         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
3318         if (rc < 0) {
3319                 fprintf(stderr,
3320                         "%s setstripe: cannot move component cursor: %s\n",
3321                         progname, strerror(errno));
3322                 return rc;
3323         }
3324
3325         rc = llapi_layout_comp_extent_get(layout, &start, &end);
3326         if (rc) {
3327                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
3328                         progname, strerror(errno));
3329                 return rc;
3330         }
3331
3332         if (start == 0 && end == 0) {
3333                 rc = layout_extend_comp(layout, start, &end,
3334                                         comp_add ? prev_end : 0);
3335                 if (rc)
3336                         return rc;
3337         }
3338
3339         if (start > prev_end || end < prev_end) {
3340                 fprintf(stderr,
3341                         "%s setstripe: first extent [%lu, %lu) not adjacent with extent end %lu\n",
3342                         progname, start, end, prev_end);
3343                 return -EINVAL;
3344         }
3345
3346         rc = llapi_layout_comp_extent_set(layout, prev_end, end);
3347         if (rc) {
3348                 fprintf(stderr,
3349                         "%s setstripe: cannot set component extent [%lu, %lu): %s\n",
3350                         progname, prev_end, end, strerror(errno));
3351                 return rc;
3352         }
3353
3354         return ret;
3355 }
3356
3357 static int mirror_adjust_first_extents(struct mirror_args *list)
3358 {
3359         int rc = 0;
3360
3361         if (!list)
3362                 return 0;
3363
3364         while (list) {
3365                 rc = layout_adjust_first_extent(NULL, list->m_layout, false);
3366                 if (rc)
3367                         break;
3368                 list = list->m_next;
3369         }
3370
3371         return rc;
3372 }
3373
3374 static inline bool arg_is_eof(char *arg)
3375 {
3376         return !strncmp(arg, "-1", strlen("-1")) ||
3377                !strncmp(arg, "EOF", strlen("EOF")) ||
3378                !strncmp(arg, "eof", strlen("eof"));
3379 }
3380
3381 /**
3382  * lfs_mirror_alloc() - Allocate a mirror argument structure.
3383  *
3384  * Return: Valid mirror_args pointer on success and
3385  *         NULL if memory allocation fails.
3386  */
3387 static struct mirror_args *lfs_mirror_alloc(void)
3388 {
3389         struct mirror_args *mirror = NULL;
3390
3391         while (1) {
3392                 mirror = calloc(1, sizeof(*mirror));
3393                 if (mirror) {
3394                         mirror->m_inherit = false;
3395                         break;
3396                 }
3397
3398                 sleep(1);
3399         }
3400
3401         return mirror;
3402 }
3403
3404 /**
3405  * lfs_mirror_free() - Free memory allocated for a mirror argument
3406  *                     structure.
3407  * @mirror: Previously allocated mirror argument structure by
3408  *          lfs_mirror_alloc().
3409  *
3410  * Free memory allocated for @mirror.
3411  *
3412  * Return: void.
3413  */
3414 static void lfs_mirror_free(struct mirror_args *mirror)
3415 {
3416         if (mirror->m_layout)
3417                 llapi_layout_free(mirror->m_layout);
3418         free(mirror);
3419 }
3420
3421 /**
3422  * lfs_mirror_list_free() - Free memory allocated for a mirror list.
3423  * @mirror_list: Previously allocated mirror list.
3424  *
3425  * Free memory allocated for @mirror_list.
3426  *
3427  * Return: void.
3428  */
3429 static void lfs_mirror_list_free(struct mirror_args *mirror_list)
3430 {
3431         struct mirror_args *next_mirror = NULL;
3432
3433         while (mirror_list) {
3434                 next_mirror = mirror_list->m_next;
3435                 lfs_mirror_free(mirror_list);
3436                 mirror_list = next_mirror;
3437         }
3438 }
3439
3440 enum {
3441         LFS_POOL_OPT = 3,
3442         LFS_COMP_COUNT_OPT,
3443         LFS_COMP_START_OPT,
3444         LFS_COMP_FLAGS_OPT,
3445         LFS_COMP_DEL_OPT,
3446         LFS_COMP_SET_OPT,
3447         LFS_COMP_ADD_OPT,
3448         LFS_COMP_NO_VERIFY_OPT,
3449         LFS_PROJID_OPT,
3450         LFS_LAYOUT_FLAGS_OPT, /* used for mirror and foreign flags */
3451         LFS_MIRROR_ID_OPT,
3452         LFS_MIRROR_STATE_OPT,
3453         LFS_LAYOUT_COPY,
3454         LFS_MIRROR_INDEX_OPT,
3455         LFS_LAYOUT_FOREIGN_OPT,
3456         LFS_MODE_OPT,
3457         LFS_NEWERXY_OPT,
3458         LFS_INHERIT_RR_OPT,
3459         LFS_FIND_PERM,
3460 };
3461
3462 #ifndef LCME_USER_MIRROR_FLAGS
3463 /* The mirror flags can be set by users at creation time. */
3464 #define LCME_USER_MIRROR_FLAGS  (LCME_FL_PREF_RW)
3465 #endif
3466
3467 /* functions */
3468 static int lfs_setstripe_internal(int argc, char **argv,
3469                                   enum setstripe_origin opc)
3470 {
3471         struct lfs_setstripe_args        lsa = { 0 };
3472         struct llapi_stripe_param       *param = NULL;
3473         struct find_param                migrate_mdt_param = {
3474                 .fp_max_depth = -1,
3475                 .fp_mdt_index = -1,
3476         };
3477         char                            *fname;
3478         int                              result = 0;
3479         int                              result2 = 0;
3480         char                            *end;
3481         int                              c;
3482         int                              delete = 0;
3483         unsigned long long               size_units = 1;
3484         bool                             migrate_mode = false;
3485         bool                             migrate_mdt_mode = false;
3486         bool                             setstripe_mode = false;
3487         bool                             migration_block = false;
3488         __u64                            migration_flags = 0;
3489         __u32                            tgts[LOV_MAX_STRIPE_COUNT] = { 0 };
3490         int                              comp_del = 0, comp_set = 0;
3491         int                              comp_add = 0;
3492         __u32                            comp_id = 0;
3493         struct llapi_layout             *layout = NULL;
3494         struct llapi_layout             **lpp = &layout;
3495         bool                             mirror_mode = false;
3496         bool                             has_m_file = false;
3497         __u32                            mirror_count = 0;
3498         enum mirror_flags                mirror_flags = 0;
3499         struct mirror_args              *mirror_list = NULL;
3500         struct mirror_args              *new_mirror = NULL;
3501         struct mirror_args              *last_mirror = NULL;
3502         __u16                            mirror_id = 0;
3503         char                             cmd[PATH_MAX];
3504         bool from_yaml = false;
3505         bool from_copy = false;
3506         char *template = NULL;
3507         bool foreign_mode = false;
3508         char *xattr = NULL;
3509         uint32_t type = LU_FOREIGN_TYPE_NONE, flags = 0;
3510         char *mode_opt = NULL;
3511         mode_t previous_umask = 0;
3512         mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
3513
3514         struct option long_opts[] = {
3515 /* find { .val = '0',   .name = "null",         .has_arg = no_argument }, */
3516 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
3517         /* --block is only valid in migrate mode */
3518         { .val = 'b',   .name = "block",        .has_arg = no_argument },
3519 /* find { .val = 'B',   .name = "btime",        .has_arg = required_argument }*/
3520         { .val = LFS_COMP_ADD_OPT,
3521                         .name = "comp-add",     .has_arg = no_argument },
3522         { .val = LFS_COMP_ADD_OPT,
3523                         .name = "component-add", .has_arg = no_argument },
3524         { .val = LFS_COMP_DEL_OPT,
3525                         .name = "comp-del",     .has_arg = no_argument },
3526         { .val = LFS_COMP_DEL_OPT,
3527                         .name = "component-del", .has_arg = no_argument },
3528         { .val = LFS_COMP_FLAGS_OPT,
3529                         .name = "comp-flags",   .has_arg = required_argument },
3530         { .val = LFS_COMP_FLAGS_OPT,
3531                         .name = "component-flags",
3532                                                 .has_arg = required_argument },
3533         { .val = LFS_COMP_SET_OPT,
3534                         .name = "comp-set",     .has_arg = no_argument },
3535         { .val = LFS_COMP_SET_OPT,
3536                         .name = "component-set",
3537                                                 .has_arg = no_argument},
3538         { .val = LFS_COMP_NO_VERIFY_OPT,
3539                         .name = "no-verify",    .has_arg = no_argument},
3540         { .val = LFS_LAYOUT_FLAGS_OPT,
3541                         .name = "flags",        .has_arg = required_argument},
3542         { .val = LFS_LAYOUT_FOREIGN_OPT,
3543                         .name = "foreign",      .has_arg = optional_argument},
3544         { .val = LFS_MIRROR_ID_OPT,
3545                         .name = "mirror-id",    .has_arg = required_argument},
3546         { .val = LFS_MODE_OPT,
3547                         .name = "mode",         .has_arg = required_argument},
3548         { .val = LFS_LAYOUT_COPY,
3549                         .name = "copy",         .has_arg = required_argument},
3550         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument},
3551         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument},
3552         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument},
3553         { .val = 'C',   .name = "overstripe-count",
3554                                                 .has_arg = required_argument},
3555         { .val = 'd',   .name = "delete",       .has_arg = no_argument},
3556         { .val = 'd',   .name = "destroy",      .has_arg = no_argument},
3557         /* --non-direct is only valid in migrate mode */
3558         { .val = 'D',   .name = "non-direct",   .has_arg = no_argument },
3559         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument},
3560         { .val = 'E',   .name = "component-end",
3561                                                 .has_arg = required_argument},
3562         { .val = 'f',   .name = "file",         .has_arg = required_argument },
3563 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
3564 /* find { .val = 'g',   .name = "gid",          .has_arg = no_argument }, */
3565 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
3566         { .val = 'h',   .name = "help",         .has_arg = no_argument },
3567         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument},
3568         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument},
3569         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument},
3570         { .val = 'I',   .name = "comp-id",      .has_arg = required_argument},
3571         { .val = 'I',   .name = "component-id", .has_arg = required_argument},
3572 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
3573         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
3574         { .val = 'm',   .name = "mdt",          .has_arg = required_argument},
3575         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument},
3576         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument},
3577         /* --non-block is only valid in migrate mode */
3578         { .val = 'n',   .name = "non-block",    .has_arg = no_argument },
3579         { .val = 'N',   .name = "mirror-count", .has_arg = optional_argument},
3580         { .val = 'o',   .name = "ost",          .has_arg = required_argument },
3581 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
3582         { .val = 'o',   .name = "ost-list",     .has_arg = required_argument },
3583         { .val = 'o',   .name = "ost_list",     .has_arg = required_argument },
3584 #endif
3585         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
3586 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
3587 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
3588 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
3589 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
3590         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
3591         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
3592 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
3593 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
3594 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
3595 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
3596         /* --verbose is only valid in migrate mode */
3597         { .val = 'v',   .name = "verbose",      .has_arg = no_argument},
3598         { .val = 'x',   .name = "xattr",        .has_arg = required_argument },
3599 /* dirstripe { .val = 'X',.name = "max-inherit",.has_arg = required_argument }*/
3600         { .val = 'y',   .name = "yaml",         .has_arg = required_argument },
3601         { .val = 'z',   .name = "ext-size",     .has_arg = required_argument},
3602         { .val = 'z',   .name = "extension-size", .has_arg = required_argument},
3603         { .name = NULL } };
3604
3605         setstripe_args_init(&lsa);
3606
3607         migrate_mode = (opc == SO_MIGRATE);
3608         mirror_mode = (opc == SO_MIRROR_CREATE || opc == SO_MIRROR_EXTEND);
3609         setstripe_mode = (opc == SO_SETSTRIPE);
3610         if (opc == SO_MIRROR_DELETE) {
3611                 delete = 1;
3612                 mirror_flags = MF_DESTROY;
3613         }
3614
3615         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
3616         progname = cmd;
3617         while ((c = getopt_long(argc, argv,
3618                                 "bc:C:dDE:f:hH:i:I:m:N::no:p:L:s:S:vx:y:z:",
3619                                 long_opts, NULL)) >= 0) {
3620                 size_units = 1;
3621                 switch (c) {
3622                 case 0:
3623                         /* Long options. */
3624                         break;
3625                 case LFS_COMP_ADD_OPT:
3626                         comp_add = 1;
3627                         break;
3628                 case LFS_COMP_DEL_OPT:
3629                         comp_del = 1;
3630                         break;
3631                 case LFS_COMP_FLAGS_OPT:
3632                         result = comp_str2flags(optarg, &lsa.lsa_comp_flags,
3633                                                 &lsa.lsa_comp_neg_flags);
3634                         if (result != 0)
3635                                 goto usage_error;
3636                         if (mirror_mode && lsa.lsa_comp_neg_flags) {
3637                                 fprintf(stderr,
3638                                         "%s: inverted flags are not supported\n",
3639                                         progname);
3640                                 goto usage_error;
3641                         }
3642                         break;
3643                 case LFS_COMP_SET_OPT:
3644                         comp_set = 1;
3645                         break;
3646                 case LFS_COMP_NO_VERIFY_OPT:
3647                         mirror_flags |= MF_NO_VERIFY;
3648                         break;
3649                 case LFS_MIRROR_ID_OPT: {
3650                         unsigned long int id;
3651
3652                         errno = 0;
3653                         id = strtoul(optarg, &end, 0);
3654                         if (errno != 0 || *end != '\0' || id == 0 ||
3655                             id > UINT16_MAX) {
3656                                 fprintf(stderr,
3657                                         "%s %s: invalid mirror ID '%s'\n",
3658                                         progname, argv[0], optarg);
3659                                 goto usage_error;
3660                         }
3661
3662                         mirror_id = (__u16)id;
3663                         break;
3664                 }
3665                 case LFS_LAYOUT_FLAGS_OPT: {
3666                         uint32_t neg_flags;
3667
3668                         /* check for numeric flags (foreign and mirror cases) */
3669                         if (setstripe_mode && !mirror_mode && !last_mirror) {
3670                                 errno = 0;
3671                                 flags = strtoul(optarg, &end, 16);
3672                                 if (errno != 0 || *end != '\0' ||
3673                                     flags >= UINT32_MAX) {
3674                                         fprintf(stderr,
3675                                                 "%s %s: invalid hex flags '%s'\n",
3676                                                 progname, argv[0], optarg);
3677                                         return CMD_HELP;
3678                                 }
3679                                 if (!foreign_mode) {
3680                                         fprintf(stderr,
3681                                                 "%s %s: hex flags must be specified with --foreign option\n",
3682                                                 progname, argv[0]);
3683                                         return CMD_HELP;
3684                                 }
3685                                 break;
3686                         }
3687
3688                         if (!mirror_mode || !last_mirror) {
3689                                 fprintf(stderr,
3690                                         "error: %s: --flags must be specified with --mirror-count|-N option\n",
3691                                         progname);
3692                                 goto usage_error;
3693                         }
3694
3695                         result = comp_str2flags(optarg, &last_mirror->m_flags,
3696                                                 &neg_flags);
3697                         if (result != 0)
3698                                 goto usage_error;
3699
3700                         if (neg_flags) {
3701                                 fprintf(stderr,
3702                                         "%s: inverted flags are not supported\n",
3703                                         progname);
3704                                 result = -EINVAL;
3705                                 goto usage_error;
3706                         }
3707                         if (last_mirror->m_flags & ~LCME_USER_MIRROR_FLAGS) {
3708                                 fprintf(stderr,
3709                                         "%s: unsupported mirror flags: %s\n",
3710                                         progname, optarg);
3711                                 result = -EINVAL;
3712                                 goto error;
3713                         }
3714                         break;
3715                 }
3716                 case LFS_LAYOUT_FOREIGN_OPT:
3717                         if (optarg) {
3718                                 /* check pure numeric */
3719                                 type = strtoul(optarg, &end, 0);
3720                                 if (*end) {
3721                                         /* check name */
3722                                         type = check_foreign_type_name(optarg);
3723                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
3724                                                 fprintf(stderr,
3725                                                         "%s %s: unrecognized foreign type '%s'\n",
3726                                                         progname, argv[0],
3727                                                         optarg);
3728                                                 return CMD_HELP;
3729                                         }
3730                                 } else if (type >= UINT32_MAX) {
3731                                         fprintf(stderr,
3732                                                 "%s %s: invalid foreign type '%s'\n",
3733                                                 progname, argv[0], optarg);
3734                                         return CMD_HELP;
3735                                 }
3736                         }
3737                         foreign_mode = true;
3738                         break;
3739                 case LFS_MODE_OPT:
3740                         mode_opt = optarg;
3741                         if (mode_opt) {
3742                                 mode = strtoul(mode_opt, &end, 8);
3743                                 if (*end != '\0') {
3744                                         fprintf(stderr,
3745                                                 "%s %s: bad mode '%s'\n",
3746                                                 progname, argv[0], mode_opt);
3747                                         return CMD_HELP;
3748                                 }
3749                                 previous_umask = umask(0);
3750                         }
3751                         break;
3752                 case LFS_LAYOUT_COPY:
3753                         from_copy = true;
3754                         template = optarg;
3755                         break;
3756                 case 'b':
3757                         if (!migrate_mode) {
3758                                 fprintf(stderr,
3759                                         "%s %s: -b|--block valid only for migrate command\n",
3760                                         progname, argv[0]);
3761                                 goto usage_error;
3762                         }
3763                         migration_block = true;
3764                         break;
3765                 case 'C':
3766                         if (lsa.lsa_pattern == LLAPI_LAYOUT_MDT) {
3767                                 fprintf(stderr,
3768                                         "%s %s: -C|--overstripe-count incompatible with DoM layout\n",
3769                                         progname, argv[0]);
3770                                 goto usage_error;
3771                         }
3772                         lsa.lsa_pattern = LLAPI_LAYOUT_OVERSTRIPING;
3773                         /* fall through */
3774                 case 'c':
3775                         errno = 0;
3776                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
3777                         if (errno != 0 || *end != '\0'||
3778                             lsa.lsa_stripe_count < -1 ||
3779                             lsa.lsa_stripe_count > LOV_MAX_STRIPE_COUNT) {
3780                                 fprintf(stderr,
3781                                         "%s %s: invalid stripe count '%s'\n",
3782                                         progname, argv[0], optarg);
3783                                 goto usage_error;
3784                         }
3785
3786                         if (lsa.lsa_stripe_count == -1)
3787                                 lsa.lsa_stripe_count = LLAPI_LAYOUT_WIDE;
3788                         break;
3789                 case 'd':
3790                         /* delete the default striping pattern */
3791                         delete = 1;
3792                         if (opc == SO_MIRROR_SPLIT) {
3793                                 if (has_m_file) {
3794                                         fprintf(stderr,
3795                                               "%s %s: -d cannot used with -f\n",
3796                                                 progname, argv[0]);
3797                                         goto usage_error;
3798                                 }
3799                                 mirror_flags |= MF_DESTROY;
3800                         }
3801                         break;
3802                 case 'D':
3803                         if (!migrate_mode) {
3804                                 fprintf(stderr,
3805                                         "%s %s: -D|--non-direct is valid only for migrate command\n",
3806                                         progname, argv[0]);
3807                                 goto usage_error;
3808                         }
3809                         migration_flags |= MIGRATION_NONDIRECT;
3810                         break;
3811                 case 'E':
3812                         if (lsa.lsa_comp_end != 0) {
3813                                 result = comp_args_to_layout(lpp, &lsa, true);
3814                                 if (result) {
3815                                         fprintf(stderr, "%s: invalid layout\n",
3816                                                 progname);
3817                                         goto usage_error;
3818                                 }
3819
3820                                 setstripe_args_init_inherit(&lsa);
3821                         }
3822
3823                         if (arg_is_eof(optarg)) {
3824                                 lsa.lsa_comp_end = LUSTRE_EOF;
3825                         } else {
3826                                 result = llapi_parse_size(optarg,
3827                                                           &lsa.lsa_comp_end,
3828                                                           &size_units, 0);
3829                                 /* assume units of KB if too small */
3830                                 if (lsa.lsa_comp_end < 4096)
3831                                         lsa.lsa_comp_end *= 1024;
3832                                 if (result ||
3833                                     lsa.lsa_comp_end & (LOV_MIN_STRIPE_SIZE - 1)) {
3834                                         fprintf(stderr,
3835                                                 "%s %s: invalid component end '%s'\n",
3836                                                 progname, argv[0], optarg);
3837                                         goto usage_error;
3838                                 }
3839                         }
3840                         break;
3841                 case 'H':
3842                         if (!migrate_mode) {
3843                                 fprintf(stderr,
3844                                         "--mdt-hash is valid only for migrate command\n");
3845                                 return CMD_HELP;
3846                         }
3847
3848                         lsa.lsa_pattern = check_hashtype(optarg);
3849                         if (lsa.lsa_pattern == 0) {
3850                                 fprintf(stderr,
3851                                         "%s %s: bad stripe hash type '%s'\n",
3852                                         progname, argv[0], optarg);
3853                                 return CMD_HELP;
3854                         }
3855                         break;
3856                 case 'i':
3857                         errno = 0;
3858                         lsa.lsa_stripe_off = strtol(optarg, &end, 0);
3859                         if (errno != 0 || *end != '\0' ||
3860                             lsa.lsa_stripe_off < -1 ||
3861                             lsa.lsa_stripe_off > LOV_V1_INSANE_STRIPE_COUNT) {
3862                                 fprintf(stderr,
3863                                         "%s %s: invalid stripe offset '%s'\n",
3864                                         progname, argv[0], optarg);
3865                                 goto usage_error;
3866                         }
3867                         if (lsa.lsa_stripe_off == -1)
3868                                 lsa.lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
3869                         break;
3870                 case 'I':
3871                         comp_id = strtoul(optarg, &end, 0);
3872                         if (*end != '\0' || comp_id == 0 ||
3873                             comp_id > LCME_ID_MAX) {
3874                                 fprintf(stderr,
3875                                         "%s %s: invalid component ID '%s'\n",
3876                                         progname, argv[0], optarg);
3877                                 goto usage_error;
3878                         }
3879                         break;
3880                 case 'f':
3881                         if (opc != SO_MIRROR_EXTEND && opc != SO_MIRROR_SPLIT) {
3882                                 fprintf(stderr,
3883                                         "error: %s: invalid option: %s\n",
3884                                         progname, argv[optopt + 1]);
3885                                 goto usage_error;
3886                         }
3887                         if (opc == SO_MIRROR_EXTEND) {
3888                                 if (!last_mirror) {
3889                                         fprintf(stderr,
3890                                 "error: %s: '-N' must exist in front of '%s'\n",
3891                                                 progname, argv[optopt + 1]);
3892                                         goto usage_error;
3893                                 }
3894                                 last_mirror->m_file = optarg;
3895                                 last_mirror->m_count = 1;
3896                         } else {
3897                                 /* mirror split */
3898                                 if (!mirror_list)
3899                                         mirror_list = lfs_mirror_alloc();
3900                                 mirror_list->m_file = optarg;
3901                         }
3902                         has_m_file = true;
3903                         break;
3904                 case 'L':
3905                         if (strcmp(argv[optind - 1], "mdt") == 0) {
3906                                 /* Can be only the first component */
3907                                 if (layout) {
3908                                         result = -EINVAL;
3909                                         fprintf(stderr,
3910                                                 "error: 'mdt' layout can be only the first one\n");
3911                                         goto error;
3912                                 }
3913                                 if (lsa.lsa_comp_end > (1ULL << 30)) { /* 1Gb */
3914                                         result = -EFBIG;
3915                                         fprintf(stderr,
3916                                                 "error: 'mdt' layout size is too big\n");
3917                                         goto error;
3918                                 }
3919                                 lsa.lsa_pattern = LLAPI_LAYOUT_MDT;
3920                                 lsa.lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
3921                         } else if (strcmp(argv[optind - 1], "raid0") != 0) {
3922                                 result = -EINVAL;
3923                                 fprintf(stderr,
3924                                         "error: layout '%s' is unknown, supported layouts are: 'mdt', 'raid0'\n",
3925                                         argv[optind]);
3926                                 goto error;
3927                         }
3928                         break;
3929                 case 'm':
3930                         if (!migrate_mode) {
3931                                 fprintf(stderr,
3932                                         "%s %s: -m|--mdt-index is valid only for migrate command\n",
3933                                         progname, argv[0]);
3934                                 goto usage_error;
3935                         }
3936                         migrate_mdt_mode = true;
3937                         lsa.lsa_nr_tgts = parse_targets(tgts,
3938                                                 sizeof(tgts) / sizeof(__u32),
3939                                                 lsa.lsa_nr_tgts, optarg, NULL);
3940                         if (lsa.lsa_nr_tgts < 0) {
3941                                 fprintf(stderr,
3942                                         "%s: invalid MDT target(s) '%s'\n",
3943                                         progname, optarg);
3944                                 goto usage_error;
3945                         }
3946
3947                         lsa.lsa_tgts = tgts;
3948                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
3949                                 lsa.lsa_stripe_off = tgts[0];
3950                         break;
3951                 case 'n':
3952                         if (!migrate_mode) {
3953                                 fprintf(stderr,
3954                                         "%s %s: -n|--non-block valid only for migrate command\n",
3955                                         progname, argv[0]);
3956                                 goto usage_error;
3957                         }
3958                         migration_flags |= MIGRATION_NONBLOCK;
3959                         break;
3960                 case 'N':
3961                         if (opc == SO_SETSTRIPE) {
3962                                 opc = SO_MIRROR_CREATE;
3963                                 mirror_mode = true;
3964                         }
3965                         mirror_count = 1;
3966                         if (optarg) {
3967                                 errno = 0;
3968                                 mirror_count = strtoul(optarg, &end, 0);
3969                                 if (errno != 0 || *end != '\0' ||
3970                                     mirror_count == 0 ||
3971                                     mirror_count > LUSTRE_MIRROR_COUNT_MAX) {
3972                                         fprintf(stderr,
3973                                                 "error: %s: bad mirror count: %s\n",
3974                                                 progname, optarg);
3975                                         result = -EINVAL;
3976                                         goto error;
3977                                 }
3978                         }
3979
3980                         new_mirror = lfs_mirror_alloc();
3981                         new_mirror->m_count = mirror_count;
3982
3983                         if (!mirror_list)
3984                                 mirror_list = new_mirror;
3985
3986                         if (last_mirror) {
3987                                 /* wrap up last mirror */
3988                                 if (!setstripe_args_specified(&lsa))
3989                                         last_mirror->m_inherit = true;
3990                                 if (lsa.lsa_comp_end == 0)
3991                                         lsa.lsa_comp_end = LUSTRE_EOF;
3992
3993                                 result = comp_args_to_layout(lpp, &lsa, true);
3994                                 if (result) {
3995                                         lfs_mirror_free(new_mirror);
3996                                         goto error;
3997                                 }
3998
3999                                 setstripe_args_init_inherit(&lsa);
4000
4001                                 last_mirror->m_next = new_mirror;
4002                         }
4003
4004                         last_mirror = new_mirror;
4005                         lpp = &last_mirror->m_layout;
4006                         break;
4007                 case 'o':
4008 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4009                         if (strcmp(argv[optind - 1], "--ost-list") == 0)
4010                                 fprintf(stderr,
4011                                         "warning: '--ost-list' is deprecated, use '--ost' instead\n");
4012 #endif
4013                         if (lsa.lsa_pattern == LLAPI_LAYOUT_MDT) {
4014                                 fprintf(stderr,
4015                                         "%s %s: -o|--ost incompatible with DoM layout\n",
4016                                         progname, argv[0]);
4017                                 goto usage_error;
4018                         }
4019                         /*
4020                          * -o allows overstriping, and must note it because
4021                          * parse_targets is shared with MDT striping, which
4022                          * does not allow duplicates
4023                          */
4024                         lsa.lsa_pattern = LLAPI_LAYOUT_OVERSTRIPING;
4025                         lsa.lsa_nr_tgts = parse_targets(tgts,
4026                                                 sizeof(tgts) / sizeof(__u32),
4027                                                 lsa.lsa_nr_tgts, optarg,
4028                                                 &lsa.lsa_pattern);
4029                         if (lsa.lsa_nr_tgts < 0) {
4030                                 fprintf(stderr,
4031                                         "%s %s: invalid OST target(s) '%s'\n",
4032                                         progname, argv[0], optarg);
4033                                 goto usage_error;
4034                         }
4035
4036                         lsa.lsa_tgts = tgts;
4037                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
4038                                 lsa.lsa_stripe_off = tgts[0];
4039                         break;
4040                 case 'p':
4041                         if (!optarg)
4042                                 goto usage_error;
4043                         lsa.lsa_pool_name = optarg;
4044
4045                         if (strlen(lsa.lsa_pool_name) == 0 ||
4046                             strncmp(lsa.lsa_pool_name, "none",
4047                                     LOV_MAXPOOLNAME) == 0)
4048                                 lsa.lsa_pool_name = NULL;
4049                         break;
4050                 case 'S':
4051                         result = llapi_parse_size(optarg, &lsa.lsa_stripe_size,
4052                                                   &size_units, 0);
4053                         /* assume units of KB if too small to be valid */
4054                         if (lsa.lsa_stripe_size < 4096)
4055                                 lsa.lsa_stripe_size *= 1024;
4056                         if (result ||
4057                             lsa.lsa_stripe_size & (LOV_MIN_STRIPE_SIZE - 1)) {
4058                                 fprintf(stderr,
4059                                         "%s %s: invalid stripe size '%s'\n",
4060                                         progname, argv[0], optarg);
4061                                 goto usage_error;
4062                         }
4063                         break;
4064                 case 'v':
4065                         if (!migrate_mode) {
4066                                 fprintf(stderr,
4067                                         "%s %s: -v|--verbose valid only for migrate command\n",
4068                                         progname, argv[0]);
4069                                 goto usage_error;
4070                         }
4071                         migrate_mdt_param.fp_verbose = VERBOSE_DETAIL;
4072                         migration_flags = MIGRATION_VERBOSE;
4073                         break;
4074                 case 'x':
4075                         xattr = optarg;
4076                         break;
4077                 case 'y':
4078                         from_yaml = true;
4079                         template = optarg;
4080                         break;
4081                 case 'z':
4082                         result = llapi_parse_size(optarg,
4083                                                   &lsa.lsa_extension_size,
4084                                                   &size_units, 0);
4085                         if (result) {
4086                                 fprintf(stderr,
4087                                         "%s %s: invalid extension size '%s'\n",
4088                                         progname, argv[0], optarg);
4089                                 goto usage_error;
4090                         }
4091
4092                         lsa.lsa_extension_comp = true;
4093                         break;
4094                 default:
4095                         fprintf(stderr, "%s: unrecognized option '%s'\n",
4096                                 progname, argv[optind - 1]);
4097                 case 'h':
4098                         goto usage_error;
4099                 }
4100         }
4101
4102         fname = argv[optind];
4103
4104         if (optind == argc) {
4105                 fprintf(stderr, "%s %s: FILE must be specified\n",
4106                         progname, argv[0]);
4107                 goto usage_error;
4108         }
4109
4110         /* lfs migrate $filename should keep the file's layout by default */
4111         if (migrate_mode && !layout && !from_yaml &&
4112             !setstripe_args_specified(&lsa) && !lsa.lsa_pool_name)
4113                 from_copy = true;
4114
4115         if (xattr && !foreign_mode) {
4116                 /*
4117                  * only print a warning as this is harmless and will be ignored
4118                  */
4119                 fprintf(stderr,
4120                         "%s %s: xattr has been specified for non-foreign layout\n",
4121                         progname, argv[0]);
4122         } else if (foreign_mode && !xattr) {
4123                 fprintf(stderr,
4124                         "%s %s: xattr must be provided in foreign mode\n",
4125                         progname, argv[0]);
4126                 goto usage_error;
4127         }
4128
4129         if (foreign_mode && (!setstripe_mode || comp_add | comp_del ||
4130             comp_set || comp_id || delete || from_copy ||
4131             setstripe_args_specified(&lsa) || lsa.lsa_nr_tgts ||
4132             lsa.lsa_tgts)) {
4133                 fprintf(stderr,
4134                         "%s %s: only --xattr/--flags/--mode options are valid with --foreign\n",
4135                         progname, argv[0]);
4136                 return CMD_HELP;
4137         }
4138
4139         if (mirror_mode && mirror_count == 0) {
4140                 fprintf(stderr,
4141                         "error: %s: --mirror-count|-N option is required\n",
4142                         progname);
4143                 result = -EINVAL;
4144                 goto error;
4145         }
4146
4147         if (mirror_mode) {
4148                 if (!setstripe_args_specified(&lsa))
4149                         last_mirror->m_inherit = true;
4150                 if (lsa.lsa_comp_end == 0)
4151                         lsa.lsa_comp_end = LUSTRE_EOF;
4152         }
4153
4154         if (lsa.lsa_comp_end != 0) {
4155                 result = comp_args_to_layout(lpp, &lsa, true);
4156                 if (result) {
4157                         fprintf(stderr, "error: %s: invalid layout\n",
4158                                 progname);
4159                         result = -EINVAL;
4160                         goto error;
4161                 }
4162         }
4163
4164         if (mirror_flags & MF_NO_VERIFY) {
4165                 if (opc != SO_MIRROR_EXTEND) {
4166                         fprintf(stderr,
4167                                 "error: %s: --no-verify is valid only for lfs mirror extend command\n",
4168                                 progname);
4169                         result = -EINVAL;
4170                         goto error;
4171                 } else if (!has_m_file) {
4172                         fprintf(stderr,
4173                                 "error: %s: --no-verify must be specified with -f <victim_file> option\n",
4174                                 progname);
4175                         result = -EINVAL;
4176                         goto error;
4177                 }
4178         }
4179
4180         if (comp_set && !comp_id && !lsa.lsa_pool_name) {
4181                 fprintf(stderr,
4182                         "%s %s: --component-set doesn't have component-id set\n",
4183                         progname, argv[0]);
4184                 goto usage_error;
4185         }
4186
4187         if ((delete + comp_set + comp_del + comp_add) > 1) {
4188                 fprintf(stderr,
4189                         "%s %s: options --component-set, --component-del, --component-add and -d are mutually exclusive\n",
4190                         progname, argv[0]);
4191                 goto usage_error;
4192         }
4193
4194         if (delete && (setstripe_args_specified(&lsa) || comp_id != 0 ||
4195                        lsa.lsa_comp_flags != 0 || layout != NULL)) {
4196                 fprintf(stderr,
4197                         "%s %s: option -d is mutually exclusive with -s, -c, -o, -p, -I, -F and -E options\n",
4198                         progname, argv[0]);
4199                 goto usage_error;
4200         }
4201
4202         if ((comp_set || comp_del) &&
4203             (setstripe_args_specified(&lsa) || layout != NULL)) {
4204                 fprintf(stderr,
4205                         "%s %s: options --component-del and --component-set are mutually exclusive when used with -c, -E, -o, -p, or -s\n",
4206                         progname, argv[0]);
4207                 goto usage_error;
4208         }
4209
4210         if (comp_del && comp_id != 0 && lsa.lsa_comp_flags != 0) {
4211                 fprintf(stderr,
4212                         "%s %s: options -I and -F are mutually exclusive when used with --component-del\n",
4213                         progname, argv[0]);
4214                 goto usage_error;
4215         }
4216
4217         if (comp_add || comp_del) {
4218                 struct stat st;
4219
4220                 result = lstat(fname, &st);
4221                 if (result == 0 && S_ISDIR(st.st_mode)) {
4222                         fprintf(stderr,
4223                                 "%s setstripe: cannot use --component-add or --component-del for directory\n",
4224                                 progname);
4225                         goto usage_error;
4226                 }
4227
4228                 if (mirror_mode) {
4229                         fprintf(stderr,
4230                                 "error: %s: can't use --component-add or --component-del for mirror operation\n",
4231                                 progname);
4232                         goto usage_error;
4233                 }
4234         }
4235
4236         if (comp_add) {
4237                 if (!layout) {
4238                         fprintf(stderr,
4239                                 "%s %s: option -E must be specified with --component-add\n",
4240                                 progname, argv[0]);
4241                         goto usage_error;
4242                 }
4243         }
4244
4245         if (from_yaml && from_copy) {
4246                 fprintf(stderr,
4247                         "%s: can't specify --yaml and --copy together\n",
4248                         progname);
4249                 goto error;
4250         }
4251
4252         if ((from_yaml || from_copy) &&
4253             (setstripe_args_specified(&lsa) || layout != NULL)) {
4254                 fprintf(stderr,
4255                         "error: %s: can't specify --yaml or --copy with -c, -S, -i, -o, -p or -E options.\n",
4256                         argv[0]);
4257                 goto error;
4258         }
4259
4260         if ((migration_flags & MIGRATION_NONBLOCK) && migration_block) {
4261                 fprintf(stderr,
4262                         "%s %s: options --non-block and --block are mutually exclusive\n",
4263                         progname, argv[0]);
4264                 goto usage_error;
4265         }
4266
4267         if (!comp_del && !comp_set && opc != SO_MIRROR_SPLIT &&
4268             opc != SO_MIRROR_DELETE && comp_id != 0) {
4269                 fprintf(stderr,
4270                         "%s: option -I can only be used with --component-del or --component-set or lfs mirror split\n",
4271                         progname);
4272                 goto usage_error;
4273         }
4274
4275         if (migrate_mdt_mode) {
4276                 struct lmv_user_md *lmu;
4277
4278                 /* initialize migrate mdt parameters */
4279                 lmu = calloc(1, lmv_user_md_size(lsa.lsa_nr_tgts,
4280                                                  LMV_USER_MAGIC_SPECIFIC));
4281                 if (!lmu) {
4282                         fprintf(stderr,
4283                                 "%s %s: cannot allocate memory for lmv_user_md: %s\n",
4284                                 progname, argv[0], strerror(ENOMEM));
4285                         result = -ENOMEM;
4286                         goto error;
4287                 }
4288                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
4289                         lmu->lum_stripe_count = lsa.lsa_stripe_count;
4290                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT) {
4291                         fprintf(stderr,
4292                                 "%s %s: migrate should specify MDT index\n",
4293                                 progname, argv[0]);
4294                         free(lmu);
4295                         goto usage_error;
4296                 }
4297                 lmu->lum_stripe_offset = lsa.lsa_stripe_off;
4298                 if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
4299                         lmu->lum_hash_type = lsa.lsa_pattern;
4300                 else
4301                         lmu->lum_hash_type = LMV_HASH_TYPE_UNKNOWN;
4302                 if (lsa.lsa_pool_name) {
4303                         strncpy(lmu->lum_pool_name, lsa.lsa_pool_name,
4304                                 sizeof(lmu->lum_pool_name) - 1);
4305                         lmu->lum_pool_name[sizeof(lmu->lum_pool_name) - 1] = 0;
4306                 }
4307                 if (lsa.lsa_nr_tgts > 1) {
4308                         int i;
4309
4310                         if (lsa.lsa_stripe_count > 0 &&
4311                             lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
4312                             lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
4313                                 fprintf(stderr,
4314                                         "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
4315                                         progname, lsa.lsa_stripe_count,
4316                                         lsa.lsa_nr_tgts);
4317                                 free(lmu);
4318                                 goto usage_error;
4319                         }
4320
4321                         lmu->lum_magic = LMV_USER_MAGIC_SPECIFIC;
4322                         lmu->lum_stripe_count = lsa.lsa_nr_tgts;
4323                         for (i = 0; i < lsa.lsa_nr_tgts; i++)
4324                                 lmu->lum_objects[i].lum_mds = lsa.lsa_tgts[i];
4325                 } else {
4326                         lmu->lum_magic = LMV_USER_MAGIC;
4327                 }
4328
4329                 migrate_mdt_param.fp_lmv_md = lmu;
4330                 migrate_mdt_param.fp_migrate = 1;
4331         } else if (!layout) {
4332                 if (lsa_args_stripe_count_check(&lsa))
4333                         goto usage_error;
4334
4335                 /* initialize stripe parameters */
4336                 param = calloc(1, offsetof(typeof(*param),
4337                                lsp_osts[lsa.lsa_nr_tgts]));
4338                 if (!param) {
4339                         fprintf(stderr,
4340                                 "%s %s: cannot allocate memory for parameters: %s\n",
4341                                 progname, argv[0], strerror(ENOMEM));
4342                         result = -ENOMEM;
4343                         goto error;
4344                 }
4345
4346                 if (lsa.lsa_stripe_size != LLAPI_LAYOUT_DEFAULT)
4347                         param->lsp_stripe_size = lsa.lsa_stripe_size;
4348                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
4349                         if (lsa.lsa_stripe_count == LLAPI_LAYOUT_WIDE)
4350                                 param->lsp_stripe_count = -1;
4351                         else
4352                                 param->lsp_stripe_count = lsa.lsa_stripe_count;
4353                 }
4354                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
4355                         param->lsp_stripe_offset = -1;
4356                 else
4357                         param->lsp_stripe_offset = lsa.lsa_stripe_off;
4358                 param->lsp_stripe_pattern =
4359                                 llapi_pattern_to_lov(lsa.lsa_pattern);
4360                 if (param->lsp_stripe_pattern == EINVAL) {
4361                         fprintf(stderr, "error: %s: invalid stripe pattern\n",
4362                                 argv[0]);
4363                         free(param);
4364                         goto usage_error;
4365                 }
4366                 param->lsp_pool = lsa.lsa_pool_name;
4367                 param->lsp_is_specific = false;
4368
4369                 if (lsa.lsa_nr_tgts > 0) {
4370                         param->lsp_is_specific = true;
4371                         param->lsp_stripe_count = lsa.lsa_nr_tgts;
4372                         memcpy(param->lsp_osts, tgts,
4373                                sizeof(*tgts) * lsa.lsa_nr_tgts);
4374                 }
4375         }
4376
4377         if (from_yaml) {
4378                 /* generate a layout from a YAML template */
4379                 result = lfs_comp_create_from_yaml(template, &layout,
4380                                                    &lsa, tgts);
4381                 if (result) {
4382                         fprintf(stderr,
4383                                 "error: %s: can't create composite layout from template file %s\n",
4384                                 argv[0], template);
4385                         goto error;
4386                 }
4387         }
4388
4389         if (layout != NULL || mirror_list != NULL) {
4390                 if (mirror_list)
4391                         result = mirror_adjust_first_extents(mirror_list);
4392                 else
4393                         result = layout_adjust_first_extent(fname, layout,
4394                                                             comp_add);
4395                 if (result == -ENODATA)
4396                         comp_add = 0;
4397                 else if (result != 0) {
4398                         fprintf(stderr, "error: %s: invalid layout\n",
4399                                 progname);
4400                         goto error;
4401                 }
4402         }
4403
4404         for (fname = argv[optind]; fname != NULL; fname = argv[++optind]) {
4405                 if (from_copy) {
4406                         layout = llapi_layout_get_by_path(template ?: fname, 0);
4407                         if (!layout) {
4408                                 fprintf(stderr,
4409                                         "%s: can't create composite layout from file %s: %s\n",
4410                                         progname, template ?: fname,
4411                                         strerror(errno));
4412                                 result = -errno;
4413                                 goto error;
4414                         }
4415                 }
4416
4417                 if (migrate_mdt_mode) {
4418                         result = llapi_migrate_mdt(fname, &migrate_mdt_param);
4419                 } else if (migrate_mode) {
4420                         result = lfs_migrate(fname, migration_flags, param,
4421                                              layout);
4422                 } else if (comp_set != 0) {
4423                         result = lfs_component_set(fname, comp_id,
4424                                                    lsa.lsa_pool_name,
4425                                                    lsa.lsa_comp_flags,
4426                                                    lsa.lsa_comp_neg_flags);
4427                 } else if (comp_del != 0) {
4428                         result = lfs_component_del(fname, comp_id,
4429                                                    lsa.lsa_comp_flags,
4430                                                    lsa.lsa_comp_neg_flags);
4431                 } else if (comp_add != 0) {
4432                         result = lfs_component_add(fname, layout);
4433                 } else if (opc == SO_MIRROR_CREATE) {
4434                         result = mirror_create(fname, mirror_list);
4435                 } else if (opc == SO_MIRROR_EXTEND) {
4436                         result = mirror_extend(fname, mirror_list,
4437                                                mirror_flags);
4438                 } else if (opc == SO_MIRROR_SPLIT || opc == SO_MIRROR_DELETE) {
4439                         if (!mirror_id && !comp_id && !lsa.lsa_pool_name) {
4440                                 fprintf(stderr,
4441                                         "%s: no mirror id, component id, or pool name specified to delete from '%s'\n",
4442                                         progname, fname);
4443                                 goto usage_error;
4444                         }
4445                         if (lsa.lsa_pool_name)
4446                                 mirror_flags |= MF_COMP_POOL;
4447                         else if (mirror_id != 0)
4448                                 comp_id = mirror_id;
4449                         else
4450                                 mirror_flags |= MF_COMP_ID;
4451                         if (has_m_file && !strcmp(fname, mirror_list->m_file)) {
4452                                 fprintf(stderr,
4453                                         "%s: the file specified by -f cannot be same as the source file '%s'\n",
4454                                         progname, fname);
4455                                 goto usage_error;
4456                         }
4457                         result = mirror_split(fname, comp_id, lsa.lsa_pool_name,
4458                                               mirror_flags,
4459                                               has_m_file ? mirror_list->m_file :
4460                                               NULL);
4461                 } else if (layout) {
4462                         result = lfs_component_create(fname, O_CREAT | O_WRONLY,
4463                                                       mode, layout);
4464                         if (result >= 0) {
4465                                 close(result);
4466                                 result = 0;
4467                         }
4468                 } else if (foreign_mode) {
4469                         result = llapi_file_create_foreign(fname, mode, type,
4470                                                            flags, xattr);
4471                         if (result >= 0) {
4472                                 close(result);
4473                                 result = 0;
4474                         }
4475                 } else {
4476                         result = llapi_file_open_param(fname,
4477                                                        O_CREAT | O_WRONLY,
4478                                                        mode, param);
4479                         if (result >= 0) {
4480                                 close(result);
4481                                 result = 0;
4482                         }
4483                 }
4484                 if (result) {
4485                         /* Save the first error encountered. */
4486                         if (result2 == 0)
4487                                 result2 = result;
4488                         continue;
4489                 }
4490         }
4491
4492         if (mode_opt)
4493                 umask(previous_umask);
4494
4495         free(param);
4496         free(migrate_mdt_param.fp_lmv_md);
4497         llapi_layout_free(layout);
4498         lfs_mirror_list_free(mirror_list);
4499         return result2;
4500 usage_error:
4501         result = CMD_HELP;
4502 error:
4503         llapi_layout_free(layout);
4504         lfs_mirror_list_free(mirror_list);
4505         return result;
4506 }
4507
4508 static int lfs_poollist(int argc, char **argv)
4509 {
4510         if (argc != 2)
4511                 return CMD_HELP;
4512
4513         return llapi_poollist(argv[1]);
4514 }
4515
4516 #define FP_DEFAULT_TIME_MARGIN (24 * 60 * 60)
4517 static time_t set_time(struct find_param *param, time_t *time, time_t *set,
4518                        char *str)
4519 {
4520         long long t = 0;
4521         int sign = 0;
4522         char *endptr = "AD";
4523         char *timebuf;
4524
4525         if (str[0] == '+')
4526                 sign = 1;
4527         else if (str[0] == '-')
4528                 sign = -1;
4529
4530         if (sign)
4531                 str++;
4532
4533         for (timebuf = str; *endptr && *(endptr + 1); timebuf = endptr + 1) {
4534                 long long val = strtoll(timebuf, &endptr, 0);
4535                 int unit = 1;
4536
4537                 switch (*endptr) {
4538                 case  'y':
4539                         unit *= 52; /* 52 weeks + 1 day below */
4540                 case  'w':      /* fallthrough */
4541                         unit *= 7;
4542                         if (param->fp_time_margin == FP_DEFAULT_TIME_MARGIN)
4543                                 param->fp_time_margin *= (1 + unit / 52);
4544                         unit += (*endptr == 'y'); /* +1 day for 365 days/year */
4545                 case '\0': /* days are default unit if none used */
4546                 case  'd':      /* fallthrough */
4547                         unit *= 24;
4548                 case  'h':      /* fallthrough */
4549                         unit *= 60;
4550                 case  'm':      /* fallthrough */
4551                         unit *= 60;
4552                 case  's':      /* fallthrough */
4553                         break;
4554                         /* don't need to multiply by 1 for seconds */
4555                 default:
4556                         fprintf(stderr,
4557                                 "%s find: bad time string '%s': %s\n",
4558                                 progname, timebuf, strerror(EINVAL));
4559                         return LONG_MAX;
4560                 }
4561
4562                 if (param->fp_time_margin == 0 ||
4563                     (*endptr && unit < param->fp_time_margin))
4564                         param->fp_time_margin = unit;
4565
4566                 t += val * unit;
4567         }
4568         if (*time < t) {
4569                 if (sign != 0)
4570                         str--;
4571                 fprintf(stderr, "%s find: bad time '%s': too large\n",
4572                         progname, str);
4573                 return LONG_MAX;
4574         }
4575
4576         *set = *time - t;
4577
4578         return sign;
4579 }
4580
4581 static int str2quotaid(__u32 *id, const char *arg)
4582 {
4583         unsigned long int projid_tmp = 0;
4584         char *endptr = NULL;
4585
4586         projid_tmp = strtoul(arg, &endptr, 10);
4587         if (*endptr != '\0')
4588                 return -EINVAL;
4589         /* UINT32_MAX is not allowed - see projid_valid()/INVALID_PROJID */
4590         if (projid_tmp >= UINT32_MAX)
4591                 return -ERANGE;
4592
4593         *id = projid_tmp;
4594         return 0;
4595 }
4596
4597 static int name2uid(unsigned int *id, const char *name)
4598 {
4599         struct passwd *passwd;
4600
4601         passwd = getpwnam(name);
4602         if (!passwd)
4603                 return -ENOENT;
4604         *id = passwd->pw_uid;
4605
4606         return 0;
4607 }
4608
4609 static int name2gid(unsigned int *id, const char *name)
4610 {
4611         struct group *group;
4612
4613         group = getgrnam(name);
4614         if (!group)
4615                 return -ENOENT;
4616         *id = group->gr_gid;
4617
4618         return 0;
4619 }
4620
4621 static inline int name2projid(unsigned int *id, const char *name)
4622 {
4623         return -ENOTSUP;
4624 }
4625
4626 static int uid2name(char **name, unsigned int id)
4627 {
4628         struct passwd *passwd;
4629
4630         passwd = getpwuid(id);
4631         if (!passwd)
4632                 return -ENOENT;
4633         *name = passwd->pw_name;
4634
4635         return 0;
4636 }
4637
4638 static inline int gid2name(char **name, unsigned int id)
4639 {
4640         struct group *group;
4641
4642         group = getgrgid(id);
4643         if (!group)
4644                 return -ENOENT;
4645         *name = group->gr_name;
4646
4647         return 0;
4648 }
4649
4650 static int name2layout(__u32 *layout, char *name)
4651 {
4652         char *ptr, *layout_name;
4653
4654         *layout = 0;
4655         for (ptr = name; ; ptr = NULL) {
4656                 layout_name = strtok(ptr, ",");
4657                 if (!layout_name)
4658                         break;
4659                 if (strcmp(layout_name, "released") == 0)
4660                         *layout |= LOV_PATTERN_F_RELEASED;
4661                 else if (strcmp(layout_name, "raid0") == 0)
4662                         *layout |= LOV_PATTERN_RAID0;
4663                 else if (strcmp(layout_name, "mdt") == 0)
4664                         *layout |= LOV_PATTERN_MDT;
4665                 else if (strcmp(layout_name, "overstriping") == 0)
4666                         *layout |= LOV_PATTERN_OVERSTRIPING;
4667                 else
4668                         return -1;
4669         }
4670         return 0;
4671 }
4672
4673 static int parse_symbolic(const char *input, mode_t *outmode, const char **end)
4674 {
4675         int loop;
4676         int user, group, other;
4677         int who, all;
4678         char c, op;
4679         mode_t perm;
4680         mode_t usermask;
4681         mode_t previous_flags;
4682
4683         user = group = other = 0;
4684         all = 0;
4685         loop = 1;
4686         perm = 0;
4687         previous_flags = 0;
4688         *end = input;
4689         usermask = 0;
4690
4691         while (loop) {
4692                 switch (*input) {
4693                 case 'u':
4694                         user = 1;
4695                         break;
4696                 case 'g':
4697                         group = 1;
4698                         break;
4699                 case 'o':
4700                         other = 1;
4701                         break;
4702                 case 'a':
4703                         user = group = other = 1;
4704                         all = 1;
4705                         break;
4706                 default:
4707                         loop = 0;
4708                 }
4709
4710                 if (loop)
4711                         input++;
4712         }
4713
4714         who = user || group || other;
4715         if (!who) {
4716                 /* get the umask */
4717                 usermask = umask(0022);
4718                 umask(usermask);
4719                 usermask &= 07777;
4720         }
4721
4722         if (*input == '-' || *input == '+' || *input == '=')
4723                 op = *input++;
4724         else
4725                 /* operation is required */
4726                 return -1;
4727
4728         /* get the flags in *outmode */
4729         switch (*input) {
4730         case 'u':
4731                 previous_flags = (*outmode & 0700);
4732                 perm |= user  ? previous_flags : 0;
4733                 perm |= group ? (previous_flags >> 3) : 0;
4734                 perm |= other ? (previous_flags >> 6) : 0;
4735                 input++;
4736                 goto write_perm;
4737         case 'g':
4738                 previous_flags = (*outmode & 0070);
4739                 perm |= user  ? (previous_flags << 3) : 0;
4740                 perm |= group ? previous_flags : 0;
4741                 perm |= other ? (previous_flags >> 3) : 0;
4742                 input++;
4743                 goto write_perm;
4744         case 'o':
4745                 previous_flags = (*outmode & 0007);
4746                 perm |= user  ? (previous_flags << 6) : 0;
4747                 perm |= group ? (previous_flags << 3) : 0;
4748                 perm |= other ? previous_flags : 0;
4749                 input++;
4750                 goto write_perm;
4751         default:
4752                 break;
4753         }
4754
4755         /* this part is optional,
4756          * if empty perm = 0 and *outmode is not modified
4757          */
4758         loop = 1;
4759         while (loop) {
4760                 c = *input;
4761                 switch (c) {
4762                 case 'r':
4763                         perm |= user  ? 0400 : 0;
4764                         perm |= group ? 0040 : 0;
4765                         perm |= other ? 0004 : 0;
4766                         /* set read permission for uog except for umask's
4767                          * permissions
4768                          */
4769                         perm |= who   ? 0 : (0444 & ~usermask);
4770                         break;
4771                 case 'w':
4772                         perm |= user  ? 0200 : 0;
4773                         perm |= group ? 0020 : 0;
4774                         perm |= other ? 0002 : 0;
4775                         /* set write permission for uog except for umask'
4776                          * permissions
4777                          */
4778                         perm |= who   ? 0 : (0222 & ~usermask);
4779                         break;
4780                 case 'x':
4781                         perm |= user  ? 0100 : 0;
4782                         perm |= group ? 0010 : 0;
4783                         perm |= other ? 0001 : 0;
4784                         /* set execute permission for uog except for umask'
4785                          * permissions
4786                          */
4787                         perm |= who   ? 0 : (0111 & ~usermask);
4788                         break;
4789                 case 'X':
4790                         /*
4791                          * Adds execute permission to 'u', 'g' and/or 'g' if
4792                          * specified and either 'u', 'g' or 'o' already has
4793                          * execute permissions.
4794                          */
4795                         if ((*outmode & 0111) != 0) {
4796                                 perm |= user  ? 0100 : 0;
4797                                 perm |= group ? 0010 : 0;
4798                                 perm |= other ? 0001 : 0;
4799                                 perm |= !who  ? 0111 : 0;
4800                         }
4801                         break;
4802                 case 's':
4803                         /* s is ignored if o is given, but it's not an error */
4804                         if (other && !group && !user)
4805                                 break;
4806                         perm |= user  ? S_ISUID : 0;
4807                         perm |= group ? S_ISGID : 0;
4808                         break;
4809                 case 't':
4810                         /* 't' should be used when 'a' is given
4811                          * or who is empty
4812                          */
4813                         perm |= (!who || all) ? S_ISVTX : 0;
4814                         /* using ugo with t is not an error */
4815                         break;
4816                 default:
4817                         loop = 0;
4818                         break;
4819                 }
4820                 if (loop)
4821                         input++;
4822         }
4823
4824 write_perm:
4825         /* uog flags should be only one character long */
4826         if (previous_flags && (*input != '\0' && *input != ','))
4827                 return -1;
4828
4829         switch (op) {
4830         case '-':
4831                 /* remove the flags from outmode */
4832                 *outmode &= ~perm;
4833                 break;
4834         case '+':
4835                 /* add the flags to outmode */
4836                 *outmode |= perm;
4837                 break;
4838         case '=':
4839                 /* set the flags of outmode to perm */
4840                 if (perm != 0)
4841                         *outmode = perm;
4842                 break;
4843         }
4844
4845         *end = input;
4846         return 0;
4847 }
4848
4849 static int str2mode_t(const char *input, mode_t *outmode)
4850 {
4851         int ret;
4852         const char *iter;
4853
4854         ret = 0;
4855
4856         if (*input >= '0' && *input <= '7') {
4857                 /* parse octal representation */
4858                 char *end;
4859
4860                 iter = input;
4861
4862                 /* look for invalid digits in octal representation */
4863                 while (isdigit(*iter))
4864                         if (*iter++ > '7')
4865                                 return -1;
4866
4867                 errno = 0;
4868                 *outmode = strtoul(input, &end, 8);
4869
4870                 if (errno != 0 || *outmode > 07777) {
4871                         *outmode = 0;
4872                         ret = -1;
4873                 }
4874
4875         } else if (*input == '8' || *input == '9') {
4876                 /* error: invalid octal number */
4877                 ret = -1;
4878         } else {
4879                 /* parse coma seperated list of symbolic representation */
4880                 int rc;
4881                 const char *end;
4882
4883                 *outmode = 0;
4884                 rc = 0;
4885                 end = NULL;
4886
4887                 do {
4888                         rc = parse_symbolic(input, outmode, &end);
4889                         if (rc)
4890                                 return -1;
4891
4892                         input = end+1;
4893                 } while (*end == ',');
4894
4895                 if (*end != '\0')
4896                         ret = -1;
4897         }
4898         return ret;
4899 }
4900
4901 static int lfs_find(int argc, char **argv)
4902 {
4903         int c, rc;
4904         int ret = 0;
4905         time_t t;
4906         struct find_param param = {
4907                 .fp_max_depth = -1,
4908                 .fp_quiet = 1,
4909                 .fp_time_margin = FP_DEFAULT_TIME_MARGIN,
4910         };
4911         struct option long_opts[] = {
4912         { .val = 'A',   .name = "atime",        .has_arg = required_argument },
4913         { .val = 'b',   .name = "blocks",       .has_arg = required_argument },
4914         { .val = 'B',   .name = "btime",        .has_arg = required_argument },
4915         { .val = 'B',   .name = "Btime",        .has_arg = required_argument },
4916         { .val = LFS_COMP_COUNT_OPT,
4917                         .name = "comp-count",   .has_arg = required_argument },
4918         { .val = LFS_COMP_COUNT_OPT,
4919                         .name = "component-count",
4920                                                 .has_arg = required_argument },
4921         { .val = LFS_COMP_FLAGS_OPT,
4922                         .name = "comp-flags",   .has_arg = required_argument },
4923         { .val = LFS_COMP_FLAGS_OPT,
4924                         .name = "component-flags",
4925                                                 .has_arg = required_argument },
4926         { .val = LFS_COMP_START_OPT,
4927                         .name = "comp-start",   .has_arg = required_argument },
4928         { .val = LFS_COMP_START_OPT,
4929                         .name = "component-start",
4930                                                 .has_arg = required_argument },
4931         { .val = LFS_MIRROR_STATE_OPT,
4932                         .name = "mirror-state", .has_arg = required_argument },
4933         { .val = LFS_NEWERXY_OPT,
4934                         .name = "newer",        .has_arg = required_argument},
4935         { .val = LFS_NEWERXY_OPT,
4936                         .name = "neweraa",      .has_arg = required_argument},
4937         { .val = LFS_NEWERXY_OPT,
4938                         .name = "neweram",      .has_arg = required_argument},
4939         { .val = LFS_NEWERXY_OPT,
4940                         .name = "newerac",      .has_arg = required_argument},
4941         { .val = LFS_NEWERXY_OPT,
4942                         .name = "newerab",      .has_arg = required_argument},
4943         { .val = LFS_NEWERXY_OPT,
4944                         .name = "newerma",      .has_arg = required_argument},
4945         { .val = LFS_NEWERXY_OPT,
4946                         .name = "newermm",      .has_arg = required_argument},
4947         { .val = LFS_NEWERXY_OPT,
4948                         .name = "newermc",      .has_arg = required_argument},
4949         { .val = LFS_NEWERXY_OPT,
4950                         .name = "newermb",      .has_arg = required_argument},
4951         { .val = LFS_NEWERXY_OPT,
4952                         .name = "newerca",      .has_arg = required_argument},
4953         { .val = LFS_NEWERXY_OPT,
4954                         .name = "newercm",      .has_arg = required_argument},
4955         { .val = LFS_NEWERXY_OPT,
4956                         .name = "newercc",      .has_arg = required_argument},
4957         { .val = LFS_NEWERXY_OPT,
4958                         .name = "newercb",      .has_arg = required_argument},
4959         { .val = LFS_NEWERXY_OPT,
4960                         .name = "newerba",      .has_arg = required_argument},
4961         { .val = LFS_NEWERXY_OPT,
4962                         .name = "newerbm",      .has_arg = required_argument},
4963         { .val = LFS_NEWERXY_OPT,
4964                         .name = "newerbc",      .has_arg = required_argument},
4965         { .val = LFS_NEWERXY_OPT,
4966                         .name = "newerbb",      .has_arg = required_argument},
4967         { .val = LFS_NEWERXY_OPT,
4968                         .name = "newerBa",      .has_arg = required_argument},
4969         { .val = LFS_NEWERXY_OPT,
4970                         .name = "newerBm",      .has_arg = required_argument},
4971         { .val = LFS_NEWERXY_OPT,
4972                         .name = "newerBc",      .has_arg = required_argument},
4973         { .val = LFS_NEWERXY_OPT,
4974                         .name = "newerBB",      .has_arg = required_argument},
4975         { .val = LFS_NEWERXY_OPT,
4976                         .name = "newerat",      .has_arg = required_argument},
4977         { .val = LFS_NEWERXY_OPT,
4978                         .name = "newermt",      .has_arg = required_argument},
4979         { .val = LFS_NEWERXY_OPT,
4980                         .name = "newerct",      .has_arg = required_argument},
4981         { .val = LFS_NEWERXY_OPT,
4982                         .name = "newerbt",      .has_arg = required_argument},
4983         { .val = LFS_NEWERXY_OPT,
4984                         .name = "newerBt",      .has_arg = required_argument},
4985         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument },
4986         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument },
4987         { .val = 'C',   .name = "ctime",        .has_arg = required_argument },
4988 /* getstripe { .val = 'd', .name = "directory", .has_arg = no_argument }, */
4989         { .val = 'D',   .name = "maxdepth",     .has_arg = required_argument },
4990         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument },
4991         { .val = 'E',   .name = "component-end",
4992                                                 .has_arg = required_argument },
4993 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
4994         { .val = LFS_LAYOUT_FOREIGN_OPT,
4995                         .name = "foreign",      .has_arg = optional_argument},
4996         { .val = 'g',   .name = "gid",          .has_arg = required_argument },
4997         { .val = 'G',   .name = "group",        .has_arg = required_argument },
4998         { .val = 'h',   .name = "help",         .has_arg = no_argument },
4999         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
5000         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument },
5001         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument },
5002 /* getstripe { .val = 'I', .name = "comp-id",   .has_arg = required_argument }*/
5003         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
5004         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
5005         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
5006         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
5007         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument },
5008         { .val = 'M',   .name = "mtime",        .has_arg = required_argument },
5009         { .val = 'n',   .name = "name",         .has_arg = required_argument },
5010         { .val = 'N',   .name = "mirror-count", .has_arg = required_argument },
5011 /* find { .val = 'o'    .name = "or", .has_arg = no_argument }, like find(1) */
5012         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
5013         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
5014         /* no short option for pool yet, can be 'p' after 2.18 */
5015         { .val = LFS_POOL_OPT,
5016                         .name = "pool",         .has_arg = required_argument },
5017         { .val = '0',   .name = "print0",       .has_arg = no_argument },
5018         { .val = 'P',   .name = "print",        .has_arg = no_argument },
5019         { .val = LFS_PROJID_OPT,
5020                         .name = "projid",       .has_arg = required_argument },
5021 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
5022 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
5023 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
5024         { .val = 's',   .name = "size",         .has_arg = required_argument },
5025         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
5026         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
5027         { .val = 't',   .name = "type",         .has_arg = required_argument },
5028         { .val = LFS_FIND_PERM,
5029                         .name = "perm",         .has_arg = required_argument },
5030         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
5031         { .val = 'u',   .name = "uid",          .has_arg = required_argument },
5032         { .val = 'U',   .name = "user",         .has_arg = required_argument },
5033         { .val = 'z',   .name = "extension-size",
5034                                                 .has_arg = required_argument },
5035         { .val = 'z',   .name = "ext-size",     .has_arg = required_argument },
5036 /* getstripe { .val = 'v', .name = "verbose",   .has_arg = no_argument }, */
5037 /* getstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
5038         { .name = NULL } };
5039         int optidx = 0;
5040         int pathstart = -1;
5041         int pathend = -1;
5042         int pathbad = -1;
5043         int neg_opt = 0;
5044         time_t *xtime;
5045         int *xsign;
5046         int isoption;
5047         char *endptr;
5048
5049         time(&t);
5050
5051         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
5052         while ((c = getopt_long_only(argc, argv,
5053                 "-0A:b:B:c:C:D:E:g:G:hH:i:L:m:M:n:N:O:Ppqrs:S:t:T:u:U:vz:",
5054                 long_opts, &optidx)) >= 0) {
5055                 xtime = NULL;
5056                 xsign = NULL;
5057                 if (neg_opt)
5058                         --neg_opt;
5059                 /* '!' is part of option */
5060                 /*
5061                  * when getopt_long_only() finds a string which is not
5062                  * an option nor a known option argument it returns 1
5063                  * in that case if we already have found pathstart and pathend
5064                  * (i.e. we have the list of pathnames),
5065                  * the only supported value is "!"
5066                  */
5067                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
5068                 if (!isoption && pathend != -1) {
5069                         fprintf(stderr,
5070                                 "err: %s: filename|dirname must either precede options or follow options\n",
5071                                 argv[0]);
5072                         ret = CMD_HELP;
5073                         goto err;
5074                 }
5075                 if (!isoption && pathstart == -1)
5076                         pathstart = optind - 1;
5077                 if (isoption && pathstart != -1 && pathend == -1)
5078                         pathend = optind - 2;
5079                 switch (c) {
5080                 case 0:
5081                         /* Long options. */
5082                         break;
5083                 case 1:
5084                         /*
5085                          * unknown; opt is "!" or path component,
5086                          * checking done above.
5087                          */
5088                         if (strcmp(optarg, "!") == 0)
5089                                 neg_opt = 2;
5090                         break;
5091                 case 'A':
5092                         xtime = &param.fp_atime;
5093                         xsign = &param.fp_asign;
5094                         param.fp_exclude_atime = !!neg_opt;
5095                         /* no break, this falls through to 'B' for btime */
5096                 case 'B':
5097                         if (c == 'B') {
5098                                 xtime = &param.fp_btime;
5099                                 xsign = &param.fp_bsign;
5100                                 param.fp_exclude_btime = !!neg_opt;
5101                         }
5102                         /* no break, this falls through to 'C' for ctime */
5103                 case 'C':
5104                         if (c == 'C') {
5105                                 xtime = &param.fp_ctime;
5106                                 xsign = &param.fp_csign;
5107                                 param.fp_exclude_ctime = !!neg_opt;
5108                         }
5109                         /* no break, this falls through to 'M' for mtime */
5110                 case 'M':
5111                         if (c == 'M') {
5112                                 xtime = &param.fp_mtime;
5113                                 xsign = &param.fp_msign;
5114                                 param.fp_exclude_mtime = !!neg_opt;
5115                         }
5116                         rc = set_time(&param, &t, xtime, optarg);
5117                         if (rc == LONG_MAX) {
5118                                 ret = -1;
5119                                 goto err;
5120                         }
5121                         if (rc)
5122                                 *xsign = rc;
5123                         break;
5124                 case 'b':
5125                         if (optarg[0] == '+') {
5126                                 param.fp_blocks_sign = -1;
5127                                 optarg++;
5128                         } else if (optarg[0] == '-') {
5129                                 param.fp_blocks_sign =  1;
5130                                 optarg++;
5131                         }
5132
5133                         param.fp_blocks_units = 1024;
5134                         ret = llapi_parse_size(optarg, &param.fp_blocks,
5135                                                &param.fp_blocks_units, 0);
5136                         if (ret) {
5137                                 fprintf(stderr, "error: bad blocks '%s'\n",
5138                                         optarg);
5139                                 goto err;
5140                         }
5141                         param.fp_check_blocks = 1;
5142                         param.fp_exclude_blocks = !!neg_opt;
5143                         break;
5144                 case LFS_COMP_COUNT_OPT:
5145                         if (optarg[0] == '+') {
5146                                 param.fp_comp_count_sign = -1;
5147                                 optarg++;
5148                         } else if (optarg[0] == '-') {
5149                                 param.fp_comp_count_sign =  1;
5150                                 optarg++;
5151                         }
5152
5153                         errno = 0;
5154                         param.fp_comp_count = strtoul(optarg, &endptr, 0);
5155                         if (errno != 0 || *endptr != '\0' ||
5156                             param.fp_comp_count > UINT32_MAX) {
5157                                 fprintf(stderr,
5158                                         "error: bad component count '%s'\n",
5159                                         optarg);
5160                                 goto err;
5161                         }
5162                         param.fp_check_comp_count = 1;
5163                         param.fp_exclude_comp_count = !!neg_opt;
5164                         break;
5165                 case LFS_COMP_FLAGS_OPT:
5166                         rc = comp_str2flags(optarg, &param.fp_comp_flags,
5167                                             &param.fp_comp_neg_flags);
5168                         if (rc) {
5169                                 fprintf(stderr,
5170                                         "error: bad component flags '%s'\n",
5171                                         optarg);
5172                                 goto err;
5173                         }
5174                         param.fp_check_comp_flags = 1;
5175                         if (neg_opt) {
5176                                 __u32 flags = param.fp_comp_neg_flags;
5177
5178                                 param.fp_comp_neg_flags = param.fp_comp_flags;
5179                                 param.fp_comp_flags = flags;
5180                         }
5181                         break;
5182                 case LFS_COMP_START_OPT:
5183                         if (optarg[0] == '+') {
5184                                 param.fp_comp_start_sign = -1;
5185                                 optarg++;
5186                         } else if (optarg[0] == '-') {
5187                                 param.fp_comp_start_sign =  1;
5188                                 optarg++;
5189                         }
5190
5191                         rc = llapi_parse_size(optarg, &param.fp_comp_start,
5192                                               &param.fp_comp_start_units, 0);
5193                         if (rc) {
5194                                 fprintf(stderr,
5195                                         "error: bad component start '%s'\n",
5196                                         optarg);
5197                                 goto err;
5198                         }
5199                         param.fp_check_comp_start = 1;
5200                         param.fp_exclude_comp_start = !!neg_opt;
5201                         break;
5202                 case LFS_MIRROR_STATE_OPT:
5203                         rc = mirror_str2state(optarg, &param.fp_mirror_state,
5204                                               &param.fp_mirror_neg_state);
5205                         if (rc) {
5206                                 fprintf(stderr,
5207                                         "error: bad mirrored file state '%s'\n",
5208                                         optarg);
5209                                 goto err;
5210                         }
5211                         param.fp_check_mirror_state = 1;
5212                         if (neg_opt) {
5213                                 __u16 state = param.fp_mirror_neg_state;
5214
5215                                 param.fp_mirror_neg_state =
5216                                         param.fp_mirror_state;
5217                                 param.fp_mirror_state = state;
5218                         }
5219                         break;
5220                 case 'c':
5221                         if (optarg[0] == '+') {
5222                                 param.fp_stripe_count_sign = -1;
5223                                 optarg++;
5224                         } else if (optarg[0] == '-') {
5225                                 param.fp_stripe_count_sign =  1;
5226                                 optarg++;
5227                         }
5228
5229                         errno = 0;
5230                         param.fp_stripe_count = strtoul(optarg, &endptr, 0);
5231                         if (errno != 0 || *endptr != '\0' ||
5232                             param.fp_stripe_count > LOV_MAX_STRIPE_COUNT) {
5233                                 fprintf(stderr,
5234                                         "error: bad stripe_count '%s'\n",
5235                                         optarg);
5236                                 ret = -1;
5237                                 goto err;
5238                         }
5239                         param.fp_check_stripe_count = 1;
5240                         param.fp_exclude_stripe_count = !!neg_opt;
5241                         break;
5242                 case 'D':
5243                         errno = 0;
5244                         param.fp_max_depth = strtol(optarg, 0, 0);
5245                         if (errno != 0 || param.fp_max_depth < 0) {
5246                                 fprintf(stderr,
5247                                         "error: bad maxdepth '%s'\n",
5248                                         optarg);
5249                                 ret = -1;
5250                                 goto err;
5251                         }
5252                         break;
5253                 case 'E':
5254                         if (optarg[0] == '+') {
5255                                 param.fp_comp_end_sign = -1;
5256                                 optarg++;
5257                         } else if (optarg[0] == '-') {
5258                                 param.fp_comp_end_sign =  1;
5259                                 optarg++;
5260                         }
5261
5262                         if (arg_is_eof(optarg)) {
5263                                 param.fp_comp_end = LUSTRE_EOF;
5264                                 param.fp_comp_end_units = 1;
5265                                 rc = 0;
5266                         } else {
5267                                 rc = llapi_parse_size(optarg,
5268                                                 &param.fp_comp_end,
5269                                                 &param.fp_comp_end_units, 0);
5270                                 /* assume units of KB if too small */
5271                                 if (param.fp_comp_end < 4096)
5272                                         param.fp_comp_end *= 1024;
5273                         }
5274                         if (rc) {
5275                                 fprintf(stderr,
5276                                         "error: bad component end '%s'\n",
5277                                         optarg);
5278                                 goto err;
5279                         }
5280                         param.fp_check_comp_end = 1;
5281                         param.fp_exclude_comp_end = !!neg_opt;
5282                         break;
5283                 case LFS_LAYOUT_FOREIGN_OPT: {
5284                         /* all types by default */
5285                         uint32_t type = LU_FOREIGN_TYPE_UNKNOWN;
5286
5287                         if (optarg) {
5288                                 /* check pure numeric */
5289                                 type = strtoul(optarg, &endptr, 0);
5290                                 if (*endptr) {
5291                                         /* check name */
5292                                         type = check_foreign_type_name(optarg);
5293                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
5294                                                 fprintf(stderr,
5295                                                         "%s %s: unknown foreign type '%s'\n",
5296                                                         progname, argv[0],
5297                                                         optarg);
5298                                                 return CMD_HELP;
5299                                         }
5300                                 } else if (type >= UINT32_MAX) {
5301                                         fprintf(stderr,
5302                                                 "%s %s: invalid foreign type '%s'\n",
5303                                                 progname, argv[0], optarg);
5304                                         return CMD_HELP;
5305                                 }
5306                         }
5307                         param.fp_foreign_type = type;
5308                         param.fp_check_foreign = 1;
5309                         param.fp_exclude_foreign = !!neg_opt;
5310                         break;
5311                 }
5312                 case LFS_NEWERXY_OPT: {
5313                         char x = 'm';
5314                         char y = 'm';
5315                         int xidx;
5316                         int negidx;
5317                         time_t *newery;
5318                         time_t ref = time(NULL);
5319
5320                         /* no need to check bad options, they won't get here */
5321                         if (strlen(long_opts[optidx].name) == 7) {
5322                                 x = long_opts[optidx].name[5];
5323                                 y = long_opts[optidx].name[6];
5324                         }
5325
5326                         if (y == 't') {
5327                                 static const char *const fmts[] = {
5328                                         "%Y-%m-%d %H:%M:%S",
5329                                         "%Y-%m-%d %H:%M",
5330                                         "%Y-%m-%d",
5331                                         "%H:%M:%S", /* sometime today */
5332                                         "%H:%M",
5333                                         "@%s",
5334                                         "%s",
5335                                         NULL };
5336                                 struct tm tm;
5337                                 bool found = false;
5338                                 int i;
5339
5340                                 for (i = 0; fmts[i] != NULL; i++) {
5341                                         char *ptr;
5342
5343                                         /* Init for times relative to today */
5344                                         if (strncmp(fmts[i], "%H", 2) == 0)
5345                                                 localtime_r(&ref, &tm);
5346                                         else
5347                                                 memset(&tm, 0, sizeof(tm));
5348                                         ptr = strptime(optarg, fmts[i], &tm);
5349                                         /* Skip spaces */
5350                                         while (ptr && isspace(*ptr))
5351                                                 ptr++;
5352                                         if (ptr == optarg + strlen(optarg)) {
5353                                                 found = true;
5354                                                 break;
5355                                         }
5356                                 }
5357
5358                                 if (!found) {
5359                                         fprintf(stderr,
5360                                                 "%s: invalid time '%s'\n",
5361                                                 progname, optarg);
5362                                         fprintf(stderr,
5363                                                 "supported formats are:\n  ");
5364                                         for (i = 0; fmts[i] != NULL; i++)
5365                                                 fprintf(stderr, "'%s', ",
5366                                                         fmts[i]);
5367                                         fprintf(stderr, "\n");
5368                                         ret = -EINVAL;
5369                                         goto err;
5370                                 }
5371
5372                                 ref = mktime(&tm);
5373                         } else if (y == 'b' || y == 'B') {
5374                                 lstatx_t stx;
5375
5376                                 rc = llapi_get_lum_file(optarg, NULL, &stx,
5377                                                         NULL, 0);
5378                                 if (rc || !(stx.stx_mask & STATX_BTIME)) {
5379                                         if (!(stx.stx_mask & STATX_BTIME))
5380                                                 ret = -EOPNOTSUPP;
5381                                         else
5382                                                 ret = -errno;
5383                                         fprintf(stderr,
5384                                                 "%s: get btime failed '%s': %s\n",
5385                                                 progname, optarg,
5386                                                 strerror(-ret));
5387                                         goto err;
5388                                 }
5389
5390                                 ref = stx.stx_btime.tv_sec;
5391                         } else {
5392                                 struct stat statbuf;
5393
5394                                 if (stat(optarg, &statbuf) < 0) {
5395                                         fprintf(stderr,
5396                                                 "%s: cannot stat file '%s': %s\n",
5397                                                 progname, optarg,
5398                                                 strerror(errno));
5399                                         ret = -errno;
5400                                         goto err;
5401                                 }
5402
5403                                 switch (y) {
5404                                 case 'a':
5405                                         ref = statbuf.st_atime;
5406                                         break;
5407                                 case 'm':
5408                                         ref = statbuf.st_mtime;
5409                                         break;
5410                                 case 'c':
5411                                         ref = statbuf.st_ctime;
5412                                         break;
5413                                 default:
5414                                         fprintf(stderr,
5415                                                 "%s: invalid Y argument: '%c'\n",
5416                                                 progname, x);
5417                                         ret = -EINVAL;
5418                                         goto err;
5419                                 }
5420                         }
5421
5422                         switch (x) {
5423                         case 'a':
5424                                 xidx = NEWERXY_ATIME;
5425                                 break;
5426                         case 'm':
5427                                 xidx = NEWERXY_MTIME;
5428                                 break;
5429                         case 'c':
5430                                 xidx = NEWERXY_CTIME;
5431                                 break;
5432                         case 'b':
5433                         case 'B':
5434                                 xidx = NEWERXY_BTIME;
5435                                 break;
5436                         default:
5437                                 fprintf(stderr,
5438                                         "%s: invalid X argument: '%c'\n",
5439                                         progname, x);
5440                                 ret = -EINVAL;
5441                                 goto err;
5442                         }
5443
5444                         negidx = !!neg_opt;
5445                         newery = &param.fp_newery[xidx][negidx];
5446
5447                         if (*newery == 0) {
5448                                 *newery = ref;
5449                         } else {
5450                                 if (negidx)
5451                                         *newery = *newery > ref ? ref : *newery;
5452                                 else
5453                                         *newery = *newery > ref ? *newery : ref;
5454                         }
5455                         param.fp_newerxy = 1;
5456                         break;
5457                 }
5458                 case 'g':
5459                 case 'G':
5460                         rc = name2gid(&param.fp_gid, optarg);
5461                         if (rc) {
5462                                 if (str2quotaid(&param.fp_gid, optarg)) {
5463                                         fprintf(stderr,
5464                                                 "Group/GID: %s cannot be found.\n",
5465                                                 optarg);
5466                                         ret = -1;
5467                                         goto err;
5468                                 }
5469                         }
5470                         param.fp_exclude_gid = !!neg_opt;
5471                         param.fp_check_gid = 1;
5472                         break;
5473                 case 'H':
5474                         rc = mdthash_input(optarg, &param.fp_hash_inflags,
5475                                            &param.fp_hash_exflags,
5476                                            &param.fp_hash_type);
5477                         if (rc) {
5478                                 ret = -1;
5479                                 goto err;
5480                         }
5481                         if (param.fp_hash_inflags || param.fp_hash_exflags)
5482                                 param.fp_check_hash_flag = 1;
5483                         param.fp_exclude_hash_type = !!neg_opt;
5484                         break;
5485                 case 'l':
5486                         param.fp_lazy = 1;
5487                         break;
5488                 case 'L':
5489                         ret = name2layout(&param.fp_layout, optarg);
5490                         if (ret)
5491                                 goto err;
5492                         param.fp_exclude_layout = !!neg_opt;
5493                         param.fp_check_layout = 1;
5494                         break;
5495                 case 'u':
5496                 case 'U':
5497                         rc = name2uid(&param.fp_uid, optarg);
5498                         if (rc) {
5499                                 if (str2quotaid(&param.fp_uid, optarg)) {
5500                                         fprintf(stderr,
5501                                                 "User/UID: %s cannot be found.\n",
5502                                                 optarg);
5503                                         ret = -1;
5504                                         goto err;
5505                                 }
5506                         }
5507                         param.fp_exclude_uid = !!neg_opt;
5508                         param.fp_check_uid = 1;
5509                         break;
5510                 case 'n':
5511                         param.fp_pattern = (char *)optarg;
5512                         param.fp_exclude_pattern = !!neg_opt;
5513                         break;
5514                 case 'N':
5515                         if (optarg[0] == '+') {
5516                                 param.fp_mirror_count_sign = -1;
5517                                 optarg++;
5518                         } else if (optarg[0] == '-') {
5519                                 param.fp_mirror_count_sign =  1;
5520                                 optarg++;
5521                         }
5522
5523                         errno = 0;
5524                         param.fp_mirror_count = strtoul(optarg, &endptr, 0);
5525                         if (errno != 0 || *endptr != '\0' ||
5526                             param.fp_mirror_count > LUSTRE_MIRROR_COUNT_MAX) {
5527                                 fprintf(stderr,
5528                                         "error: bad mirror count '%s'\n",
5529                                         optarg);
5530                                 goto err;
5531                         }
5532                         param.fp_check_mirror_count = 1;
5533                         param.fp_exclude_mirror_count = !!neg_opt;
5534                         break;
5535                 case 'm':
5536                 case 'i':
5537                 case 'O': {
5538                         char *buf, *token, *next, *p;
5539                         int len = 1;
5540                         void *tmp;
5541
5542                         buf = strdup(optarg);
5543                         if (!buf) {
5544                                 ret = -ENOMEM;
5545                                 goto err;
5546                         }
5547
5548                         param.fp_exclude_obd = !!neg_opt;
5549
5550                         token = buf;
5551                         while (token && *token) {
5552                                 token = strchr(token, ',');
5553                                 if (token) {
5554                                         len++;
5555                                         token++;
5556                                 }
5557                         }
5558                         if (c == 'm') {
5559                                 param.fp_exclude_mdt = !!neg_opt;
5560                                 param.fp_num_alloc_mdts += len;
5561                                 tmp = realloc(param.fp_mdt_uuid,
5562                                               param.fp_num_alloc_mdts *
5563                                               sizeof(*param.fp_mdt_uuid));
5564                                 if (!tmp) {
5565                                         ret = -ENOMEM;
5566                                         goto err_free;
5567                                 }
5568
5569                                 param.fp_mdt_uuid = tmp;
5570                         } else {
5571                                 param.fp_exclude_obd = !!neg_opt;
5572                                 param.fp_num_alloc_obds += len;
5573                                 tmp = realloc(param.fp_obd_uuid,
5574                                               param.fp_num_alloc_obds *
5575                                               sizeof(*param.fp_obd_uuid));
5576                                 if (!tmp) {
5577                                         ret = -ENOMEM;
5578                                         goto err_free;
5579                                 }
5580
5581                                 param.fp_obd_uuid = tmp;
5582                         }
5583                         for (token = buf; token && *token; token = next) {
5584                                 struct obd_uuid *puuid;
5585
5586                                 if (c == 'm') {
5587                                         puuid =
5588                                         &param.fp_mdt_uuid[param.fp_num_mdts++];
5589                                 } else {
5590                                         puuid =
5591                                         &param.fp_obd_uuid[param.fp_num_obds++];
5592                                 }
5593                                 p = strchr(token, ',');
5594                                 next = 0;
5595                                 if (p) {
5596                                         *p = 0;
5597                                         next = p+1;
5598                                 }
5599
5600                                 if (strlen(token) > sizeof(puuid->uuid) - 1) {
5601                                         ret = -E2BIG;
5602                                         goto err_free;
5603                                 }
5604
5605                                 strncpy(puuid->uuid, token,
5606                                         sizeof(puuid->uuid));
5607                         }
5608 err_free:
5609                         if (buf)
5610                                 free(buf);
5611                         break;
5612                 }
5613 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 18, 53, 0)
5614                 case 'p':
5615 #endif
5616                 case LFS_POOL_OPT:
5617                         if (strlen(optarg) > LOV_MAXPOOLNAME) {
5618                                 fprintf(stderr,
5619                                         "Pool name %s is too long (max %d)\n",
5620                                         optarg, LOV_MAXPOOLNAME);
5621                                 ret = -1;
5622                                 goto err;
5623                         }
5624                         /*
5625                          * We do check for empty pool because empty pool
5626                          * is used to find V1 LOV attributes
5627                          */
5628                         strncpy(param.fp_poolname, optarg, LOV_MAXPOOLNAME);
5629                         param.fp_poolname[LOV_MAXPOOLNAME] = '\0';
5630                         param.fp_exclude_pool = !!neg_opt;
5631                         param.fp_check_pool = 1;
5632                         break;
5633 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 14, 53, 0)
5634                 case 'p': /* want this for --pool, to match getstripe/find */
5635                         fprintf(stderr,
5636                                 "warning: -p deprecated, use --print0 or -0\n");
5637 #endif
5638                 case '0':
5639                         param.fp_zero_end = 1;
5640                         break;
5641                 case 'P': /* we always print, this option is a no-op */
5642                         break;
5643                 case LFS_PROJID_OPT:
5644                         rc = name2projid(&param.fp_projid, optarg);
5645                         if (rc) {
5646                                 if (str2quotaid(&param.fp_projid, optarg)) {
5647                                         fprintf(stderr,
5648                                                 "Invalid project ID: %s\n",
5649                                                 optarg);
5650                                         ret = -1;
5651                                         goto err;
5652                                 }
5653                         }
5654                         param.fp_exclude_projid = !!neg_opt;
5655                         param.fp_check_projid = 1;
5656                         break;
5657                 case 's':
5658                         if (optarg[0] == '+') {
5659                                 param.fp_size_sign = -1;
5660                                 optarg++;
5661                         } else if (optarg[0] == '-') {
5662                                 param.fp_size_sign =  1;
5663                                 optarg++;
5664                         }
5665
5666                         ret = llapi_parse_size(optarg, &param.fp_size,
5667                                                &param.fp_size_units, 0);
5668                         if (ret) {
5669                                 fprintf(stderr, "error: bad file size '%s'\n",
5670                                         optarg);
5671                                 goto err;
5672                         }
5673                         param.fp_check_size = 1;
5674                         param.fp_exclude_size = !!neg_opt;
5675                         break;
5676                 case 'S':
5677                         if (optarg[0] == '+') {
5678                                 param.fp_stripe_size_sign = -1;
5679                                 optarg++;
5680                         } else if (optarg[0] == '-') {
5681                                 param.fp_stripe_size_sign =  1;
5682                                 optarg++;
5683                         }
5684
5685                         ret = llapi_parse_size(optarg, &param.fp_stripe_size,
5686                                                &param.fp_stripe_size_units, 0);
5687                         /* assume units of KB if too small to be valid */
5688                         if (param.fp_stripe_size < 4096)
5689                                 param.fp_stripe_size *= 1024;
5690                         if (ret) {
5691                                 fprintf(stderr, "error: bad stripe_size '%s'\n",
5692                                         optarg);
5693                                 goto err;
5694                         }
5695                         param.fp_check_stripe_size = 1;
5696                         param.fp_exclude_stripe_size = !!neg_opt;
5697                         break;
5698                 case 't':
5699                         param.fp_exclude_type = !!neg_opt;
5700                         switch (optarg[0]) {
5701                         case 'b':
5702                                 param.fp_type = S_IFBLK;
5703                                 break;
5704                         case 'c':
5705                                 param.fp_type = S_IFCHR;
5706                                 break;
5707                         case 'd':
5708                                 param.fp_type = S_IFDIR;
5709                                 break;
5710                         case 'f':
5711                                 param.fp_type = S_IFREG;
5712                                 break;
5713                         case 'l':
5714                                 param.fp_type = S_IFLNK;
5715                                 break;
5716                         case 'p':
5717                                 param.fp_type = S_IFIFO;
5718                                 break;
5719                         case 's':
5720                                 param.fp_type = S_IFSOCK;
5721                                 break;
5722                         default:
5723                                 fprintf(stderr, "%s: bad type '%s'\n",
5724                                         progname, optarg);
5725                                 ret = CMD_HELP;
5726                                 goto err;
5727                         }
5728                         break;
5729                 case LFS_FIND_PERM:
5730                         param.fp_exclude_perm = !!neg_opt;
5731                         param.fp_perm_sign = LFS_FIND_PERM_EXACT;
5732                         if (*optarg == '/') {
5733                                 param.fp_perm_sign = LFS_FIND_PERM_ANY;
5734                                 optarg++;
5735                         } else if (*optarg == '-') {
5736                                 param.fp_perm_sign = LFS_FIND_PERM_ALL;
5737                                 optarg++;
5738                         }
5739
5740                         if (str2mode_t(optarg, &param.fp_perm)) {
5741                                 fprintf(stderr, "error: invalid mode '%s'\n",
5742                                         optarg);
5743                                 ret = -1;
5744                                 goto err;
5745                         }
5746                         break;
5747                 case 'T':
5748                         if (optarg[0] == '+') {
5749                                 param.fp_mdt_count_sign = -1;
5750                                 optarg++;
5751                         } else if (optarg[0] == '-') {
5752                                 param.fp_mdt_count_sign =  1;
5753                                 optarg++;
5754                         }
5755
5756                         errno = 0;
5757                         param.fp_mdt_count = strtoul(optarg, &endptr, 0);
5758                         if (errno != 0 || *endptr != '\0' ||
5759                             param.fp_mdt_count >= UINT32_MAX) {
5760                                 fprintf(stderr, "error: bad mdt_count '%s'\n",
5761                                         optarg);
5762                                 ret = -1;
5763                                 goto err;
5764                         }
5765                         param.fp_check_mdt_count = 1;
5766                         param.fp_exclude_mdt_count = !!neg_opt;
5767                         break;
5768                 case 'z':
5769                         if (optarg[0] == '+') {
5770                                 param.fp_ext_size_sign = -1;
5771                                 optarg++;
5772                         } else if (optarg[0] == '-') {
5773                                 param.fp_ext_size_sign =  1;
5774                                 optarg++;
5775                         }
5776
5777                         ret = llapi_parse_size(optarg, &param.fp_ext_size,
5778                                                &param.fp_ext_size_units, 0);
5779                         if (ret) {
5780                                 fprintf(stderr, "error: bad ext-size '%s'\n",
5781                                         optarg);
5782                                 goto err;
5783                         }
5784                         param.fp_ext_size /= SEL_UNIT_SIZE;
5785                         param.fp_ext_size_units /= SEL_UNIT_SIZE;
5786                         param.fp_check_ext_size = 1;
5787                         param.fp_exclude_ext_size = !!neg_opt;
5788                         break;
5789                 default:
5790                         fprintf(stderr, "%s: unrecognized option '%s'\n",
5791                                 progname, argv[optind - 1]);
5792                 case 'h':
5793                         ret = CMD_HELP;
5794                         goto err;
5795                 }
5796         }
5797
5798         if (pathstart == -1) {
5799                 fprintf(stderr, "error: %s: no filename|pathname\n",
5800                         argv[0]);
5801                 ret = CMD_HELP;
5802                 goto err;
5803         } else if (pathend == -1) {
5804                 /* no options */
5805                 pathend = argc;
5806         }
5807
5808         do {
5809                 rc = llapi_find(argv[pathstart], &param);
5810                 if (rc && !ret) {
5811                         ret = rc;
5812                         pathbad = pathstart;
5813                 }
5814         } while (++pathstart < pathend);
5815
5816         if (ret)
5817                 fprintf(stderr, "%s: failed for '%s': %s\n",
5818                         progname, argv[pathbad], strerror(-rc));
5819
5820 err:
5821         if (param.fp_obd_uuid && param.fp_num_alloc_obds)
5822                 free(param.fp_obd_uuid);
5823
5824         if (param.fp_mdt_uuid && param.fp_num_alloc_mdts)
5825                 free(param.fp_mdt_uuid);
5826
5827         return ret;
5828 }
5829
5830 static int lfs_getstripe_internal(int argc, char **argv,
5831                                   struct find_param *param)
5832 {
5833         struct option long_opts[] = {
5834 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
5835 /* find { .val = 'b',   .name = "blocks",       .has_arg = required_argument }*/
5836 /* find { .val = 'B',   .name = "btime",        .has_arg = required_argument }*/
5837 /* find { .val = 'B',   .name = "Btime",        .has_arg = required_argument }*/
5838         { .val = LFS_COMP_COUNT_OPT,
5839                         .name = "comp-count",   .has_arg = no_argument },
5840         { .val = LFS_COMP_COUNT_OPT,
5841                 .name = "component-count",      .has_arg = no_argument },
5842         { .val = LFS_COMP_FLAGS_OPT,
5843                         .name = "comp-flags",   .has_arg = optional_argument },
5844         { .val = LFS_COMP_FLAGS_OPT,
5845                 .name = "component-flags",      .has_arg = optional_argument },
5846         { .val = LFS_COMP_START_OPT,
5847                         .name = "comp-start",   .has_arg = optional_argument },
5848         { .val = LFS_COMP_START_OPT,
5849                 .name = "component-start",      .has_arg = optional_argument },
5850         { .val = LFS_MIRROR_INDEX_OPT,
5851                 .name = "mirror-index",         .has_arg = required_argument },
5852         { .val = LFS_MIRROR_ID_OPT,
5853                 .name = "mirror-id",            .has_arg = required_argument },
5854         { .val = 'c',   .name = "stripe-count", .has_arg = no_argument },
5855         { .val = 'c',   .name = "stripe_count", .has_arg = no_argument },
5856 /* find { .val = 'C',   .name = "ctime",        .has_arg = required_argument }*/
5857         { .val = 'd',   .name = "directory",    .has_arg = no_argument },
5858         { .val = 'D',   .name = "default",      .has_arg = no_argument },
5859         { .val = 'E',   .name = "comp-end",     .has_arg = optional_argument },
5860         { .val = 'E',   .name = "component-end", .has_arg = optional_argument },
5861         { .val = 'F',   .name = "fid",          .has_arg = no_argument },
5862         { .val = 'g',   .name = "generation",   .has_arg = no_argument },
5863 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
5864         { .val = 'h',   .name = "help",         .has_arg = no_argument },
5865 /* dirstripe { .val = 'H', .name = "mdt-hash",  .has_arg = required_argument }*/
5866         { .val = 'i',   .name = "stripe-index", .has_arg = no_argument },
5867         { .val = 'i',   .name = "stripe_index", .has_arg = no_argument },
5868         { .val = 'I',   .name = "comp-id",      .has_arg = optional_argument },
5869         { .val = 'I',   .name = "component-id", .has_arg = optional_argument },
5870 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
5871         { .val = 'L',   .name = "layout",       .has_arg = no_argument },
5872         { .val = 'm',   .name = "mdt",          .has_arg = no_argument },
5873         { .val = 'm',   .name = "mdt-index",    .has_arg = no_argument },
5874         { .val = 'm',   .name = "mdt_index",    .has_arg = no_argument },
5875 /* find { .val = 'M',   .name = "mtime",        .has_arg = required_argument }*/
5876 /* find { .val = 'n',   .name = "name",         .has_arg = required_argument }*/
5877         { .val = 'N',   .name = "mirror-count", .has_arg = no_argument },
5878         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
5879         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
5880         { .val = 'p',   .name = "pool",         .has_arg = no_argument },
5881 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
5882         { .val = 'q',   .name = "quiet",        .has_arg = no_argument },
5883         { .val = 'r',   .name = "recursive",    .has_arg = no_argument },
5884         { .val = 'R',   .name = "raw",          .has_arg = no_argument },
5885         { .val = 'S',   .name = "stripe-size",  .has_arg = no_argument },
5886         { .val = 'S',   .name = "stripe_size",  .has_arg = no_argument },
5887 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
5888 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
5889 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
5890 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
5891         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
5892 /* dirstripe { .val = 'X',.name = "max-inherit",.has_arg = required_argument }*/
5893         { .val = 'y',   .name = "yaml",         .has_arg = no_argument },
5894         { .val = 'z',   .name = "extension-size", .has_arg = no_argument },
5895         { .val = 'z',   .name = "ext-size",     .has_arg = no_argument },
5896         { .name = NULL } };
5897         int c, rc;
5898         int neg_opt = 0;
5899         int pathstart = -1, pathend = -1;
5900         int isoption;
5901         char *end, *tmp;
5902
5903         while ((c = getopt_long(argc, argv,
5904                         "-cdDE::FghiI::LmMNoO:pqrRsSvyz",
5905                         long_opts, NULL)) != -1) {
5906                 if (neg_opt)
5907                         --neg_opt;
5908
5909                 /* '!' is part of option */
5910                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
5911                 if (!isoption && pathend != -1) {
5912                         fprintf(stderr,
5913                                 "error: %s: filename|dirname must either precede options or follow options\n",
5914                                 argv[0]);
5915                         return CMD_HELP;
5916                 }
5917                 if (!isoption && pathstart == -1)
5918                         pathstart = optind - 1;
5919                 if (isoption && pathstart != -1 && pathend == -1)
5920                         pathend = optind - 2;
5921
5922                 switch (c) {
5923                 case 1:
5924                         /* unknown: opt is "!" */
5925                         if (strcmp(optarg, "!") == 0)
5926                                 neg_opt = 2;
5927                         break;
5928                 case 'c':
5929                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
5930                                 param->fp_verbose |= VERBOSE_COUNT;
5931                                 param->fp_max_depth = 0;
5932                         }
5933                         break;
5934                 case LFS_COMP_COUNT_OPT:
5935                         param->fp_verbose |= VERBOSE_COMP_COUNT;
5936                         param->fp_max_depth = 0;
5937                         break;
5938                 case LFS_COMP_FLAGS_OPT:
5939                         if (optarg) {
5940                                 rc = comp_str2flags(optarg,
5941                                                     &param->fp_comp_flags,
5942                                                     &param->fp_comp_neg_flags);
5943                                 if (rc != 0) {
5944                                         fprintf(stderr,
5945                                                 "error: %s bad component flags '%s'.\n",
5946                                                 argv[0], optarg);
5947                                         return CMD_HELP;
5948                                 }
5949                                 param->fp_check_comp_flags = 1;
5950                         } else {
5951                                 param->fp_verbose |= VERBOSE_COMP_FLAGS;
5952                                 param->fp_max_depth = 0;
5953                         }
5954                         break;
5955                 case LFS_COMP_START_OPT:
5956                         if (optarg) {
5957                                 tmp = optarg;
5958                                 if (tmp[0] == '+') {
5959                                         param->fp_comp_start_sign = -1;
5960                                         tmp++;
5961                                 } else if (tmp[0] == '-') {
5962                                         param->fp_comp_start_sign = 1;
5963                                         tmp++;
5964                                 }
5965                                 rc = llapi_parse_size(tmp,
5966                                                 &param->fp_comp_start,
5967                                                 &param->fp_comp_start_units, 0);
5968                                 if (rc != 0) {
5969                                         fprintf(stderr,
5970                                                 "error: %s bad component start '%s'.\n",
5971                                                 argv[0], tmp);
5972                                         return CMD_HELP;
5973                                 }
5974                                 param->fp_check_comp_start = 1;
5975                         } else {
5976                                 param->fp_verbose |= VERBOSE_COMP_START;
5977                                 param->fp_max_depth = 0;
5978                         }
5979                         break;
5980                 case LFS_MIRROR_INDEX_OPT: {
5981                         unsigned long int mirror_index;
5982
5983                         if (optarg[0] == '+') {
5984                                 param->fp_mirror_index_sign = -1;
5985                                 optarg++;
5986                         } else if (optarg[0] == '-') {
5987                                 param->fp_mirror_index_sign = 1;
5988                                 optarg++;
5989                         }
5990
5991                         errno = 0;
5992                         mirror_index = strtoul(optarg, &end, 0);
5993                         if (errno != 0 || *end != '\0' ||
5994                             mirror_index > UINT16_MAX || (mirror_index == 0 &&
5995                             param->fp_mirror_index_sign == 0 && neg_opt == 0)) {
5996                                 fprintf(stderr,
5997                                         "%s %s: invalid mirror index '%s'\n",
5998                                         progname, argv[0], optarg);
5999                                 return CMD_HELP;
6000                         }
6001
6002                         param->fp_mirror_index = (__u16)mirror_index;
6003
6004                         if (param->fp_mirror_id != 0) {
6005                                 fprintf(stderr,
6006                                         "%s %s: can't specify both mirror index and mirror ID\n",
6007                                         progname, argv[0]);
6008                                 return CMD_HELP;
6009                         }
6010                         param->fp_check_mirror_index = 1;
6011                         param->fp_exclude_mirror_index = !!neg_opt;
6012                         break;
6013                 }
6014                 case LFS_MIRROR_ID_OPT: {
6015                         unsigned long int mirror_id;
6016
6017                         if (optarg[0] == '+') {
6018                                 param->fp_mirror_id_sign = -1;
6019                                 optarg++;
6020                         } else if (optarg[0] == '-') {
6021                                 param->fp_mirror_id_sign = 1;
6022                                 optarg++;
6023                         }
6024
6025                         errno = 0;
6026                         mirror_id = strtoul(optarg, &end, 0);
6027                         if (errno != 0 || *end != '\0' ||
6028                             mirror_id > UINT16_MAX || (mirror_id == 0 &&
6029                             param->fp_mirror_id_sign == 0 && neg_opt == 0)) {
6030                                 fprintf(stderr,
6031                                         "%s %s: invalid mirror ID '%s'\n",
6032                                         progname, argv[0], optarg);
6033                                 return CMD_HELP;
6034                         }
6035
6036                         param->fp_mirror_id = (__u16)mirror_id;
6037
6038                         if (param->fp_mirror_index != 0) {
6039                                 fprintf(stderr,
6040                                         "%s %s: can't specify both mirror index and mirror ID\n",
6041                                         progname, argv[0]);
6042                                 return CMD_HELP;
6043                         }
6044                         param->fp_check_mirror_id = 1;
6045                         param->fp_exclude_mirror_id = !!neg_opt;
6046                         break;
6047                 }
6048                 case 'd':
6049                         param->fp_max_depth = 0;
6050                         break;
6051                 case 'D':
6052                         param->fp_get_default_lmv = 1;
6053                         break;
6054                 case 'E':
6055                         if (optarg) {
6056                                 tmp = optarg;
6057                                 if (tmp[0] == '+') {
6058                                         param->fp_comp_end_sign = -1;
6059                                         tmp++;
6060                                 } else if (tmp[0] == '-') {
6061                                         param->fp_comp_end_sign = 1;
6062                                         tmp++;
6063                                 }
6064
6065                                 if (arg_is_eof(tmp)) {
6066                                         param->fp_comp_end = LUSTRE_EOF;
6067                                         param->fp_comp_end_units = 1;
6068                                         rc = 0;
6069                                 } else {
6070                                         rc = llapi_parse_size(tmp,
6071                                                 &param->fp_comp_end,
6072                                                 &param->fp_comp_end_units, 0);
6073                                         /* assume units of KB if too small */
6074                                         if (param->fp_comp_end < 4096)
6075                                                 param->fp_comp_end *= 1024;
6076                                 }
6077                                 if (rc != 0) {
6078                                         fprintf(stderr,
6079                                                 "error: %s bad component end '%s'.\n",
6080                                                 argv[0], tmp);
6081                                         return CMD_HELP;
6082                                 }
6083                                 param->fp_check_comp_end = 1;
6084                         } else {
6085                                 param->fp_verbose |= VERBOSE_COMP_END;
6086                                 param->fp_max_depth = 0;
6087                         }
6088                         break;
6089                 case 'F':
6090                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6091                                 param->fp_verbose |= VERBOSE_DFID;
6092                                 param->fp_max_depth = 0;
6093                         }
6094                         break;
6095                 case 'g':
6096                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6097                                 param->fp_verbose |= VERBOSE_GENERATION;
6098                                 param->fp_max_depth = 0;
6099                         }
6100                         break;
6101                 case 'i':
6102                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6103                                 param->fp_verbose |= VERBOSE_STRIPE_OFFSET;
6104                                 param->fp_max_depth = 0;
6105                         }
6106                         break;
6107                 case 'I':
6108                         if (optarg) {
6109                                 param->fp_comp_id = strtoul(optarg, &end, 0);
6110                                 if (*end != '\0' || param->fp_comp_id == 0 ||
6111                                     param->fp_comp_id > LCME_ID_MAX) {
6112                                         fprintf(stderr,
6113                                                 "error: %s bad component id '%s'\n",
6114                                                 argv[0], optarg);
6115                                         return CMD_HELP;
6116                                 }
6117                                 param->fp_check_comp_id = 1;
6118                         } else {
6119                                 param->fp_max_depth = 0;
6120                                 param->fp_verbose |= VERBOSE_COMP_ID;
6121                         }
6122                         break;
6123                 case 'L':
6124                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6125                                 param->fp_verbose |= VERBOSE_PATTERN;
6126                                 param->fp_max_depth = 0;
6127                         }
6128                         break;
6129 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6130                 case 'M':
6131                         fprintf(stderr,
6132                                 "warning: '-M' deprecated, use '--mdt-index' or '-m' instead\n");
6133 #endif
6134                 case 'm':
6135                         if (!(param->fp_verbose & VERBOSE_DETAIL))
6136                                 param->fp_max_depth = 0;
6137                         param->fp_verbose |= VERBOSE_MDTINDEX;
6138                         break;
6139                 case 'N':
6140                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6141                                 param->fp_verbose |= VERBOSE_MIRROR_COUNT;
6142                                 param->fp_max_depth = 0;
6143                         }
6144                         break;
6145                 case 'O':
6146                         if (param->fp_obd_uuid) {
6147                                 fprintf(stderr,
6148                                         "error: %s: only one obduuid allowed",
6149                                         argv[0]);
6150                                 return CMD_HELP;
6151                         }
6152                         param->fp_obd_uuid = (struct obd_uuid *)optarg;
6153                         break;
6154                 case 'p':
6155                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6156                                 param->fp_verbose |= VERBOSE_POOL;
6157                                 param->fp_max_depth = 0;
6158                         }
6159                         break;
6160                 case 'q':
6161                         param->fp_quiet++;
6162                         break;
6163                 case 'r':
6164                         param->fp_recursive = 1;
6165                         break;
6166                 case 'R':
6167                         param->fp_raw = 1;
6168                         break;
6169                 case 'S':
6170                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6171                                 param->fp_verbose |= VERBOSE_STRIPE_SIZE;
6172                                 param->fp_max_depth = 0;
6173                         }
6174                         break;
6175                 case 'v':
6176                         param->fp_verbose = VERBOSE_DEFAULT | VERBOSE_DETAIL;
6177                         break;
6178                 case 'y':
6179                         param->fp_yaml = 1;
6180                         break;
6181                 case 'z':
6182                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6183                                 param->fp_verbose |= VERBOSE_EXT_SIZE;
6184                                 param->fp_max_depth = 0;
6185                         }
6186                         break;
6187                 default:
6188                         fprintf(stderr, "%s: unrecognized option '%s'\n",
6189                                 progname, argv[optind - 1]);
6190                 case 'h':
6191                         return CMD_HELP;
6192                 }
6193         }
6194
6195         if (pathstart == -1) {
6196                 fprintf(stderr, "error: %s: no filename|pathname\n",
6197                                 argv[0]);
6198                 return CMD_HELP;
6199         } else if (pathend == -1) {
6200                 /* no options */
6201                 pathend = argc;
6202         }
6203
6204         if (pathend > argc)
6205                 return CMD_HELP;
6206
6207         if (param->fp_recursive)
6208                 param->fp_max_depth = -1;
6209         else if (param->fp_verbose & VERBOSE_DETAIL)
6210                 param->fp_max_depth = 1;
6211
6212         if (!param->fp_verbose)
6213                 param->fp_verbose = VERBOSE_DEFAULT;
6214         if (param->fp_quiet)
6215                 param->fp_verbose = VERBOSE_OBJID;
6216
6217         do {
6218                 rc = llapi_getstripe(argv[pathstart], param);
6219         } while (++pathstart < pathend && !rc);
6220
6221         if (rc)
6222                 fprintf(stderr, "error: %s failed for %s.\n",
6223                         argv[0], argv[optind - 1]);
6224         return rc;
6225 }
6226
6227 static int lfs_tgts(int argc, char **argv)
6228 {
6229         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
6230         struct find_param param;
6231         int index = 0, rc = 0;
6232
6233         if (argc > 2)
6234                 return CMD_HELP;
6235
6236         if (argc == 2 && !realpath(argv[1], path)) {
6237                 rc = -errno;
6238                 fprintf(stderr, "error: invalid path '%s': %s\n",
6239                         argv[1], strerror(-rc));
6240                 return rc;
6241         }
6242
6243         while (!llapi_search_mounts(path, index++, mntdir, NULL)) {
6244                 /* Check if we have a mount point */
6245                 if (mntdir[0] == '\0')
6246                         continue;
6247
6248                 memset(&param, 0, sizeof(param));
6249                 if (!strcmp(argv[0], "mdts"))
6250                         param.fp_get_lmv = 1;
6251
6252                 rc = llapi_ostlist(mntdir, &param);
6253                 if (rc) {
6254                         fprintf(stderr, "error: %s: failed on %s\n",
6255                                 argv[0], mntdir);
6256                 }
6257                 if (path[0] != '\0')
6258                         break;
6259                 memset(mntdir, 0, PATH_MAX);
6260         }
6261
6262         return rc;
6263 }
6264
6265 static int lfs_getstripe(int argc, char **argv)
6266 {
6267         struct find_param param = { 0 };
6268
6269         param.fp_max_depth = 1;
6270         return lfs_getstripe_internal(argc, argv, &param);
6271 }
6272
6273 /* functions */
6274 static int lfs_getdirstripe(int argc, char **argv)
6275 {
6276         struct find_param param = { 0 };
6277         struct option long_opts[] = {
6278         { .val = 'c',   .name = "mdt-count",     .has_arg = no_argument },
6279         { .val = 'D',   .name = "default",       .has_arg = no_argument },
6280         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6281         { .val = 'H',   .name = "mdt-hash",      .has_arg = no_argument },
6282         { .val = 'i',   .name = "mdt-index",     .has_arg = no_argument },
6283         { .val = 'm',   .name = "mdt-index",     .has_arg = no_argument },
6284         { .val = 'O',   .name = "obd",           .has_arg = required_argument },
6285         { .val = 'r',   .name = "recursive",     .has_arg = no_argument },
6286         { .val = 'T',   .name = "mdt-count",     .has_arg = no_argument },
6287         { .val = 'v',   .name = "verbose",       .has_arg = no_argument },
6288         { .val = 'X',   .name = "max-inherit",   .has_arg = no_argument },
6289         { .val = 'y',   .name = "yaml",          .has_arg = no_argument },
6290         { .val = LFS_INHERIT_RR_OPT,
6291                         .name = "max-inherit-rr", .has_arg = no_argument },
6292         { .name = NULL } };
6293         int c, rc;
6294
6295         param.fp_get_lmv = 1;
6296
6297         while ((c = getopt_long(argc, argv,
6298                                 "cDhHimO:rtTvXy", long_opts, NULL)) != -1) {
6299                 switch (c) {
6300                 case 'c':
6301                 case 'T':
6302                         param.fp_verbose |= VERBOSE_COUNT;
6303                         break;
6304                 case 'D':
6305                         param.fp_get_default_lmv = 1;
6306                         break;
6307 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6308                 case 't':
6309                         fprintf(stderr,
6310                                 "warning: '-t' deprecated, use '--mdt-hash' or '-H' instead\n");
6311                         /* fallthrough */
6312 #endif
6313                 case 'H':
6314                         param.fp_verbose |= VERBOSE_HASH_TYPE;
6315                         break;
6316                 case 'i': /* fallthrough */
6317                 case 'm':
6318                         param.fp_verbose |= VERBOSE_STRIPE_OFFSET;
6319                         break;
6320                 case 'O':
6321                         if (param.fp_obd_uuid) {
6322                                 fprintf(stderr,
6323                                         "%s: only one obduuid allowed",
6324                                         progname);
6325                                 return CMD_HELP;
6326                         }
6327                         param.fp_obd_uuid = (struct obd_uuid *)optarg;
6328                         break;
6329                 case 'r':
6330                         param.fp_recursive = 1;
6331                         break;
6332                 case 'v':
6333                         param.fp_verbose |= VERBOSE_DETAIL;
6334                         break;
6335                 case 'X':
6336                         param.fp_verbose |= VERBOSE_INHERIT;
6337                         break;
6338                 case LFS_INHERIT_RR_OPT:
6339                         param.fp_verbose |= VERBOSE_INHERIT_RR;
6340                         break;
6341                 case 'y':
6342                         param.fp_yaml = 1;
6343                         break;
6344                 default:
6345                         fprintf(stderr, "%s: unrecognized option '%s'\n",
6346                                 progname, argv[optind - 1]);
6347                         /* fallthrough */
6348                 case 'h':
6349                         return CMD_HELP;
6350                 }
6351         }
6352
6353         if (optind >= argc)
6354                 return CMD_HELP;
6355
6356         if (param.fp_recursive)
6357                 param.fp_max_depth = -1;
6358
6359         if (!param.fp_verbose)
6360                 param.fp_verbose = VERBOSE_DEFAULT;
6361
6362         do {
6363                 rc = llapi_getstripe(argv[optind], &param);
6364         } while (++optind < argc && !rc);
6365
6366         if (rc)
6367                 fprintf(stderr, "error: %s failed for %s.\n",
6368                         argv[0], argv[optind - 1]);
6369         return rc;
6370 }
6371
6372 enum mntdf_flags {
6373         MNTDF_INODES    = 0x0001,
6374         MNTDF_COOKED    = 0x0002,
6375         MNTDF_LAZY      = 0x0004,
6376         MNTDF_VERBOSE   = 0x0008,
6377         MNTDF_SHOW      = 0x0010,
6378         MNTDF_DECIMAL   = 0x0020,
6379 };
6380
6381 #define COOK(value, base)                                       \
6382 ({                                                              \
6383         int radix = 0;                                          \
6384         while (value > base) {                                  \
6385                 value /= base;                                  \
6386                 radix++;                                        \
6387         }                                                       \
6388         radix;                                                  \
6389 })
6390 #define UUF     "%-20s"
6391 #define CSF     "%11s"
6392 #define CDF     "%11llu"
6393 #define HDF     "%8.1f%c"
6394 #define RSF     "%4s"
6395 #define RDF     "%3d%%"
6396
6397 static inline int obd_statfs_ratio(const struct obd_statfs *st, bool inodes)
6398 {
6399         double avail, used, ratio = 0;
6400
6401         if (inodes) {
6402                 avail = st->os_ffree;
6403                 used = st->os_files - st->os_ffree;
6404         } else {
6405                 avail = st->os_bavail;
6406                 used = st->os_blocks - st->os_bfree;
6407         }
6408         if (avail + used > 0)
6409                 ratio = used / (used + avail) * 100;
6410
6411         /* Round up to match df(1) usage percentage */
6412         return (ratio - (int)ratio) > 0 ? (int)(ratio + 1) : (int)ratio;
6413 }
6414
6415 /*
6416  * This is to identify various problem states for "lfs df" if .osn_err = true,
6417  * so only show flags reflecting those states by default. Informational states
6418  * are only shown with "-v" and use lower-case names to distinguish them.
6419  * UNUSED[12] were for "EROFS = 30" until 1.6 but are now available for use.
6420  */
6421 static struct obd_statfs_state_names {
6422         enum obd_statfs_state   osn_state;
6423         const char              osn_name;
6424         bool                    osn_err;
6425 } oss_names[] = {
6426         { .osn_state = OS_STATFS_DEGRADED,   .osn_name = 'D', .osn_err = true },
6427         { .osn_state = OS_STATFS_READONLY,   .osn_name = 'R', .osn_err = true },
6428         { .osn_state = OS_STATFS_NOPRECREATE,.osn_name = 'N', .osn_err = true },
6429         { .osn_state = OS_STATFS_UNUSED1,    .osn_name = '?', .osn_err = true },
6430         { .osn_state = OS_STATFS_UNUSED2,    .osn_name = '?', .osn_err = true },
6431         { .osn_state = OS_STATFS_ENOSPC,     .osn_name = 'S', .osn_err = true },
6432         { .osn_state = OS_STATFS_ENOINO,     .osn_name = 'I', .osn_err = true },
6433         { .osn_state = OS_STATFS_SUM,        .osn_name = 'a', /* aggregate */ },
6434         { .osn_state = OS_STATFS_NONROT,     .osn_name = 'f', /* flash */     },
6435 };
6436
6437 static int showdf(char *mntdir, struct obd_statfs *stat,
6438                   char *uuid, enum mntdf_flags flags,
6439                   char *type, int index, int rc)
6440 {
6441         long long avail, used, total;
6442         int ratio = 0;
6443         char *suffix = flags & MNTDF_DECIMAL ? "kMGTPEZY" : "KMGTPEZY";
6444         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
6445         char tbuf[3 * sizeof(__u64)];
6446         char ubuf[3 * sizeof(__u64)];
6447         char abuf[3 * sizeof(__u64)];
6448         char rbuf[3 * sizeof(__u64)];
6449
6450         if (!uuid || !stat)
6451                 return -EINVAL;
6452
6453         switch (rc) {
6454         case 0:
6455                 if (flags & MNTDF_INODES) {
6456                         avail = stat->os_ffree;
6457                         used = stat->os_files - stat->os_ffree;
6458                         total = stat->os_files;
6459                 } else {
6460                         int shift = flags & MNTDF_COOKED ? 0 : 10;
6461
6462                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
6463                         used  = ((stat->os_blocks - stat->os_bfree) *
6464                                  stat->os_bsize) >> shift;
6465                         total = (stat->os_blocks * stat->os_bsize) >> shift;
6466                 }
6467
6468                 ratio = obd_statfs_ratio(stat, flags & MNTDF_INODES);
6469
6470                 if (flags & MNTDF_COOKED) {
6471                         int base = flags & MNTDF_DECIMAL ? 1000 : 1024;
6472                         double cook_val;
6473                         int i;
6474
6475                         cook_val = (double)total;
6476                         i = COOK(cook_val, base);
6477                         if (i > 0)
6478                                 snprintf(tbuf, sizeof(tbuf), HDF, cook_val,
6479                                          suffix[i - 1]);
6480                         else
6481                                 snprintf(tbuf, sizeof(tbuf), CDF, total);
6482
6483                         cook_val = (double)used;
6484                         i = COOK(cook_val, base);
6485                         if (i > 0)
6486                                 snprintf(ubuf, sizeof(ubuf), HDF, cook_val,
6487                                          suffix[i - 1]);
6488                         else
6489                                 snprintf(ubuf, sizeof(ubuf), CDF, used);
6490
6491                         cook_val = (double)avail;
6492                         i = COOK(cook_val, base);
6493                         if (i > 0)
6494                                 snprintf(abuf, sizeof(abuf), HDF, cook_val,
6495                                          suffix[i - 1]);
6496                         else
6497                                 snprintf(abuf, sizeof(abuf), CDF, avail);
6498                 } else {
6499                         snprintf(tbuf, sizeof(tbuf), CDF, total);
6500                         snprintf(ubuf, sizeof(tbuf), CDF, used);
6501                         snprintf(abuf, sizeof(tbuf), CDF, avail);
6502                 }
6503
6504                 sprintf(rbuf, RDF, ratio);
6505                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
6506                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
6507                 if (type)
6508                         printf("[%s:%d]", type, index);
6509
6510                 if (stat->os_state) {
6511                         uint32_t i;
6512
6513                         printf(" ");
6514                         for (i = 0; i < ARRAY_SIZE(oss_names); i++) {
6515                                 if (oss_names[i].osn_state & stat->os_state &&
6516                                     (oss_names[i].osn_err ||
6517                                      flags & MNTDF_VERBOSE))
6518                                         printf("%c", oss_names[i].osn_name);
6519                         }
6520                 }
6521
6522                 printf("\n");
6523                 break;
6524         case -ENODATA:
6525                 printf(UUF": inactive device\n", uuid);
6526                 break;
6527         default:
6528                 printf(UUF": %s\n", uuid, strerror(-rc));
6529                 break;
6530         }
6531
6532         return 0;
6533 }
6534
6535 struct ll_stat_type {
6536         int   st_op;
6537         char *st_name;
6538 };
6539
6540 #define LL_STATFS_MAX   LOV_MAX_STRIPE_COUNT
6541
6542 struct ll_statfs_data {
6543         int                     sd_index;
6544         struct obd_statfs       sd_st;
6545 };
6546
6547 struct ll_statfs_buf {
6548         int                     sb_count;
6549         struct ll_statfs_data   sb_buf[LL_STATFS_MAX];
6550 };
6551
6552 static int mntdf(char *mntdir, char *fsname, char *pool, enum mntdf_flags flags,
6553                  int ops, struct ll_statfs_buf *lsb)
6554 {
6555         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
6556         struct obd_uuid uuid_buf;
6557         char *poolname = NULL;
6558         struct ll_stat_type types[] = {
6559                 { .st_op = LL_STATFS_LMV,       .st_name = "MDT" },
6560                 { .st_op = LL_STATFS_LOV,       .st_name = "OST" },
6561                 { .st_name = NULL } };
6562         struct ll_stat_type *tp;
6563         __u64 ost_files = 0;
6564         __u64 ost_ffree = 0;
6565         __u32 index;
6566         __u32 type;
6567         int fd;
6568         int rc = 0;
6569         int rc2;
6570
6571         if (pool) {
6572                 poolname = strchr(pool, '.');
6573                 if (poolname) {
6574                         if (strncmp(fsname, pool, strlen(fsname))) {
6575                                 fprintf(stderr, "filesystem name incorrect\n");
6576                                 return -ENODEV;
6577                         }
6578                         poolname++;
6579                 } else
6580                         poolname = pool;
6581         }
6582
6583         fd = open(mntdir, O_RDONLY);
6584         if (fd < 0) {
6585                 rc = -errno;
6586                 fprintf(stderr, "%s: cannot open '%s': %s\n", progname, mntdir,
6587                         strerror(errno));
6588                 return rc;
6589         }
6590
6591         if (flags & MNTDF_SHOW) {
6592                 if (flags & MNTDF_INODES)
6593                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
6594                                "UUID", "Inodes", "IUsed", "IFree",
6595                                "IUse%", "Mounted on");
6596                 else
6597                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
6598                                "UUID",
6599                                flags & MNTDF_COOKED ? "bytes" : "1K-blocks",
6600                                "Used", "Available", "Use%", "Mounted on");
6601         }
6602
6603         for (tp = types; tp->st_name != NULL; tp++) {
6604                 bool have_ost = false;
6605
6606                 if (!(tp->st_op & ops))
6607                         continue;
6608
6609                 for (index = 0; ; index++) {
6610                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
6611                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
6612                         type = flags & MNTDF_LAZY ?
6613                                 tp->st_op | LL_STATFS_NODELAY : tp->st_op;
6614                         rc2 = llapi_obd_fstatfs(fd, type, index,
6615                                                &stat_buf, &uuid_buf);
6616                         if (rc2 == -ENODEV)
6617                                 break;
6618                         if (rc2 == -EAGAIN)
6619                                 continue;
6620                         if (rc2 == -ENODATA) { /* Inactive device, OK. */
6621                                 if (!(flags & MNTDF_VERBOSE))
6622                                         continue;
6623                         } else if (rc2 < 0 && rc == 0) {
6624                                 rc = rc2;
6625                         }
6626
6627                         /*
6628                          * If we have OSTs then don't report MDT block counts.
6629                          * For MDT-only filesystems the expectation is that all
6630                          * layouts have a DoM component.  For filesystems with
6631                          * OSTs, files are not necessarily going to store data
6632                          * on MDTs, and MDT space is limited to a fraction of
6633                          * OST space, so don't include it in the summary.
6634                          */
6635                         if (tp->st_op == LL_STATFS_LOV && !have_ost) {
6636                                 have_ost = true;
6637                                 sum.os_blocks = 0;
6638                                 sum.os_bfree = 0;
6639                                 sum.os_bavail = 0;
6640                         }
6641
6642                         if (poolname && tp->st_op == LL_STATFS_LOV &&
6643                             llapi_search_ost(fsname, poolname,
6644                                              obd_uuid2str(&uuid_buf)) != 1)
6645                                 continue;
6646
6647                         /*
6648                          * the llapi_obd_fstatfs() call may have returned with
6649                          * an error, but if it filled in uuid_buf we will at
6650                          * lease use that to print out a message for that OBD.
6651                          * If we didn't get anything in the uuid_buf, then fill
6652                          * it in so that we can print an error message.
6653                          */
6654                         if (uuid_buf.uuid[0] == '\0')
6655                                 snprintf(uuid_buf.uuid, sizeof(uuid_buf.uuid),
6656                                          "%s%04x", tp->st_name, index);
6657                         if (!rc && lsb) {
6658                                 lsb->sb_buf[lsb->sb_count].sd_index = index;
6659                                 lsb->sb_buf[lsb->sb_count].sd_st = stat_buf;
6660                                 lsb->sb_count++;
6661                         }
6662                         if (flags & MNTDF_SHOW)
6663                                 showdf(mntdir, &stat_buf,
6664                                        obd_uuid2str(&uuid_buf), flags,
6665                                        tp->st_name, index, rc2);
6666
6667                         if (rc2)
6668                                 continue;
6669
6670                         if (tp->st_op == LL_STATFS_LMV) {
6671                                 sum.os_ffree += stat_buf.os_ffree;
6672                                 sum.os_files += stat_buf.os_files;
6673                         } else /* if (tp->st_op == LL_STATFS_LOV) */ {
6674                                 ost_files += stat_buf.os_files;
6675                                 ost_ffree += stat_buf.os_ffree;
6676                         }
6677                         sum.os_blocks += stat_buf.os_blocks *
6678                                          stat_buf.os_bsize;
6679                         sum.os_bfree  += stat_buf.os_bfree *
6680                                          stat_buf.os_bsize;
6681                         sum.os_bavail += stat_buf.os_bavail *
6682                                          stat_buf.os_bsize;
6683                 }
6684         }
6685
6686         close(fd);
6687
6688         /*
6689          * If we have _some_ OSTs, but don't have as many free objects on the
6690          * OST as inodes on the MDTs, reduce the reported number of inodes
6691          * to compensate, so that the "inodes in use" number is correct.
6692          * This should be kept in sync with ll_statfs_internal().
6693          */
6694         if (ost_files && ost_ffree < sum.os_ffree) {
6695                 sum.os_files = (sum.os_files - sum.os_ffree) + ost_ffree;
6696                 sum.os_ffree = ost_ffree;
6697         }
6698         if (flags & MNTDF_SHOW) {
6699                 printf("\n");
6700                 showdf(mntdir, &sum, "filesystem_summary:", flags, NULL, 0, 0);
6701                 printf("\n");
6702         }
6703
6704         return rc;
6705 }
6706
6707 enum {
6708         LAYOUT_INHERIT_UNSET    = -2,
6709 };
6710
6711 /* functions */
6712 static int lfs_setdirstripe(int argc, char **argv)
6713 {
6714         char *dname;
6715         struct lfs_setstripe_args lsa = { 0 };
6716         struct llapi_stripe_param *param = NULL;
6717         __u32 mdts[LMV_MAX_STRIPE_COUNT] = { 0 };
6718         char *end;
6719         int c;
6720         char *mode_opt = NULL;
6721         bool default_stripe = false;
6722         bool delete = false;
6723         bool foreign_mode = false;
6724         mode_t mode = S_IRWXU | S_IRWXG | S_IRWXO;
6725         mode_t previous_mode = 0;
6726         char *xattr = NULL;
6727         __u32 type = LU_FOREIGN_TYPE_SYMLINK, flags = 0;
6728         int max_inherit = LAYOUT_INHERIT_UNSET;
6729         int max_inherit_rr = LAYOUT_INHERIT_UNSET;
6730         struct option long_opts[] = {
6731         { .val = 'c',   .name = "count",        .has_arg = required_argument },
6732         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument },
6733         { .val = 'd',   .name = "delete",       .has_arg = no_argument },
6734         { .val = 'D',   .name = "default",      .has_arg = no_argument },
6735         { .val = 'D',   .name = "default_stripe", .has_arg = no_argument },
6736         { .val = LFS_LAYOUT_FLAGS_OPT,
6737                         .name = "flags",        .has_arg = required_argument },
6738         { .val = LFS_LAYOUT_FOREIGN_OPT,
6739                         .name = "foreign",      .has_arg = optional_argument},
6740         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6741         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
6742 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 17, 53, 0)
6743         { .val = 'i',   .name = "mdt-index",    .has_arg = required_argument },
6744         { .val = 'i',   .name = "mdt",          .has_arg = required_argument },
6745 #else
6746 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
6747         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
6748         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
6749 #endif
6750 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6751         { .val = 'i',   .name = "index",        .has_arg = required_argument },
6752 #endif
6753         { .val = 'o',   .name = "mode",         .has_arg = required_argument },
6754 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6755         { .val = 't',   .name = "hash-type",    .has_arg = required_argument },
6756 #endif
6757         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
6758         { .val = 'x',   .name = "xattr",        .has_arg = required_argument },
6759         { .val = 'X',   .name = "max-inherit",  .has_arg = required_argument },
6760         { .val = LFS_INHERIT_RR_OPT,
6761                         .name = "max-inherit-rr", .has_arg = required_argument},
6762 /* setstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
6763         { .name = NULL } };
6764         int result = 0;
6765
6766         setstripe_args_init(&lsa);
6767
6768         while ((c = getopt_long(argc, argv, "c:dDi:hH:m:o:t:T:x:X:",
6769                                 long_opts, NULL)) >= 0) {
6770                 switch (c) {
6771                 case 0:
6772                         /* Long options. */
6773                         break;
6774                 case 'c':
6775                 case 'T':
6776                         errno = 0;
6777                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
6778                         if (errno != 0 || *end != '\0' ||
6779                             lsa.lsa_stripe_count < -1 ||
6780                             lsa.lsa_stripe_count > LOV_MAX_STRIPE_COUNT) {
6781                                 fprintf(stderr,
6782                                         "%s: invalid stripe count '%s'\n",
6783                                         progname, optarg);
6784                                 return CMD_HELP;
6785                         }
6786                         break;
6787                 case 'd':
6788                         delete = true;
6789                         default_stripe = true;
6790                         break;
6791                 case 'D':
6792                         default_stripe = true;
6793                         break;
6794                 case LFS_LAYOUT_FOREIGN_OPT:
6795                         if (optarg) {
6796                                 /* check pure numeric */
6797                                 type = strtoul(optarg, &end, 0);
6798                                 if (*end) {
6799                                         /* check name */
6800                                         type = check_foreign_type_name(optarg);
6801                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
6802                                                 fprintf(stderr,
6803                                                         "%s %s: unknown foreign type '%s'\n",
6804                                                         progname, argv[0],
6805                                                         optarg);
6806                                                 return CMD_HELP;
6807                                         }
6808                                 } else if (type >= UINT32_MAX) {
6809                                         fprintf(stderr,
6810                                                 "%s %s: invalid foreign type '%s'\n",
6811                                                 progname, argv[0], optarg);
6812                                         return CMD_HELP;
6813                                 }
6814                         }
6815                         foreign_mode = true;
6816                         break;
6817                 case LFS_LAYOUT_FLAGS_OPT:
6818                         errno = 0;
6819                         flags = strtoul(optarg, &end, 16);
6820                         if (errno != 0 || *end != '\0' ||
6821                             flags >= UINT32_MAX) {
6822                                 fprintf(stderr,
6823                                         "%s %s: invalid hex flags '%s'\n",
6824                                         progname, argv[0], optarg);
6825                                 return CMD_HELP;
6826                         }
6827                         if (!foreign_mode) {
6828                                 fprintf(stderr,
6829                                         "%s %s: hex flags must be specified with --foreign option\n",
6830                                         progname, argv[0]);
6831                                 return CMD_HELP;
6832                         }
6833                         break;
6834 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6835                 case 't':
6836                         fprintf(stderr,
6837                                 "warning: '--hash-type' and '-t' deprecated, use '--mdt-hash' or '-H' instead\n");
6838                         /* fallthrough */
6839 #endif
6840                 case 'H':
6841                         lsa.lsa_pattern = check_hashtype(optarg);
6842                         if (lsa.lsa_pattern == 0) {
6843                                 fprintf(stderr,
6844                                         "%s %s: bad stripe hash type '%s'\n",
6845                                         progname, argv[0], optarg);
6846                                 return CMD_HELP;
6847                         }
6848                         break;
6849                 case 'i':
6850 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 17, 53, 0)
6851                 case 'm':
6852 #endif
6853 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6854                         if (strcmp(argv[optind - 1], "--index") == 0)
6855                                 fprintf(stderr,
6856                                         "%s %s: warning: '--index' deprecated, use '--mdt-index' instead\n",
6857                                         progname, argv[0]);
6858 #endif
6859                         lsa.lsa_nr_tgts = parse_targets(mdts,
6860                                                 sizeof(mdts) / sizeof(__u32),
6861                                                 lsa.lsa_nr_tgts, optarg, NULL);
6862                         if (lsa.lsa_nr_tgts < 0) {
6863                                 fprintf(stderr,
6864                                         "%s %s: invalid MDT target(s) '%s'\n",
6865                                         progname, argv[0], optarg);
6866                                 return CMD_HELP;
6867                         }
6868
6869                         lsa.lsa_tgts = mdts;
6870                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
6871                                 lsa.lsa_stripe_off = mdts[0];
6872                         break;
6873 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 15, 53, 0)
6874                 case 'm':
6875                         fprintf(stderr,
6876                                 "warning: '-m' is deprecated, use '--mode' or '-o' instead\n");
6877 #endif
6878                 case 'o':
6879                         mode_opt = optarg;
6880                         break;
6881                 case 'x':
6882                         xattr = optarg;
6883                         break;
6884                 case 'X':
6885                         if (!default_stripe) {
6886                                 fprintf(stderr,
6887                                         "%s %s: '--max-inherit' must be specified with '-D'\n",
6888                                         progname, argv[0]);
6889                                 return CMD_HELP;
6890                         }
6891                         errno = 0;
6892                         max_inherit = strtol(optarg, &end, 10);
6893                         if (errno != 0 || *end != '\0' || max_inherit < -2) {
6894                                 fprintf(stderr,
6895                                         "%s %s: invalid max-inherit '%s'\n",
6896                                         progname, argv[0], optarg);
6897                                 return CMD_HELP;
6898                         }
6899                         if (max_inherit == 0) {
6900                                 max_inherit = LMV_INHERIT_NONE;
6901                         } else if (max_inherit == -1) {
6902                                 max_inherit = LMV_INHERIT_UNLIMITED;
6903                         } else if (max_inherit > LMV_INHERIT_MAX) {
6904                                 fprintf(stderr,
6905                                         "%s %s: max-inherit %d exceeds maximum %u\n",
6906                                         progname, argv[0], max_inherit,
6907                                         LMV_INHERIT_MAX);
6908                                 return CMD_HELP;
6909                         }
6910                         break;
6911                 case LFS_INHERIT_RR_OPT:
6912                         if (!default_stripe) {
6913                                 fprintf(stderr,
6914                                         "%s %s: '--max-inherit-rr' must be specified with '-D'\n",
6915                                         progname, argv[0]);
6916                                 return CMD_HELP;
6917                         }
6918                         errno = 0;
6919                         max_inherit_rr = strtol(optarg, &end, 10);
6920                         if (errno != 0 || *end != '\0' || max_inherit_rr < -2) {
6921                                 fprintf(stderr,
6922                                         "%s %s: invalid max-inherit-rr '%s'\n",
6923                                         progname, argv[0], optarg);
6924                                 return CMD_HELP;
6925                         }
6926                         if (max_inherit_rr == 0) {
6927                                 max_inherit_rr = LMV_INHERIT_RR_NONE;
6928                         } else if (max_inherit_rr == -1) {
6929                                 max_inherit_rr = LMV_INHERIT_RR_UNLIMITED;
6930                         } else if (max_inherit_rr > LMV_INHERIT_RR_MAX) {
6931                                 fprintf(stderr,
6932                                         "%s %s: max-inherit-rr %d exceeds maximum %u\n",
6933                                         progname, argv[0], max_inherit_rr,
6934                                         LMV_INHERIT_RR_MAX);
6935                                 return CMD_HELP;
6936                         }
6937                         break;
6938                 default:
6939                         fprintf(stderr, "%s: unrecognized option '%s'\n",
6940                                 progname, argv[optind - 1]);
6941                         /* fallthrough */
6942                 case 'h':
6943                         return CMD_HELP;
6944                 }
6945         }
6946
6947         if (optind == argc) {
6948                 fprintf(stderr, "%s %s: DIR must be specified\n",
6949                         progname, argv[0]);
6950                 return CMD_HELP;
6951         }
6952
6953         if (xattr && !foreign_mode) {
6954                 /*
6955                  * only print a warning as this is armless and will be
6956                  * ignored
6957                  */
6958                 fprintf(stderr,
6959                         "%s %s: xattr has been specified for non-foreign layout\n",
6960                         progname, argv[0]);
6961         } else if (foreign_mode && !xattr) {
6962                 fprintf(stderr,
6963                         "%s %s: xattr must be provided in foreign mode\n",
6964                         progname, argv[0]);
6965                 return CMD_HELP;
6966         }
6967
6968         if (foreign_mode && (delete || default_stripe || lsa.lsa_nr_tgts ||
6969             lsa.lsa_tgts || setstripe_args_specified(&lsa))) {
6970                 fprintf(stderr,
6971                         "%s %s: only --xattr/--flags/--mode options are valid with --foreign\n",
6972                         progname, argv[0]);
6973                 return CMD_HELP;
6974         }
6975
6976         if (!delete && lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT &&
6977             lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT && !foreign_mode) {
6978                 /* if no parameters set, create directory on least-used MDTs */
6979                 lsa.lsa_stripe_off = LMV_OFFSET_DEFAULT;
6980                 lsa.lsa_stripe_count = 1;
6981         }
6982
6983         if (delete &&
6984             (lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
6985              lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)) {
6986                 fprintf(stderr,
6987                         "%s %s: cannot specify -d with -c or -i options\n",
6988                         progname, argv[0]);
6989                 return CMD_HELP;
6990         }
6991
6992         if (mode_opt) {
6993                 mode = strtoul(mode_opt, &end, 8);
6994                 if (*end != '\0') {
6995                         fprintf(stderr,
6996                                 "%s %s: bad MODE '%s'\n",
6997                                 progname, argv[0], mode_opt);
6998                         return CMD_HELP;
6999                 }
7000                 previous_mode = umask(0);
7001         }
7002
7003         if (max_inherit_rr != LAYOUT_INHERIT_UNSET &&
7004             lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT &&
7005             lsa.lsa_stripe_off != LMV_OFFSET_DEFAULT) {
7006                 fprintf(stderr,
7007                         "%s %s: max-inherit-rr needs mdt-index=-1, not %lld\n",
7008                         progname, argv[0], lsa.lsa_stripe_off);
7009                 return CMD_HELP;
7010         }
7011
7012         /* foreign LMV/dir case */
7013         if (foreign_mode) {
7014                 if (argc > optind + 1) {
7015                         fprintf(stderr,
7016                                 "%s %s: cannot specify multiple foreign dirs\n",
7017                                 progname, argv[0]);
7018                         return CMD_HELP;
7019                 }
7020
7021                 dname = argv[optind];
7022                 result = llapi_dir_create_foreign(dname, mode, type, flags,
7023                                                   xattr);
7024                 if (result != 0)
7025                         fprintf(stderr,
7026                                 "%s mkdir: can't create foreign dir '%s': %s\n",
7027                                 progname, dname, strerror(-result));
7028                 return result;
7029         }
7030
7031         /*
7032          * initialize stripe parameters, in case param is converted to specific,
7033          * i.e, 'lfs mkdir -i -1 -c N', always allocate space for lsp_tgts.
7034          */
7035         param = calloc(1, offsetof(typeof(*param),
7036                        lsp_tgts[lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ?
7037                                 lsa.lsa_stripe_count : lsa.lsa_nr_tgts]));
7038         if (!param) {
7039                 fprintf(stderr,
7040                         "%s %s: cannot allocate memory for parameters: %s\n",
7041                         progname, argv[0], strerror(ENOMEM));
7042                 return CMD_HELP;
7043         }
7044
7045         /* if "lfs setdirstripe -D -i -1" is used, assume 1-stripe directory */
7046         if (default_stripe && lsa.lsa_stripe_off == LMV_OFFSET_DEFAULT &&
7047             (lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT ||
7048              lsa.lsa_stripe_count == 0))
7049                 lsa.lsa_stripe_count = 1;
7050         if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
7051                 param->lsp_stripe_count = lsa.lsa_stripe_count;
7052         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
7053                 param->lsp_stripe_offset = LMV_OFFSET_DEFAULT;
7054         else
7055                 param->lsp_stripe_offset = lsa.lsa_stripe_off;
7056         if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
7057                 param->lsp_stripe_pattern = lsa.lsa_pattern;
7058         else
7059                 param->lsp_stripe_pattern = LMV_HASH_TYPE_UNKNOWN;
7060         param->lsp_pool = lsa.lsa_pool_name;
7061         param->lsp_is_specific = false;
7062         if (default_stripe) {
7063                 if (max_inherit == LAYOUT_INHERIT_UNSET)
7064                         max_inherit = LMV_INHERIT_DEFAULT;
7065                 if (max_inherit_rr == LAYOUT_INHERIT_UNSET)
7066                         max_inherit_rr = LMV_INHERIT_RR_DEFAULT;
7067                 param->lsp_max_inherit = max_inherit;
7068                 param->lsp_max_inherit_rr = max_inherit_rr;
7069         }
7070         if (strcmp(argv[0], "mkdir") == 0)
7071                 param->lsp_is_create = true;
7072         if (lsa.lsa_nr_tgts > 1) {
7073                 if (lsa.lsa_stripe_count > 0 &&
7074                     lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
7075                     lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
7076                         fprintf(stderr,
7077                                 "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
7078                                 argv[0], lsa.lsa_stripe_count,
7079                                 lsa.lsa_nr_tgts);
7080                         free(param);
7081                         return CMD_HELP;
7082                 }
7083
7084                 param->lsp_is_specific = true;
7085                 param->lsp_stripe_count = lsa.lsa_nr_tgts;
7086                 memcpy(param->lsp_tgts, mdts, sizeof(*mdts) * lsa.lsa_nr_tgts);
7087         }
7088
7089         dname = argv[optind];
7090         do {
7091                 if (default_stripe) {
7092                         result = llapi_dir_set_default_lmv(dname, param);
7093                         if (result)
7094                                 fprintf(stderr,
7095                                         "%s setdirstripe: cannot set default stripe on dir '%s': %s\n",
7096                                         progname, dname, strerror(-result));
7097                         continue;
7098                 }
7099
7100                 result = llapi_dir_create(dname, mode, param);
7101                 if (result)
7102                         fprintf(stderr,
7103                                 "%s setdirstripe: cannot create dir '%s': %s\n",
7104                                 progname, dname, strerror(-result));
7105         } while (!result && (dname = argv[++optind]));
7106
7107         if (mode_opt)
7108                 umask(previous_mode);
7109
7110         free(param);
7111         return result;
7112 }
7113
7114 /* functions */
7115 static int lfs_rmentry(int argc, char **argv)
7116 {
7117         char *dname;
7118         int   index;
7119         int   result = 0;
7120
7121         if (argc <= 1) {
7122                 fprintf(stderr, "error: %s: missing dirname\n",
7123                         argv[0]);
7124                 return CMD_HELP;
7125         }
7126
7127         index = 1;
7128         dname = argv[index];
7129         while (dname) {
7130                 result = llapi_direntry_remove(dname);
7131                 if (result) {
7132                         fprintf(stderr,
7133                                 "error: %s: remove dir entry '%s' failed\n",
7134                                 argv[0], dname);
7135                         break;
7136                 }
7137                 dname = argv[++index];
7138         }
7139         return result;
7140 }
7141
7142 static int lfs_unlink_foreign(int argc, char **argv)
7143 {
7144         char *name;
7145         int   index;
7146         int   result = 0;
7147
7148         if (argc <= 1) {
7149                 fprintf(stderr, "error: %s: missing pathname\n",
7150                         argv[0]);
7151                 return CMD_HELP;
7152         }
7153
7154         index = 1;
7155         name = argv[index];
7156         while (name != NULL) {
7157                 result = llapi_unlink_foreign(name);
7158                 if (result) {
7159                         fprintf(stderr,
7160                                 "error: %s: unlink foreign entry '%s' failed\n",
7161                                 argv[0], name);
7162                         break;
7163                 }
7164                 name = argv[++index];
7165         }
7166         return result;
7167 }
7168
7169 static int lfs_mv(int argc, char **argv)
7170 {
7171         struct lmv_user_md lmu = { LMV_USER_MAGIC };
7172         struct find_param param = {
7173                 .fp_max_depth = -1,
7174                 .fp_mdt_index = -1,
7175         };
7176         char *end;
7177         int c;
7178         int rc = 0;
7179         struct option long_opts[] = {
7180         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
7181         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
7182         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
7183         { .name = NULL } };
7184
7185         while ((c = getopt_long(argc, argv, "m:M:v", long_opts, NULL)) != -1) {
7186                 switch (c) {
7187 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
7188                 case 'M':
7189                         fprintf(stderr,
7190                                 "warning: '-M' deprecated, use '--mdt-index' or '-m' instead\n");
7191 #endif
7192                 case 'm':
7193                         errno = 0;
7194                         lmu.lum_stripe_offset = strtoul(optarg, &end, 0);
7195                         if (errno != 0 || *end != '\0' ||
7196                             lmu.lum_stripe_offset >= UINT32_MAX) {
7197                                 fprintf(stderr, "%s mv: bad MDT index '%s'\n",
7198                                         progname, optarg);
7199                                 return CMD_HELP;
7200                         }
7201                         break;
7202                 case 'v':
7203                         param.fp_verbose = VERBOSE_DETAIL;
7204                         break;
7205                 default:
7206                         fprintf(stderr, "%s mv: unrecognized option '%s'\n",
7207                                 progname, argv[optind - 1]);
7208                         return CMD_HELP;
7209                 }
7210         }
7211
7212         if (lmu.lum_stripe_offset == LMV_OFFSET_DEFAULT) {
7213                 fprintf(stderr, "%s mv: MDT index must be specified\n",
7214                         progname);
7215                 return CMD_HELP;
7216         }
7217
7218         if (optind >= argc) {
7219                 fprintf(stderr, "%s mv: DIR must be specified\n", progname);
7220                 return CMD_HELP;
7221         }
7222
7223         lmu.lum_hash_type = LMV_HASH_TYPE_UNKNOWN;
7224
7225         /* initialize migrate mdt parameters */
7226         param.fp_lmv_md = &lmu;
7227         param.fp_migrate = 1;
7228         rc = llapi_migrate_mdt(argv[optind], &param);
7229         if (rc != 0)
7230                 fprintf(stderr, "%s mv: cannot migrate '%s' to MDT%04x: %s\n",
7231                         progname, argv[optind], lmu.lum_stripe_offset,
7232                         strerror(-rc));
7233         return rc;
7234 }
7235
7236 static int lfs_osts(int argc, char **argv)
7237 {
7238         return lfs_tgts(argc, argv);
7239 }
7240
7241 static int lfs_mdts(int argc, char **argv)
7242 {
7243         return lfs_tgts(argc, argv);
7244 }
7245
7246 static int lfs_df(int argc, char **argv)
7247 {
7248         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
7249         enum mntdf_flags flags = MNTDF_SHOW;
7250         int ops = LL_STATFS_LMV | LL_STATFS_LOV;
7251         int c, rc = 0, rc1 = 0, index = 0, arg_idx = 0;
7252         char fsname[PATH_MAX] = "", *pool_name = NULL;
7253         struct option long_opts[] = {
7254         { .val = 'h',   .name = "human-readable", .has_arg = no_argument },
7255         { .val = 'H',   .name = "si",           .has_arg = no_argument },
7256         { .val = 'i',   .name = "inodes",       .has_arg = no_argument },
7257         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
7258         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
7259         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
7260         { .name = NULL} };
7261
7262         while ((c = getopt_long(argc, argv, "hHilp:v", long_opts, NULL)) != -1) {
7263                 switch (c) {
7264                 case 'h':
7265                         flags = (flags & ~MNTDF_DECIMAL) | MNTDF_COOKED;
7266                         break;
7267                 case 'H':
7268                         flags |= MNTDF_COOKED | MNTDF_DECIMAL;
7269                         break;
7270                 case 'i':
7271                         flags |= MNTDF_INODES;
7272                         break;
7273                 case 'l':
7274                         flags |= MNTDF_LAZY;
7275                         break;
7276                 case 'p':
7277                         pool_name = optarg;
7278                         break;
7279                 case 'v':
7280                         flags |= MNTDF_VERBOSE;
7281                         break;
7282                 default:
7283                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7284                                 progname, argv[optind - 1]);
7285                         return CMD_HELP;
7286                 }
7287         }
7288
7289         /* Handle case where path is not specified */
7290         if (optind == argc) {
7291                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7292                         /* Check if we have a mount point */
7293                         if (mntdir[0] == '\0')
7294                                 continue;
7295
7296                         rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
7297                         if (rc || path[0] != '\0')
7298                                 break;
7299
7300                         fsname[0] = '\0'; /* avoid matching in next loop */
7301                         mntdir[0] = '\0'; /* avoid matching in next loop */
7302                         path[0] = '\0'; /* clean for next loop */
7303                 }
7304                 return rc;
7305         }
7306
7307         /* Loop through all the remaining arguments. These are Lustre FS
7308          * paths.
7309          */
7310         for (arg_idx = optind; arg_idx <= argc - 1; arg_idx++) {
7311                 bool valid = false;
7312
7313                 fsname[0] = '\0'; /* start clean */
7314                 mntdir[0] = '\0'; /* start clean */
7315                 path[0] = '\0';   /* start clean */
7316
7317                 /* path does not exists at all */
7318                 if (!realpath(argv[arg_idx], path)) {
7319                         rc = -errno;
7320                         fprintf(stderr, "error: invalid path '%s': %s\n",
7321                                 argv[arg_idx], strerror(-rc));
7322                         /* save first seen error */
7323                         if (!rc1)
7324                                 rc1 = rc;
7325
7326                         continue;
7327                 }
7328
7329                 /* path exists but may not be a Lustre filesystem */
7330                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7331                         /* Check if we have a mount point */
7332                         if (mntdir[0] == '\0')
7333                                 continue;
7334
7335                         rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
7336                         if (rc || path[0] != '\0') {
7337                                 valid = true;
7338
7339                                 /* save first seen error */
7340                                 if (!rc1)
7341                                         rc1 = rc;
7342                                 break;
7343                         }
7344                 }
7345
7346                 if (!valid) {
7347                         llapi_printf(LLAPI_MSG_ERROR,
7348                                      "%s:%s Not a Lustre filesystem\n",
7349                                      argv[0], argv[arg_idx]);
7350                         /* save first seen error */
7351                         if (!rc1)
7352                                 rc1 = -EOPNOTSUPP;
7353                 }
7354         }
7355
7356         return rc1;
7357 }
7358
7359 static int print_instance(const char *mntdir, char *buf, size_t buflen,
7360                           bool opt_instance, bool opt_fsname, bool opt_mntdir)
7361 {
7362         int rc = 0;
7363
7364         if (opt_fsname == opt_instance) { /* both true or both false */
7365                 rc = llapi_getname(mntdir, buf, buflen);
7366         } else if (opt_fsname) {
7367                 /*
7368                  * llapi_search_mounts() fills @buf with fsname, but that is not
7369                  * called if explicit paths are specified on the command-line
7370                  */
7371                 if (buf[0] == '\0')
7372                         rc = llapi_get_fsname(mntdir, buf, buflen);
7373         } else /* if (opt_instance) */ {
7374                 rc = llapi_get_instance(mntdir, buf, buflen);
7375         }
7376
7377         if (rc < 0) {
7378                 fprintf(stderr, "cannot get instance for '%s': %s\n",
7379                         mntdir, strerror(-rc));
7380                 return rc;
7381         }
7382
7383         if (opt_mntdir)
7384                 printf("%s %s\n", buf, mntdir);
7385         else
7386                 printf("%s\n", buf);
7387
7388         return 0;
7389 }
7390
7391 static int lfs_getname(int argc, char **argv)
7392 {
7393         struct option long_opts[] = {
7394         { .val = 'h',   .name = "help",         .has_arg = no_argument },
7395         { .val = 'i',   .name = "instance",     .has_arg = no_argument },
7396         { .val = 'n',   .name = "fsname",       .has_arg = no_argument },
7397         { .name = NULL} };
7398         bool opt_instance = false, opt_fsname = false;
7399         char fsname[PATH_MAX] = "";
7400         int rc = 0, rc2, c;
7401
7402         while ((c = getopt_long(argc, argv, "hin", long_opts, NULL)) != -1) {
7403                 switch (c) {
7404                 case 'i':
7405                         opt_instance = true;
7406                         break;
7407                 case 'n':
7408                         opt_fsname = true;
7409                         break;
7410                 default:
7411                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7412                                 progname, argv[optind - 1]);
7413                         /* fallthrough */
7414                 case 'h':
7415                         return CMD_HELP;
7416                 }
7417         }
7418
7419         if (optind == argc) { /* no paths specified, get all paths. */
7420                 char mntdir[PATH_MAX] = "", path[PATH_MAX] = "";
7421                 int index = 0;
7422
7423                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7424                         rc2 = print_instance(mntdir, fsname, sizeof(fsname),
7425                                              opt_instance, opt_fsname, true);
7426                         if (!rc)
7427                                 rc = rc2;
7428                         path[0] = fsname[0] = mntdir[0] = '\0';
7429                 }
7430         } else { /* paths specified, only attempt to search these. */
7431                 bool opt_mntdir;
7432
7433                 /* if only one path is given, print only requested info */
7434                 opt_mntdir = argc - optind > 1 || (opt_instance == opt_fsname);
7435
7436                 for (; optind < argc; optind++) {
7437                         rc2 = print_instance(argv[optind], fsname,
7438                                              sizeof(fsname), opt_instance,
7439                                              opt_fsname, opt_mntdir);
7440                         if (!rc)
7441                                 rc = rc2;
7442                         fsname[0] = '\0';
7443                 }
7444         }
7445
7446         return rc;
7447 }
7448
7449 static int lfs_check(int argc, char **argv)
7450 {
7451         char mntdir[PATH_MAX] = {'\0'};
7452         int num_types = 1;
7453         char *obd_types[3];
7454         char obd_type1[4];
7455         char obd_type2[4];
7456         char obd_type3[4];
7457         int rc;
7458
7459         if (argc != 2) {
7460                 fprintf(stderr, "%s check: server type must be specified\n",
7461                         progname);
7462                 return CMD_HELP;
7463         }
7464
7465         obd_types[0] = obd_type1;
7466         obd_types[1] = obd_type2;
7467         obd_types[2] = obd_type3;
7468
7469         if (strcmp(argv[1], "osts") == 0) {
7470                 strcpy(obd_types[0], "osc");
7471         } else if (strcmp(argv[1], "mdts") == 0 ||
7472                    strcmp(argv[1], "mds") == 0) {
7473                 strcpy(obd_types[0], "mdc");
7474         } else if (strcmp(argv[1], "mgts") == 0) {
7475                 strcpy(obd_types[0], "mgc");
7476         } else if (strcmp(argv[1], "all") == 0 ||
7477                    strcmp(argv[1], "servers") == 0) {
7478                 num_types = 3;
7479                 strcpy(obd_types[0], "osc");
7480                 strcpy(obd_types[1], "mdc");
7481                 strcpy(obd_types[2], "mgc");
7482         } else {
7483                 fprintf(stderr, "%s check: unrecognized option '%s'\n",
7484                         progname, argv[1]);
7485                 return CMD_HELP;
7486         }
7487
7488         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
7489         if (rc < 0 || mntdir[0] == '\0') {
7490                 fprintf(stderr,
7491                         "%s check: cannot find mounted Lustre filesystem: %s\n",
7492                         progname, (rc < 0) ? strerror(-rc) : strerror(ENODEV));
7493                 return rc;
7494         }
7495
7496         rc = llapi_target_check(num_types, obd_types, mntdir);
7497         if (rc)
7498                 fprintf(stderr, "%s check: cannot check target '%s': %s\n",
7499                         progname, argv[1], strerror(-rc));
7500
7501         return rc;
7502 }
7503
7504 #ifdef HAVE_SYS_QUOTA_H
7505 #define ADD_OVERFLOW(a, b) \
7506                      ((((a) + (b)) < (a)) ? \
7507                       ((a) = ULONG_MAX) : ((a) = (a) + (b)))
7508
7509 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
7510  * returns the value or ULONG_MAX on integer overflow or incorrect format
7511  * Notes:
7512  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
7513  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
7514  *        3. empty integer value is interpreted as 0
7515  */
7516 static unsigned long str2sec(const char *timestr)
7517 {
7518         const char spec[] = "smhdw";
7519         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
7520         unsigned long val = 0;
7521         char *tail;
7522
7523         if (strpbrk(timestr, spec) == NULL) {
7524                 /*
7525                  * no specifiers inside the time string,
7526                  * should treat it as an integer value
7527                  */
7528                 val = strtoul(timestr, &tail, 10);
7529                 return *tail ? ULONG_MAX : val;
7530         }
7531
7532         /* format string is XXwXXdXXhXXmXXs */
7533         while (*timestr) {
7534                 unsigned long v;
7535                 int ind;
7536                 char *ptr;
7537
7538                 v = strtoul(timestr, &tail, 10);
7539                 if (v == ULONG_MAX || *tail == '\0')
7540                         /*
7541                          * value too large (ULONG_MAX or more)
7542                          * or missing specifier
7543                          */
7544                         goto error;
7545
7546                 ptr = strchr(spec, *tail);
7547                 if (!ptr)
7548                         /* unknown specifier */
7549                         goto error;
7550
7551                 ind = ptr - spec;
7552
7553                 /* check if product will overflow the type */
7554                 if (!(v < ULONG_MAX / mult[ind]))
7555                         goto error;
7556
7557                 ADD_OVERFLOW(val, mult[ind] * v);
7558                 if (val == ULONG_MAX)
7559                         goto error;
7560
7561                 timestr = tail + 1;
7562         }
7563
7564         return val;
7565
7566 error:
7567         return ULONG_MAX;
7568 }
7569
7570 #define ARG2ULL(nr, str, def_units)                                     \
7571 do {                                                                    \
7572         unsigned long long limit, units = def_units;                    \
7573         int rc;                                                         \
7574                                                                         \
7575         rc = llapi_parse_size(str, &limit, &units, 1);                  \
7576         if (rc < 0) {                                                   \
7577                 fprintf(stderr, "%s: invalid limit '%s'\n",             \
7578                         progname, str);                                 \
7579                 return CMD_HELP;                                        \
7580         }                                                               \
7581         nr = limit;                                                     \
7582 } while (0)
7583
7584 static inline int has_times_option(int argc, char **argv)
7585 {
7586         int i;
7587
7588         for (i = 1; i < argc; i++)
7589                 if (!strcmp(argv[i], "-t"))
7590                         return 1;
7591
7592         return 0;
7593 }
7594
7595 static inline int lfs_verify_poolarg(char *pool)
7596 {
7597         if (strnlen(optarg, LOV_MAXPOOLNAME + 1) > LOV_MAXPOOLNAME) {
7598                 fprintf(stderr,
7599                         "Pool name '%.*s' is longer than %d\n",
7600                         LOV_MAXPOOLNAME, pool, LOV_MAXPOOLNAME);
7601                 return 1;
7602         }
7603         return 0;
7604 }
7605
7606 /* special grace time, only notify the user when its quota is over soft limit
7607  * but doesn't block new writes until the hard limit is reached.
7608  */
7609 #define NOTIFY_GRACE            "notify"
7610 #define NOTIFY_GRACE_TIME       LQUOTA_GRACE_MASK
7611
7612 #ifndef toqb
7613 static inline __u64 lustre_stoqb(size_t space)
7614 {
7615         return (space + QIF_DQBLKSIZE - 1) >> QIF_DQBLKSIZE_BITS;
7616 }
7617 #else
7618 #define lustre_stoqb   toqb
7619 #endif
7620
7621 int lfs_setquota_times(int argc, char **argv, struct if_quotactl *qctl)
7622 {
7623         int c, rc;
7624         char *mnt, *obd_type = (char *)qctl->obd_type;
7625         struct obd_dqblk *dqb = &qctl->qc_dqblk;
7626         struct obd_dqinfo *dqi = &qctl->qc_dqinfo;
7627         struct option long_opts[] = {
7628         { .val = 'b',   .name = "block-grace",  .has_arg = required_argument },
7629         { .val = 'g',   .name = "group",        .has_arg = no_argument },
7630         { .val = 'h',   .name = "help",         .has_arg = no_argument },
7631         { .val = 'i',   .name = "inode-grace",  .has_arg = required_argument },
7632         { .val = 'p',   .name = "projid",       .has_arg = no_argument },
7633         { .val = 't',   .name = "times",        .has_arg = no_argument },
7634         { .val = 'u',   .name = "user",         .has_arg = no_argument },
7635         { .val = LFS_POOL_OPT,
7636                         .name = "pool",         .has_arg = required_argument },
7637         { .name = NULL } };
7638         int qtype;
7639
7640         qctl->qc_cmd  = LUSTRE_Q_SETINFO;
7641         qctl->qc_type = ALLQUOTA;
7642
7643         while ((c = getopt_long(argc, argv, "b:ghi:ptu",
7644                                 long_opts, NULL)) != -1) {
7645                 switch (c) {
7646                 case 'u':
7647                         qtype = USRQUOTA;
7648                         goto quota_type;
7649                 case 'g':
7650                         qtype = GRPQUOTA;
7651                         goto quota_type;
7652                 case 'p':
7653                         qtype = PRJQUOTA;
7654 quota_type:
7655                         if (qctl->qc_type != ALLQUOTA) {
7656                                 fprintf(stderr,
7657                                         "%s: -u/g/p cannot be used more than once\n",
7658                                         progname);
7659                                 return CMD_HELP;
7660                         }
7661                         qctl->qc_type = qtype;
7662                         break;
7663                 case 'b':
7664                         if (strncmp(optarg, NOTIFY_GRACE,
7665                                     strlen(NOTIFY_GRACE)) == 0) {
7666                                 dqi->dqi_bgrace = NOTIFY_GRACE_TIME;
7667                         } else {
7668                                 dqi->dqi_bgrace = str2sec(optarg);
7669                                 if (dqi->dqi_bgrace >= NOTIFY_GRACE_TIME) {
7670                                         fprintf(stderr,
7671                                                 "%s: bad block-grace: %s\n",
7672                                                 progname, optarg);
7673                                         return CMD_HELP;
7674                                 }
7675                         }
7676                         dqb->dqb_valid |= QIF_BTIME;
7677                         break;
7678                 case 'i':
7679                         if (strncmp(optarg, NOTIFY_GRACE,
7680                                     strlen(NOTIFY_GRACE)) == 0) {
7681                                 dqi->dqi_igrace = NOTIFY_GRACE_TIME;
7682                         } else {
7683                                 dqi->dqi_igrace = str2sec(optarg);
7684                                 if (dqi->dqi_igrace >= NOTIFY_GRACE_TIME) {
7685                                         fprintf(stderr,
7686                                                 "%s: bad inode-grace: %s\n",
7687                                                 progname, optarg);
7688                                         return CMD_HELP;
7689                                 }
7690                         }
7691                         dqb->dqb_valid |= QIF_ITIME;
7692                         break;
7693                 case 't': /* Yes, of course! */
7694                         break;
7695                 case LFS_POOL_OPT:
7696                         if (lfs_verify_poolarg(optarg))
7697                                 return -1;
7698                         strncpy(qctl->qc_poolname, optarg, LOV_MAXPOOLNAME);
7699                         qctl->qc_cmd  = LUSTRE_Q_SETINFOPOOL;
7700                         break;
7701                 /* getopt prints error message for us when opterr != 0 */
7702                 default:
7703                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7704                                 progname, argv[optind - 1]);
7705                         /* fallthrough */
7706                 case 'h':
7707                         return CMD_HELP;
7708                 }
7709         }
7710
7711         if (qctl->qc_type == ALLQUOTA) {
7712                 fprintf(stderr, "%s: neither -u, -g nor -p specified\n",
7713                         progname);
7714                 return CMD_HELP;
7715         }
7716
7717         if (optind != argc - 1) {
7718                 fprintf(stderr, "%s: unexpected parameter '%s'\n",
7719                         progname, argv[optind + 1]);
7720                 return CMD_HELP;
7721         }
7722
7723         mnt = argv[optind];
7724         rc = llapi_quotactl(mnt, qctl);
7725         if (rc) {
7726                 if (*obd_type)
7727                         fprintf(stderr, "%s %s ", obd_type,
7728                                 obd_uuid2str(&qctl->obd_uuid));
7729                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
7730                 return rc;
7731         }
7732
7733         return 0;
7734 }
7735
7736 #define BSLIMIT (1 << 0)
7737 #define BHLIMIT (1 << 1)
7738 #define ISLIMIT (1 << 2)
7739 #define IHLIMIT (1 << 3)
7740
7741 int lfs_setquota(int argc, char **argv)
7742 {
7743         int c, rc = 0;
7744         struct if_quotactl *qctl;
7745         char *mnt, *obd_type;
7746         struct obd_dqblk *dqb;
7747         struct option long_opts[] = {
7748         { .val = 'b',   .name = "block-softlimit",
7749                                                 .has_arg = required_argument },
7750         { .val = 'B',   .name = "block-hardlimit",
7751                                                 .has_arg = required_argument },
7752         { .val = 'd',   .name = "default",      .has_arg = no_argument },
7753         { .val = 'g',   .name = "group",        .has_arg = required_argument },
7754         { .val = 'G',   .name = "default-grp",  .has_arg = no_argument },
7755         { .val = 'h',   .name = "help",         .has_arg = no_argument },
7756         { .val = 'i',   .name = "inode-softlimit",
7757                                                 .has_arg = required_argument },
7758         { .val = 'I',   .name = "inode-hardlimit",
7759                                                 .has_arg = required_argument },
7760         { .val = 'p',   .name = "projid",       .has_arg = required_argument },
7761         { .val = 'P',   .name = "default-prj",  .has_arg = no_argument },
7762         { .val = 'u',   .name = "user",         .has_arg = required_argument },
7763         { .val = 'U',   .name = "default-usr",  .has_arg = no_argument },
7764         { .val = LFS_POOL_OPT,
7765                         .name = "pool",         .has_arg = required_argument },
7766         { .name = NULL } };
7767         unsigned int limit_mask = 0;
7768         bool use_default = false;
7769         int qtype, qctl_len;
7770
7771         qctl_len = sizeof(*qctl) + LOV_MAXPOOLNAME + 1;
7772         qctl = malloc(qctl_len);
7773         if (!qctl)
7774                 return -ENOMEM;
7775
7776         memset(qctl, 0, qctl_len);
7777         obd_type = (char *)qctl->obd_type;
7778         dqb = &qctl->qc_dqblk;
7779
7780         if (has_times_option(argc, argv)) {
7781                 rc = lfs_setquota_times(argc, argv, qctl);
7782                 goto out;
7783         }
7784
7785         qctl->qc_cmd  = LUSTRE_Q_SETQUOTA;
7786         qctl->qc_type = ALLQUOTA; /* ALLQUOTA makes no sense for setquota,
7787                                    * so it can be used as a marker that qc_type
7788                                    * isn't reinitialized from command line
7789                                    */
7790
7791         while ((c = getopt_long(argc, argv, "b:B:dg:Ghi:I:p:Pu:U",
7792                 long_opts, NULL)) != -1) {
7793                 switch (c) {
7794                 case 'U':
7795                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7796                         qtype = USRQUOTA;
7797                         qctl->qc_id = 0;
7798                         goto quota_type_def;
7799                 case 'u':
7800                         qtype = USRQUOTA;
7801                         rc = name2uid(&qctl->qc_id, optarg);
7802                         goto quota_type;
7803                 case 'G':
7804                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7805                         qtype = GRPQUOTA;
7806                         qctl->qc_id = 0;
7807                         goto quota_type_def;
7808                 case 'g':
7809                         qtype = GRPQUOTA;
7810                         rc = name2gid(&qctl->qc_id, optarg);
7811                         goto quota_type;
7812                 case 'P':
7813                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7814                         qtype = PRJQUOTA;
7815                         qctl->qc_id = 0;
7816                         goto quota_type_def;
7817                 case 'p':
7818                         qtype = PRJQUOTA;
7819                         rc = name2projid(&qctl->qc_id, optarg);
7820 quota_type:
7821                         if (rc) {
7822                                 if (str2quotaid(&qctl->qc_id, optarg)) {
7823                                         fprintf(stderr,
7824                                                 "%s setquota: invalid id '%s'\n",
7825                                                 progname, optarg);
7826                                         rc = -1;
7827                                         goto out;
7828                                 }
7829                         }
7830
7831                         if (qctl->qc_id == 0) {
7832                                 fprintf(stderr,
7833                                         "%s setquota: can't set quota for root usr/group/project.\n",
7834                                         progname);
7835                                 rc = -1;
7836                                 goto out;
7837                         }
7838
7839 quota_type_def:
7840                         if (qctl->qc_type != ALLQUOTA) {
7841                                 fprintf(stderr,
7842                                         "%s setquota: only one of -u, -U, -g, -G, -p or -P may be specified\n",
7843                                         progname);
7844                                 rc = CMD_HELP;
7845                                 goto out;
7846                         }
7847                         qctl->qc_type = qtype;
7848                         break;
7849                 case 'd':
7850                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7851                         use_default = true;
7852                         break;
7853                 case 'b':
7854                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
7855                         dqb->dqb_bsoftlimit >>= 10;
7856                         limit_mask |= BSLIMIT;
7857                         if (dqb->dqb_bsoftlimit &&
7858                             dqb->dqb_bsoftlimit <= 1024) /* <= 1M? */
7859                                 fprintf(stderr,
7860                                         "%s setquota: warning: block softlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
7861                                         progname,
7862                                         (unsigned long long)dqb->dqb_bsoftlimit,
7863                                         progname);
7864                         break;
7865                 case 'B':
7866                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
7867                         dqb->dqb_bhardlimit >>= 10;
7868                         limit_mask |= BHLIMIT;
7869                         if (dqb->dqb_bhardlimit &&
7870                             dqb->dqb_bhardlimit <= 1024) /* <= 1M? */
7871                                 fprintf(stderr,
7872                                         "%s setquota: warning: block hardlimit '%llu' smaller than minimum qunit size\n"
7873                                         "See '%s help setquota' or Lustre manual for details\n",
7874                                         progname,
7875                                         (unsigned long long)dqb->dqb_bhardlimit,
7876                                         progname);
7877                         break;
7878                 case 'i':
7879                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
7880                         limit_mask |= ISLIMIT;
7881                         if (dqb->dqb_isoftlimit &&
7882                             dqb->dqb_isoftlimit <= 1024) /* <= 1K inodes? */
7883                                 fprintf(stderr,
7884                                         "%s setquota: warning: inode softlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
7885                                         progname,
7886                                         (unsigned long long)dqb->dqb_isoftlimit,
7887                                         progname);
7888                         break;
7889                 case 'I':
7890                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
7891                         limit_mask |= IHLIMIT;
7892                         if (dqb->dqb_ihardlimit &&
7893                             dqb->dqb_ihardlimit <= 1024) /* <= 1K inodes? */
7894                                 fprintf(stderr,
7895                                         "%s setquota: warning: inode hardlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
7896                                         progname,
7897                                         (unsigned long long)dqb->dqb_ihardlimit,
7898                                         progname);
7899                         break;
7900                 case LFS_POOL_OPT:
7901                         if (lfs_verify_poolarg(optarg)) {
7902                                 rc = -1;
7903                                 goto out;
7904                         }
7905                         strncpy(qctl->qc_poolname, optarg, LOV_MAXPOOLNAME);
7906                         qctl->qc_cmd = qctl->qc_cmd == LUSTRE_Q_SETDEFAULT ?
7907                                                 LUSTRE_Q_SETDEFAULT_POOL :
7908                                                 LUSTRE_Q_SETQUOTAPOOL;
7909                         break;
7910                 default:
7911                         fprintf(stderr,
7912                                 "%s setquota: unrecognized option '%s'\n",
7913                                 progname, argv[optind - 1]);
7914                         /* fallthrough */
7915                 case 'h':
7916                         rc = CMD_HELP;
7917                         goto out;
7918                 }
7919         }
7920
7921         if (qctl->qc_type == ALLQUOTA) {
7922                 fprintf(stderr,
7923                         "%s setquota: either -u or -g must be specified\n",
7924                         progname);
7925                 rc = CMD_HELP;
7926                 goto out;
7927         }
7928
7929         if (!use_default && limit_mask == 0) {
7930                 fprintf(stderr,
7931                         "%s setquota: at least one limit must be specified\n",
7932                         progname);
7933                 rc = CMD_HELP;
7934                 goto out;
7935         }
7936
7937         if (use_default && limit_mask != 0) {
7938                 fprintf(stderr,
7939                         "%s setquota: limits should not be specified when using default quota\n",
7940                         progname);
7941                 rc = CMD_HELP;
7942                 goto out;
7943         }
7944
7945         if (use_default && qctl->qc_id == 0) {
7946                 fprintf(stderr,
7947                         "%s setquota: can not set default quota for root user/group/project\n",
7948                         progname);
7949                 rc = CMD_HELP;
7950                 goto out;
7951         }
7952
7953         if (optind != argc - 1) {
7954                 fprintf(stderr,
7955                         "%s setquota: filesystem not specified or unexpected argument '%s'\n",
7956                         progname, argv[optind]);
7957                 rc = CMD_HELP;
7958                 goto out;
7959         }
7960
7961         mnt = argv[optind];
7962
7963         if (use_default) {
7964                 dqb->dqb_bhardlimit = 0;
7965                 dqb->dqb_bsoftlimit = 0;
7966                 dqb->dqb_ihardlimit = 0;
7967                 dqb->dqb_isoftlimit = 0;
7968                 dqb->dqb_itime = 0;
7969                 dqb->dqb_btime = 0;
7970                 dqb->dqb_valid |= QIF_LIMITS | QIF_TIMES;
7971                 /* do not set inode limits for Pool Quotas */
7972                 if (qctl->qc_cmd  == LUSTRE_Q_SETDEFAULT_POOL)
7973                         dqb->dqb_valid ^= QIF_ILIMITS | QIF_ITIME;
7974         } else if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
7975                    (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
7976                 /* sigh, we can't just set blimits/ilimits */
7977                 struct if_quotactl tmp_qctl = {.qc_cmd  = LUSTRE_Q_GETQUOTA,
7978                                                .qc_type = qctl->qc_type,
7979                                                .qc_id   = qctl->qc_id};
7980
7981                 rc = llapi_quotactl(mnt, &tmp_qctl);
7982                 if (rc < 0)
7983                         goto out;
7984
7985                 if (!(limit_mask & BHLIMIT))
7986                         dqb->dqb_bhardlimit = tmp_qctl.qc_dqblk.dqb_bhardlimit;
7987                 if (!(limit_mask & BSLIMIT))
7988                         dqb->dqb_bsoftlimit = tmp_qctl.qc_dqblk.dqb_bsoftlimit;
7989                 if (!(limit_mask & IHLIMIT))
7990                         dqb->dqb_ihardlimit = tmp_qctl.qc_dqblk.dqb_ihardlimit;
7991                 if (!(limit_mask & ISLIMIT))
7992                         dqb->dqb_isoftlimit = tmp_qctl.qc_dqblk.dqb_isoftlimit;
7993
7994                 /* Keep grace times if we have got no softlimit arguments */
7995                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
7996                         dqb->dqb_valid |= QIF_BTIME;
7997                         dqb->dqb_btime = tmp_qctl.qc_dqblk.dqb_btime;
7998                 }
7999
8000                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
8001                         dqb->dqb_valid |= QIF_ITIME;
8002                         dqb->dqb_itime = tmp_qctl.qc_dqblk.dqb_itime;
8003                 }
8004         }
8005
8006         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
8007         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
8008
8009         rc = llapi_quotactl(mnt, qctl);
8010         if (rc) {
8011                 if (*obd_type)
8012                         fprintf(stderr,
8013                                 "%s setquota: cannot quotactl '%s' '%s': %s\n",
8014                                 progname, obd_type,
8015                                 obd_uuid2str(&qctl->obd_uuid), strerror(-rc));
8016                 else
8017                         fprintf(stderr,
8018                                 "%s setquota: quotactl failed: %s\n",
8019                                 progname, strerror(-rc));
8020         }
8021 out:
8022         if (rc)
8023                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
8024
8025         free(qctl);
8026         return rc;
8027 }
8028
8029 /* Converts seconds value into format string
8030  * result is returned in buf
8031  * Notes:
8032  *        1. result is in descenting order: 1w2d3h4m5s
8033  *        2. zero fields are not filled (except for p. 3): 5d1s
8034  *        3. zero seconds value is presented as "0s"
8035  */
8036 static char *__sec2str(time_t seconds, char *buf)
8037 {
8038         const char spec[] = "smhdw";
8039         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
8040         unsigned long c;
8041         char *tail = buf;
8042         int i;
8043
8044         for (i = ARRAY_SIZE(mult) - 1 ; i >= 0; i--) {
8045                 c = seconds / mult[i];
8046
8047                 if (c > 0 || (i == 0 && buf == tail))
8048                         tail += scnprintf(tail, 40-(tail-buf), "%lu%c", c,
8049                                           spec[i]);
8050
8051                 seconds %= mult[i];
8052         }
8053
8054         return tail;
8055 }
8056
8057 static void sec2str(time_t seconds, char *buf, int rc)
8058 {
8059         char *tail = buf;
8060
8061         if (rc)
8062                 *tail++ = '[';
8063
8064         tail = __sec2str(seconds, tail);
8065
8066         if (rc && tail - buf < 39) {
8067                 *tail++ = ']';
8068                 *tail++ = 0;
8069         }
8070 }
8071
8072 static void diff2str(time_t seconds, char *buf, time_t now)
8073 {
8074         buf[0] = 0;
8075         if (!seconds)
8076                 return;
8077         if (seconds <= now) {
8078                 strcpy(buf, "none");
8079                 return;
8080         }
8081         __sec2str(seconds - now, buf);
8082 }
8083
8084 static void print_quota_title(char *name, struct if_quotactl *qctl,
8085                               bool human_readable, bool show_default)
8086 {
8087         if (show_default) {
8088                 printf("Disk default %s quota:\n", qtype_name(qctl->qc_type));
8089                 printf("%15s %8s%8s%8s %8s%8s%8s\n",
8090                        "Filesystem", "bquota", "blimit", "bgrace",
8091                        "iquota", "ilimit", "igrace");
8092         } else {
8093                 printf("Disk quotas for %s %s (%cid %u):\n",
8094                        qtype_name(qctl->qc_type), name,
8095                        *qtype_name(qctl->qc_type), qctl->qc_id);
8096                 printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
8097                        "Filesystem", human_readable ? "used" : "kbytes",
8098                        "quota", "limit", "grace",
8099                        "files", "quota", "limit", "grace");
8100         }
8101 }
8102
8103 static void kbytes2str(__u64 num, char *buf, int buflen, bool h)
8104 {
8105         if (!h) {
8106                 snprintf(buf, buflen, "%ju", (uintmax_t)num);
8107         } else {
8108                 if (num >> 40)
8109                         snprintf(buf, buflen, "%5.4gP",
8110                                  (double)num / ((__u64)1 << 40));
8111                 else if (num >> 30)
8112                         snprintf(buf, buflen, "%5.4gT",
8113                                  (double)num / (1 << 30));
8114                 else if (num >> 20)
8115                         snprintf(buf, buflen, "%5.4gG",
8116                                  (double)num / (1 << 20));
8117                 else if (num >> 10)
8118                         snprintf(buf, buflen, "%5.4gM",
8119                                  (double)num / (1 << 10));
8120                 else
8121                         snprintf(buf, buflen, "%ju%s", (uintmax_t)num, "k");
8122         }
8123 }
8124
8125 #ifdef HAVE_NATIVE_CLIENT
8126 /* In the current Lustre implementation, the grace time is either the time
8127  * or the timestamp to be used after some quota ID exceeds the soft limt,
8128  * 48 bits should be enough, its high 16 bits can be used as quota flags.
8129  */
8130 #define LQUOTA_GRACE_BITS       48
8131 #define LQUOTA_GRACE_MASK       ((1ULL << LQUOTA_GRACE_BITS) - 1)
8132 #define LQUOTA_GRACE_MAX        LQUOTA_GRACE_MASK
8133 #define LQUOTA_GRACE(t)         (t & LQUOTA_GRACE_MASK)
8134 #define LQUOTA_FLAG(t)          (t >> LQUOTA_GRACE_BITS)
8135 #define LQUOTA_GRACE_FLAG(t, f) ((__u64)t | (__u64)f << LQUOTA_GRACE_BITS)
8136 #endif
8137
8138 #define STRBUF_LEN      24
8139 static void print_quota(char *mnt, struct if_quotactl *qctl, int type,
8140                         int rc, bool h, bool show_default)
8141 {
8142         time_t now;
8143
8144         time(&now);
8145
8146         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA ||
8147             qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ||
8148             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT ||
8149             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT_POOL) {
8150                 int bover = 0, iover = 0;
8151                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
8152                 char numbuf[3][STRBUF_LEN + 2]; /* 2 for brackets or wildcard */
8153                 char timebuf[40];
8154                 char strbuf[STRBUF_LEN];
8155
8156                 if (dqb->dqb_bhardlimit &&
8157                     lustre_stoqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
8158                         bover = 1;
8159                 } else if (dqb->dqb_bsoftlimit && dqb->dqb_btime) {
8160                         if (dqb->dqb_btime > now)
8161                                 bover = 2;
8162                         else
8163                                 bover = 3;
8164                 }
8165
8166                 if (dqb->dqb_ihardlimit &&
8167                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
8168                         iover = 1;
8169                 } else if (dqb->dqb_isoftlimit && dqb->dqb_itime) {
8170                         if (dqb->dqb_itime > now)
8171                                 iover = 2;
8172                         else
8173                                 iover = 3;
8174                 }
8175
8176                 if (strlen(mnt) > 15)
8177                         printf("%s\n%15s", mnt, "");
8178                 else
8179                         printf("%15s", mnt);
8180
8181                 if (bover)
8182                         diff2str(dqb->dqb_btime, timebuf, now);
8183                 else if (show_default)
8184                         snprintf(timebuf, sizeof(timebuf), "%llu",
8185                                  (unsigned long long)dqb->dqb_btime);
8186
8187                 kbytes2str(lustre_stoqb(dqb->dqb_curspace),
8188                            strbuf, sizeof(strbuf), h);
8189                 if (rc == -EREMOTEIO)
8190                         sprintf(numbuf[0], "%s*", strbuf);
8191                 else
8192                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
8193                                 "%s" : "[%s]", strbuf);
8194
8195                 kbytes2str(dqb->dqb_bsoftlimit, strbuf, sizeof(strbuf), h);
8196                 if (type == QC_GENERAL)
8197                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS) ?
8198                                 "%s" : "[%s]", strbuf);
8199                 else
8200                         sprintf(numbuf[1], "%s", "-");
8201
8202                 kbytes2str(dqb->dqb_bhardlimit, strbuf, sizeof(strbuf), h);
8203                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS) ?
8204                         "%s" : "[%s]", strbuf);
8205
8206                 if (show_default)
8207                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
8208                 else
8209                         printf(" %7s%c %6s %7s %7s",
8210                                numbuf[0], bover ? '*' : ' ', numbuf[1],
8211                                numbuf[2], bover > 1 ? timebuf : "-");
8212
8213                 if (iover)
8214                         diff2str(dqb->dqb_itime, timebuf, now);
8215                 else if (show_default)
8216                         snprintf(timebuf, sizeof(timebuf), "%llu",
8217                                  (unsigned long long)dqb->dqb_itime);
8218
8219                 snprintf(numbuf[0], sizeof(numbuf),
8220                          (dqb->dqb_valid & QIF_INODES) ? "%ju" : "[%ju]",
8221                          (uintmax_t)dqb->dqb_curinodes);
8222
8223                 if (type == QC_GENERAL)
8224                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS) ?
8225                                 "%ju" : "[%ju]",
8226                                 (uintmax_t)dqb->dqb_isoftlimit);
8227                 else
8228                         sprintf(numbuf[1], "%s", "-");
8229
8230                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
8231                         "%ju" : "[%ju]", (uintmax_t)dqb->dqb_ihardlimit);
8232
8233                 if (show_default)
8234                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
8235                 else if (type != QC_OSTIDX)
8236                         printf(" %7s%c %6s %7s %7s",
8237                                numbuf[0], iover ? '*' : ' ', numbuf[1],
8238                                numbuf[2], iover > 1 ? timebuf : "-");
8239                 else
8240                         printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
8241                 printf("\n");
8242         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO || LUSTRE_Q_GETINFOPOOL ||
8243                    qctl->qc_cmd == Q_GETOINFO) {
8244                 char bgtimebuf[40];
8245                 char igtimebuf[40];
8246
8247                 if (qctl->qc_dqinfo.dqi_bgrace == NOTIFY_GRACE_TIME)
8248                         strncpy(bgtimebuf, NOTIFY_GRACE, 40);
8249                 else
8250                         sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
8251                 if (qctl->qc_dqinfo.dqi_igrace == NOTIFY_GRACE_TIME)
8252                         strncpy(igtimebuf, NOTIFY_GRACE, 40);
8253                 else
8254                         sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
8255
8256                 printf("Block grace time: %s; Inode grace time: %s\n",
8257                        bgtimebuf, igtimebuf);
8258         }
8259 }
8260
8261 static int tgt_name2index(const char *tgtname, unsigned int *idx)
8262 {
8263         char *dash, *endp;
8264
8265         /* format is "lustre-OST0001" */
8266         dash = memchr(tgtname, '-', LUSTRE_MAXFSNAME + 1);
8267         if (!dash) {
8268                 fprintf(stderr, "wrong tgtname format '%s'\n", tgtname);
8269                 return -EINVAL;
8270         }
8271         dash += 4;
8272
8273         *idx = strtoul(dash, &endp, 16);
8274         if (*idx > 0xffff) {
8275                 fprintf(stderr, "wrong index %s\n", tgtname);
8276                 return -ERANGE;
8277         }
8278
8279         return 0;
8280 }
8281
8282 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt,
8283                            bool h, __u64 *total)
8284 {
8285         int rc = 0, rc1 = 0, count = 0, i = 0;
8286         char **list = NULL, *buffer = NULL;
8287         __u32 valid = qctl->qc_valid;
8288
8289         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL && is_mdt)
8290                 return 0;
8291
8292         /* Is it correct for the case OST0000, OST0002, OST0003 -
8293          * we will ask OST0001 that is absent and won't ask OST0003? */
8294         rc = llapi_get_obd_count(mnt, &count, is_mdt);
8295         if (rc) {
8296                 fprintf(stderr, "can not get %s count: %s\n",
8297                         is_mdt ? "mdt" : "ost", strerror(-rc));
8298                 return rc;
8299         }
8300
8301         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8302                 char fname[PATH_MAX];
8303                 char fsname[LUSTRE_MAXFSNAME + 1];
8304                 int bufsize = sizeof(struct obd_uuid) * count;
8305
8306                 rc = llapi_search_fsname(mnt, fsname);
8307                 if (rc) {
8308                         fprintf(stderr, "cannot get fsname for mountpoint %s\n",
8309                                 mnt);
8310                         goto out;
8311                 }
8312                 buffer = malloc(bufsize + sizeof(*list) * count);
8313                 if (!buffer)
8314                         return -ENOMEM;
8315                 list = (char **)(buffer + bufsize);
8316                 snprintf(fname, PATH_MAX, "%s.%s", fsname, qctl->qc_poolname);
8317                 count = llapi_get_poolmembers(fname, list, count,
8318                                               buffer, bufsize);
8319                 if (count <= 0)
8320                         goto out;
8321         }
8322
8323         for (i = 0; i < count; i++) {
8324                 if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8325                         unsigned int index;
8326
8327                         if (tgt_name2index(list[i], &index))
8328                                 continue;
8329                         qctl->qc_idx = index;
8330                 } else {
8331                         qctl->qc_idx = i;
8332                 }
8333
8334                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
8335                 rc = llapi_quotactl(mnt, qctl);
8336                 if (rc) {
8337                         /* It is remote client case. */
8338                         if (rc == -EOPNOTSUPP) {
8339                                 rc = 0;
8340                                 goto out;
8341                         }
8342
8343                         if (!rc1)
8344                                 rc1 = rc;
8345                         fprintf(stderr, "quotactl %s%d failed.\n",
8346                                 is_mdt ? "mdt" : "ost", qctl->qc_idx);
8347                         continue;
8348                 }
8349
8350                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl,
8351                             qctl->qc_valid, 0, h, false);
8352                 *total += is_mdt ? qctl->qc_dqblk.dqb_ihardlimit :
8353                                    qctl->qc_dqblk.dqb_bhardlimit;
8354         }
8355 out:
8356         if (buffer)
8357                 free(buffer);
8358         qctl->qc_valid = valid;
8359         return rc ? : rc1;
8360 }
8361
8362 static int get_print_quota(char *mnt, char *name, struct if_quotactl *qctl,
8363                            int verbose, int quiet, bool human_readable,
8364                            bool show_default)
8365 {
8366         int rc1 = 0, rc2 = 0, rc3 = 0;
8367         char *obd_type = (char *)qctl->obd_type;
8368         char *obd_uuid = (char *)qctl->obd_uuid.uuid;
8369         __u64 total_ialloc = 0, total_balloc = 0;
8370         bool use_default_for_blk = false;
8371         bool use_default_for_file = false;
8372         int inacc;
8373
8374         rc1 = llapi_quotactl(mnt, qctl);
8375         if (rc1 < 0) {
8376                 switch (rc1) {
8377                 case -ESRCH:
8378                         fprintf(stderr, "%s quotas are not enabled.\n",
8379                                 qtype_name(qctl->qc_type));
8380                         goto out;
8381                 case -EPERM:
8382                         fprintf(stderr, "Permission denied.\n");
8383                 case -ENODEV:
8384                 case -ENOENT:
8385                         /* We already got error message. */
8386                         goto out;
8387                 default:
8388                         fprintf(stderr, "Unexpected quotactl error: %s\n",
8389                                 strerror(-rc1));
8390                 }
8391         }
8392
8393         if (!show_default && qctl->qc_id == 0) {
8394                 qctl->qc_dqblk.dqb_bhardlimit = 0;
8395                 qctl->qc_dqblk.dqb_bsoftlimit = 0;
8396                 qctl->qc_dqblk.dqb_ihardlimit = 0;
8397                 qctl->qc_dqblk.dqb_isoftlimit = 0;
8398                 qctl->qc_dqblk.dqb_btime = 0;
8399                 qctl->qc_dqblk.dqb_itime = 0;
8400                 qctl->qc_dqblk.dqb_valid |= QIF_LIMITS | QIF_TIMES;
8401         }
8402
8403         if (qctl->qc_dqblk.dqb_valid & QIF_BTIME &&
8404             LQUOTA_FLAG(qctl->qc_dqblk.dqb_btime) & LQUOTA_FLAG_DEFAULT) {
8405                 use_default_for_blk = true;
8406                 qctl->qc_dqblk.dqb_btime &= LQUOTA_GRACE_MASK;
8407         }
8408
8409         if (qctl->qc_dqblk.dqb_valid & QIF_ITIME &&
8410             LQUOTA_FLAG(qctl->qc_dqblk.dqb_itime) & LQUOTA_FLAG_DEFAULT) {
8411                 use_default_for_file = true;
8412                 qctl->qc_dqblk.dqb_itime &= LQUOTA_GRACE_MASK;
8413         }
8414
8415         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8416              qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ||
8417              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT_POOL ||
8418              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) && !quiet)
8419                 print_quota_title(name, qctl, human_readable, show_default);
8420
8421         if (rc1 && *obd_type)
8422                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
8423
8424         if (qctl->qc_valid != QC_GENERAL)
8425                 mnt = "";
8426
8427         inacc = (qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8428                  qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) &&
8429                 ((qctl->qc_dqblk.dqb_valid & (QIF_LIMITS|QIF_USAGE)) !=
8430                  (QIF_LIMITS|QIF_USAGE));
8431
8432         print_quota(mnt, qctl, QC_GENERAL, rc1, human_readable, show_default);
8433
8434         if (!show_default && verbose &&
8435             qctl->qc_valid == QC_GENERAL && qctl->qc_cmd != LUSTRE_Q_GETINFO &&
8436             qctl->qc_cmd != LUSTRE_Q_GETINFOPOOL) {
8437                 char strbuf[STRBUF_LEN];
8438
8439                 rc2 = print_obd_quota(mnt, qctl, 1, human_readable,
8440                                       &total_ialloc);
8441                 rc3 = print_obd_quota(mnt, qctl, 0, human_readable,
8442                                       &total_balloc);
8443                 kbytes2str(total_balloc, strbuf, sizeof(strbuf),
8444                            human_readable);
8445                 printf("Total allocated inode limit: %ju, total allocated block limit: %s\n",
8446                        (uintmax_t)total_ialloc, strbuf);
8447         }
8448
8449         if (use_default_for_blk)
8450                 printf("%cid %u is using default block quota setting\n",
8451                        *qtype_name(qctl->qc_type), qctl->qc_id);
8452
8453         if (use_default_for_file)
8454                 printf("%cid %u is using default file quota setting\n",
8455                        *qtype_name(qctl->qc_type), qctl->qc_id);
8456
8457         if (rc1 || rc2 || rc3 || inacc)
8458                 printf("Some errors happened when getting quota info. Some devices may be not working or deactivated. The data in \"[]\" is inaccurate.\n");
8459 out:
8460         if (rc1)
8461                 return rc1;
8462         if (rc2)
8463                 return rc2;
8464         if (rc3)
8465                 return rc3;
8466         if (inacc)
8467                 return -EIO;
8468
8469         return 0;
8470 }
8471
8472 static int lfs_project(int argc, char **argv)
8473 {
8474         int ret = 0, err = 0, c, i;
8475         struct project_handle_control phc = { 0 };
8476         enum lfs_project_ops_t op;
8477
8478         phc.newline = true;
8479         phc.assign_projid = false;
8480         /* default action */
8481         op = LFS_PROJECT_LIST;
8482
8483         while ((c = getopt(argc, argv, "p:cCsdkr0")) != -1) {
8484                 switch (c) {
8485                 case 'c':
8486                         if (op != LFS_PROJECT_LIST) {
8487                                 fprintf(stderr,
8488                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8489                                         progname);
8490                                 return CMD_HELP;
8491                         }
8492
8493                         op = LFS_PROJECT_CHECK;
8494                         break;
8495                 case 'C':
8496                         if (op != LFS_PROJECT_LIST) {
8497                                 fprintf(stderr,
8498                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8499                                         progname);
8500                                 return CMD_HELP;
8501                         }
8502
8503                         op = LFS_PROJECT_CLEAR;
8504                         break;
8505                 case 's':
8506                         if (op != LFS_PROJECT_LIST) {
8507                                 fprintf(stderr,
8508                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8509                                         progname);
8510                                 return CMD_HELP;
8511                         }
8512
8513                         phc.set_inherit = true;
8514                         op = LFS_PROJECT_SET;
8515                         break;
8516                 case 'd':
8517                         phc.dironly = true;
8518                         break;
8519                 case 'k':
8520                         phc.keep_projid = true;
8521                         break;
8522                 case 'r':
8523                         phc.recursive = true;
8524                         break;
8525                 case 'p':
8526                         if (str2quotaid(&phc.projid, optarg)) {
8527                                 fprintf(stderr,
8528                                         "Invalid project ID: %s\n",
8529                                         optarg);
8530                                 return CMD_HELP;
8531                         }
8532
8533                         phc.assign_projid = true;
8534
8535                         break;
8536                 case '0':
8537                         phc.newline = false;
8538                         break;
8539                 default:
8540                         fprintf(stderr, "%s: invalid option '%c'\n",
8541                                 progname, optopt);
8542                         return CMD_HELP;
8543                 }
8544         }
8545
8546         if (phc.assign_projid && op == LFS_PROJECT_LIST) {
8547                 op = LFS_PROJECT_SET;
8548                 phc.set_projid = true;
8549         } else if (phc.assign_projid && op == LFS_PROJECT_SET) {
8550                 phc.set_projid = true;
8551         }
8552
8553         switch (op) {
8554         case LFS_PROJECT_CHECK:
8555                 if (phc.keep_projid) {
8556                         fprintf(stderr,
8557                                 "%s: '-k' is useless together with '-c'\n",
8558                                 progname);
8559                         return CMD_HELP;
8560                 }
8561                 break;
8562         case LFS_PROJECT_CLEAR:
8563                 if (!phc.newline) {
8564                         fprintf(stderr,
8565                                 "%s: '-0' is useless together with '-C'\n",
8566                                 progname);
8567                         return CMD_HELP;
8568                 }
8569                 if (phc.assign_projid) {
8570                         fprintf(stderr,
8571                                 "%s: '-p' is useless together with '-C'\n",
8572                                 progname);
8573                         return CMD_HELP;
8574                 }
8575                 break;
8576         case LFS_PROJECT_SET:
8577                 if (!phc.newline) {
8578                         fprintf(stderr,
8579                                 "%s: '-0' is useless together with '-s'\n",
8580                                 progname);
8581                         return CMD_HELP;
8582                 }
8583                 if (phc.keep_projid) {
8584                         fprintf(stderr,
8585                                 "%s: '-k' is useless together with '-s'\n",
8586                                 progname);
8587                         return CMD_HELP;
8588                 }
8589                 break;
8590         default:
8591                 if (!phc.newline) {
8592                         fprintf(stderr,
8593                                 "%s: '-0' is useless for list operations\n",
8594                                 progname);
8595                         return CMD_HELP;
8596                 }
8597                 break;
8598         }
8599
8600         argv += optind;
8601         argc -= optind;
8602         if (argc == 0) {
8603                 fprintf(stderr, "%s: missing file or directory target(s)\n",
8604                         progname);
8605                 return CMD_HELP;
8606         }
8607
8608         for (i = 0; i < argc; i++) {
8609                 switch (op) {
8610                 case LFS_PROJECT_CHECK:
8611                         err = lfs_project_check(argv[i], &phc);
8612                         break;
8613                 case LFS_PROJECT_LIST:
8614                         err = lfs_project_list(argv[i], &phc);
8615                         break;
8616                 case LFS_PROJECT_CLEAR:
8617                         err = lfs_project_clear(argv[i], &phc);
8618                         break;
8619                 case LFS_PROJECT_SET:
8620                         err = lfs_project_set(argv[i], &phc);
8621                         break;
8622                 default:
8623                         break;
8624                 }
8625                 if (err && !ret)
8626                         ret = err;
8627         }
8628
8629         return ret;
8630 }
8631
8632 static int lfs_quota(int argc, char **argv)
8633 {
8634         int c;
8635         char *mnt, *name = NULL;
8636         struct if_quotactl *qctl;
8637         char *obd_uuid;
8638         int rc = 0, rc1 = 0, verbose = 0, quiet = 0;
8639         __u32 valid = QC_GENERAL, idx = 0;
8640         bool human_readable = false;
8641         bool show_default = false;
8642         int qtype;
8643         bool show_pools = false;
8644         struct option long_opts[] = {
8645         { .val = LFS_POOL_OPT, .name = "pool", .has_arg = optional_argument },
8646         { .name = NULL } };
8647         char **poollist = NULL;
8648         char *buf = NULL;
8649         int poolcount, i;
8650
8651         qctl = calloc(1, sizeof(*qctl) + LOV_MAXPOOLNAME + 1);
8652         if (!qctl)
8653                 return -ENOMEM;
8654
8655         qctl->qc_cmd = LUSTRE_Q_GETQUOTA;
8656         qctl->qc_type = ALLQUOTA;
8657         obd_uuid = (char *)qctl->obd_uuid.uuid;
8658
8659         while ((c = getopt_long(argc, argv, "gGi:I:o:pPqtuUvh",
8660                 long_opts, NULL)) != -1) {
8661                 switch (c) {
8662                 case 'U':
8663                         show_default = true;
8664                 case 'u':
8665                         qtype = USRQUOTA;
8666                         goto quota_type;
8667                 case 'G':
8668                         show_default = true;
8669                 case 'g':
8670                         qtype = GRPQUOTA;
8671                         goto quota_type;
8672                 case 'P':
8673                         show_default = true;
8674                 case 'p':
8675                         qtype = PRJQUOTA;
8676 quota_type:
8677                         if (qctl->qc_type != ALLQUOTA) {
8678                                 fprintf(stderr,
8679                                         "%s quota: only one of -u, -g, or -p may be specified\n",
8680                                         progname);
8681                                 rc = CMD_HELP;
8682                                 goto out;
8683                         }
8684                         qctl->qc_type = qtype;
8685                         break;
8686                 case 't':
8687                         qctl->qc_cmd = LUSTRE_Q_GETINFO;
8688                         break;
8689                 case 'o':
8690                         valid = qctl->qc_valid = QC_UUID;
8691                         snprintf(obd_uuid, sizeof(*obd_uuid), "%s", optarg);
8692                         break;
8693                 case 'i':
8694                         valid = qctl->qc_valid = QC_MDTIDX;
8695                         idx = qctl->qc_idx = atoi(optarg);
8696                         if (idx == 0 && *optarg != '0') {
8697                                 fprintf(stderr,
8698                                         "%s quota: invalid MDT index '%s'\n",
8699                                         progname, optarg);
8700                                 rc = CMD_HELP;
8701                                 goto out;
8702                         }
8703                         break;
8704                 case 'I':
8705                         valid = qctl->qc_valid = QC_OSTIDX;
8706                         idx = qctl->qc_idx = atoi(optarg);
8707                         if (idx == 0 && *optarg != '0') {
8708                                 fprintf(stderr,
8709                                         "%s quota: invalid OST index '%s'\n",
8710                                         progname, optarg);
8711                                 rc = CMD_HELP;
8712                                 goto out;
8713                         }
8714                         break;
8715                 case 'v':
8716                         verbose = 1;
8717                         break;
8718                 case 'q':
8719                         quiet = 1;
8720                         break;
8721                 case 'h':
8722                         human_readable = true;
8723                         break;
8724                 case LFS_POOL_OPT:
8725                         if ((!optarg) && (argv[optind] != NULL) &&
8726                                 (argv[optind][0] != '-') &&
8727                                 (argv[optind][0] != '/')) {
8728                                 optarg = argv[optind++];
8729                                 if (lfs_verify_poolarg(optarg)) {
8730                                         rc = -EINVAL;
8731                                         goto out;
8732                                 }
8733                                 strncpy(qctl->qc_poolname, optarg,
8734                                         LOV_MAXPOOLNAME);
8735                                 if (qctl->qc_cmd == LUSTRE_Q_GETINFO)
8736                                         qctl->qc_cmd = LUSTRE_Q_GETINFOPOOL;
8737                                 else
8738                                         qctl->qc_cmd = LUSTRE_Q_GETQUOTAPOOL;
8739                                 break;
8740                         }
8741
8742                         /* optarg is NULL */
8743                         show_pools = true;
8744                         qctl->qc_cmd = LUSTRE_Q_GETQUOTAPOOL;
8745                         break;
8746                 default:
8747                         fprintf(stderr, "%s quota: unrecognized option '%s'\n",
8748                                 progname, argv[optind - 1]);
8749                         rc = CMD_HELP;
8750                         goto out;
8751                 }
8752         }
8753
8754         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
8755         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8756              qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) &&
8757              qctl->qc_type == ALLQUOTA &&
8758              optind == argc - 1 && !show_default) {
8759                 qctl->qc_idx = idx;
8760
8761                 for (qtype = USRQUOTA; qtype <= GRPQUOTA; qtype++) {
8762                         qctl->qc_type = qtype;
8763                         qctl->qc_valid = valid;
8764                         if (qtype == USRQUOTA) {
8765                                 qctl->qc_id = geteuid();
8766                                 rc = uid2name(&name, qctl->qc_id);
8767                         } else {
8768                                 qctl->qc_id = getegid();
8769                                 rc = gid2name(&name, qctl->qc_id);
8770                                 memset(&qctl->qc_dqblk, 0,
8771                                        sizeof(qctl->qc_dqblk));
8772                         }
8773                         if (rc)
8774                                 name = "<unknown>";
8775                         mnt = argv[optind];
8776                         rc1 = get_print_quota(mnt, name, qctl, verbose, quiet,
8777                                               human_readable, show_default);
8778                         if (rc1 && !rc)
8779                                 rc = rc1;
8780                 }
8781                 goto out;
8782         /* lfs quota -u username /path/to/lustre/mount */
8783         } else if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8784                    qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8785                 /* options should be followed by u/g-name and mntpoint */
8786                 if ((!show_default && optind + 2 != argc) ||
8787                     (show_default && optind + 1 != argc) ||
8788                     qctl->qc_type == ALLQUOTA) {
8789                         fprintf(stderr,
8790                                 "%s quota: name and mount point must be specified\n",
8791                                 progname);
8792                         rc = CMD_HELP;
8793                         goto out;
8794                 }
8795
8796                 if (!show_default) {
8797                         name = argv[optind++];
8798                         switch (qctl->qc_type) {
8799                         case USRQUOTA:
8800                                 rc = name2uid(&qctl->qc_id, name);
8801                                 break;
8802                         case GRPQUOTA:
8803                                 rc = name2gid(&qctl->qc_id, name);
8804                                 break;
8805                         case PRJQUOTA:
8806                                 rc = name2projid(&qctl->qc_id, name);
8807                                 break;
8808                         default:
8809                                 rc = -ENOTSUP;
8810                                 break;
8811                         }
8812                 } else {
8813                         qctl->qc_valid = QC_GENERAL;
8814                         qctl->qc_cmd = qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ?
8815                                         LUSTRE_Q_GETDEFAULT_POOL :
8816                                         LUSTRE_Q_GETDEFAULT;
8817                         qctl->qc_id = 0;
8818                 }
8819
8820                 if (rc) {
8821                         if (str2quotaid(&qctl->qc_id, name)) {
8822                                 fprintf(stderr, "%s quota: invalid id '%s'\n",
8823                                         progname, name);
8824                                 rc = CMD_HELP;
8825                                 goto out;
8826                         }
8827                 }
8828         } else if (optind + 1 != argc || qctl->qc_type == ALLQUOTA) {
8829                 fprintf(stderr, "%s quota: missing quota info argument(s)\n",
8830                         progname);
8831                 rc = CMD_HELP;
8832                 goto out;
8833         }
8834
8835         mnt = argv[optind];
8836         if (show_pools) {
8837                 char *p;
8838
8839                 i = 0;
8840                 rc = llapi_get_poolbuf(mnt, &buf, &poollist, &poolcount);
8841                 if (rc)
8842                         goto out;
8843
8844                 for (i = 0; i < poolcount; i++) {
8845                         p = memchr(poollist[i], '.', MAXNAMLEN);
8846                         if (!p) {
8847                                 fprintf(stderr, "bad string format %.*s\n",
8848                                         MAXNAMLEN, poollist[i]);
8849                                 rc = -EINVAL;
8850                                 goto out;
8851                         }
8852                         p++;
8853                         printf("Quotas for pool: %s\n", p);
8854                         strncpy(qctl->qc_poolname, p, LOV_MAXPOOLNAME);
8855                         rc = get_print_quota(mnt, name, qctl, verbose, quiet,
8856                                              human_readable, show_default);
8857                         if (rc)
8858                                 break;
8859                 }
8860                 goto out;
8861         }
8862
8863         rc = get_print_quota(mnt, name, qctl, verbose, quiet,
8864                              human_readable, show_default);
8865 out:
8866         free(buf);
8867         free(qctl);
8868         return rc;
8869 }
8870 #endif /* HAVE_SYS_QUOTA_H! */
8871
8872 static int flushctx_ioctl(char *mp)
8873 {
8874         int fd, rc;
8875
8876         fd = open(mp, O_RDONLY);
8877         if (fd == -1) {
8878                 fprintf(stderr, "flushctx: error open %s: %s\n",
8879                         mp, strerror(errno));
8880                 return -1;
8881         }
8882
8883         rc = ioctl(fd, LL_IOC_FLUSHCTX);
8884         if (rc == -1)
8885                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
8886                         mp, strerror(errno));
8887
8888         close(fd);
8889         return rc;
8890 }
8891
8892 static int lfs_flushctx(int argc, char **argv)
8893 {
8894         int     kdestroy = 0, reap = 0, c;
8895         char    mntdir[PATH_MAX] = {'\0'};
8896         int     index = 0;
8897         int     rc = 0;
8898
8899         while ((c = getopt(argc, argv, "kr")) != -1) {
8900                 switch (c) {
8901                 case 'k':
8902                         kdestroy = 1;
8903                         break;
8904                 case 'r':
8905                         reap = 1;
8906                         break;
8907                 default:
8908                         fprintf(stderr,
8909                                 "error: %s: option '-%c' unrecognized\n",
8910                                 argv[0], c);
8911                         return CMD_HELP;
8912                 }
8913         }
8914
8915         if (kdestroy) {
8916                 rc = system("kdestroy > /dev/null");
8917                 if (rc) {
8918                         rc = WEXITSTATUS(rc);
8919                         fprintf(stderr,
8920                                 "error destroying tickets: %d, continuing\n",
8921                                 rc);
8922                 }
8923         }
8924
8925         if (optind >= argc) {
8926                 /* flush for all mounted lustre fs. */
8927                 while (!llapi_search_mounts(NULL, index++, mntdir, NULL)) {
8928                         /* Check if we have a mount point */
8929                         if (mntdir[0] == '\0')
8930                                 continue;
8931
8932                         if (flushctx_ioctl(mntdir))
8933                                 rc = -1;
8934
8935                         mntdir[0] = '\0'; /* avoid matching in next loop */
8936                 }
8937         } else {
8938                 /* flush fs as specified */
8939                 while (optind < argc) {
8940                         if (flushctx_ioctl(argv[optind++]))
8941                                 rc = -1;
8942                 }
8943         }
8944
8945         if (reap) {
8946                 rc = system("keyctl reap > /dev/null");
8947                 if (rc != 0) {
8948                         rc = WEXITSTATUS(rc);
8949                         fprintf(stderr, "error reaping keyring: %d\n", rc);
8950                 }
8951         }
8952
8953         return rc;
8954 }
8955
8956 static int lfs_changelog(int argc, char **argv)
8957 {
8958         void *changelog_priv;
8959         struct changelog_rec *rec;
8960         long long startrec = 0, endrec = 0;
8961         char *mdd;
8962         struct option long_opts[] = {
8963                 { .val = 'f', .name = "follow", .has_arg = no_argument },
8964                 { .name = NULL } };
8965         char short_opts[] = "f";
8966         int rc, follow = 0;
8967
8968         while ((rc = getopt_long(argc, argv, short_opts,
8969                 long_opts, NULL)) != -1) {
8970                 switch (rc) {
8971                 case 'f':
8972                         follow++;
8973                         break;
8974                 default:
8975                         fprintf(stderr,
8976                                 "%s changelog: unrecognized option '%s'\n",
8977                                 progname, argv[optind - 1]);
8978                         return CMD_HELP;
8979                 }
8980         }
8981         if (optind >= argc) {
8982                 fprintf(stderr, "%s changelog: mdtname must be specified\n",
8983                         progname);
8984                 return CMD_HELP;
8985         }
8986
8987         mdd = argv[optind++];
8988         if (argc > optind) {
8989                 errno = 0;
8990                 startrec = strtoll(argv[optind++], NULL, 10);
8991                 if (errno != 0 || startrec < 0) {
8992                         fprintf(stderr,
8993                                 "%s changelog: bad startrec\n",
8994                                 progname);
8995                         return CMD_HELP;
8996                 }
8997         }
8998
8999         if (argc > optind) {
9000                 errno = 0;
9001                 endrec = strtoll(argv[optind++], NULL, 10);
9002                 if (errno != 0 || endrec < 0) {
9003                         fprintf(stderr,
9004                                 "%s changelog: bad endrec\n",
9005                                 progname);
9006                         return CMD_HELP;
9007                 }
9008         }
9009
9010         rc = llapi_changelog_start(&changelog_priv,
9011                                    CHANGELOG_FLAG_BLOCK |
9012                                    CHANGELOG_FLAG_JOBID |
9013                                    CHANGELOG_FLAG_EXTRA_FLAGS |
9014                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
9015                                    mdd, startrec);
9016         if (rc < 0) {
9017                 fprintf(stderr, "%s changelog: cannot start changelog: %s\n",
9018                         progname, strerror(errno = -rc));
9019                 return rc;
9020         }
9021
9022         rc = llapi_changelog_set_xflags(changelog_priv,
9023                                         CHANGELOG_EXTRA_FLAG_UIDGID |
9024                                         CHANGELOG_EXTRA_FLAG_NID |
9025                                         CHANGELOG_EXTRA_FLAG_OMODE |
9026                                         CHANGELOG_EXTRA_FLAG_XATTR);
9027         if (rc < 0) {
9028                 fprintf(stderr,
9029                         "%s changelog: cannot set xflags for changelog: %s\n",
9030                         progname, strerror(errno = -rc));
9031                 return rc;
9032         }
9033
9034         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
9035                 time_t secs;
9036                 struct tm ts;
9037
9038                 if (endrec && rec->cr_index > endrec) {
9039                         llapi_changelog_free(&rec);
9040                         break;
9041                 }
9042                 if (rec->cr_index < startrec) {
9043                         llapi_changelog_free(&rec);
9044                         continue;
9045                 }
9046
9047                 secs = rec->cr_time >> 30;
9048                 gmtime_r(&secs, &ts);
9049                 printf("%ju %02d%-5s %02d:%02d:%02d.%09d %04d.%02d.%02d "
9050                        "0x%x t="DFID, (uintmax_t)rec->cr_index, rec->cr_type,
9051                        changelog_type2str(rec->cr_type),
9052                        ts.tm_hour, ts.tm_min, ts.tm_sec,
9053                        (int)(rec->cr_time & ((1 << 30) - 1)),
9054                        ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday,
9055                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
9056
9057                 if (rec->cr_flags & CLF_JOBID) {
9058                         struct changelog_ext_jobid *jid =
9059                                 changelog_rec_jobid(rec);
9060
9061                         if (jid->cr_jobid[0] != '\0')
9062                                 printf(" j=%s", jid->cr_jobid);
9063                 }
9064
9065                 if (rec->cr_flags & CLF_EXTRA_FLAGS) {
9066                         struct changelog_ext_extra_flags *ef =
9067                                 changelog_rec_extra_flags(rec);
9068
9069                         printf(" ef=0x%llx",
9070                                (unsigned long long)ef->cr_extra_flags);
9071
9072                         if (ef->cr_extra_flags & CLFE_UIDGID) {
9073                                 struct changelog_ext_uidgid *uidgid =
9074                                         changelog_rec_uidgid(rec);
9075
9076                                 printf(" u=%llu:%llu",
9077                                        (unsigned long long)uidgid->cr_uid,
9078                                        (unsigned long long)uidgid->cr_gid);
9079                         }
9080                         if (ef->cr_extra_flags & CLFE_NID) {
9081                                 struct changelog_ext_nid *nid =
9082                                         changelog_rec_nid(rec);
9083
9084                                 printf(" nid=%s",
9085                                        libcfs_nid2str(nid->cr_nid));
9086                         }
9087
9088                         if (ef->cr_extra_flags & CLFE_OPEN) {
9089                                 struct changelog_ext_openmode *omd =
9090                                         changelog_rec_openmode(rec);
9091                                 char mode[] = "---";
9092
9093                                 /* exec mode must be exclusive */
9094                                 if (omd->cr_openflags & MDS_FMODE_EXEC) {
9095                                         mode[2] = 'x';
9096                                 } else {
9097                                         if (omd->cr_openflags & MDS_FMODE_READ)
9098                                                 mode[0] = 'r';
9099                                         if (omd->cr_openflags &
9100                                             (MDS_FMODE_WRITE |
9101                                              MDS_OPEN_TRUNC |
9102                                              MDS_OPEN_APPEND))
9103                                                 mode[1] = 'w';
9104                                 }
9105
9106                                 if (strcmp(mode, "---") != 0)
9107                                         printf(" m=%s", mode);
9108                         }
9109
9110                         if (ef->cr_extra_flags & CLFE_XATTR) {
9111                                 struct changelog_ext_xattr *xattr =
9112                                         changelog_rec_xattr(rec);
9113
9114                                 if (xattr->cr_xattr[0] != '\0')
9115                                         printf(" x=%s", xattr->cr_xattr);
9116                         }
9117                 }
9118
9119                 if (!fid_is_zero(&rec->cr_pfid))
9120                         printf(" p="DFID, PFID(&rec->cr_pfid));
9121                 if (rec->cr_namelen)
9122                         printf(" %.*s", rec->cr_namelen,
9123                                changelog_rec_name(rec));
9124
9125                 if (rec->cr_flags & CLF_RENAME) {
9126                         struct changelog_ext_rename *rnm =
9127                                 changelog_rec_rename(rec);
9128
9129                         if (!fid_is_zero(&rnm->cr_sfid))
9130                                 printf(" s="DFID" sp="DFID" %.*s",
9131                                        PFID(&rnm->cr_sfid),
9132                                        PFID(&rnm->cr_spfid),
9133                                        (int)changelog_rec_snamelen(rec),
9134                                        changelog_rec_sname(rec));
9135                 }
9136                 printf("\n");
9137
9138                 llapi_changelog_free(&rec);
9139         }
9140
9141         llapi_changelog_fini(&changelog_priv);
9142
9143         if (rc < 0)
9144                 fprintf(stderr, "%s changelog: cannot access changelog: %s\n",
9145                         progname, strerror(errno = -rc));
9146
9147         return (rc == 1 ? 0 : rc);
9148 }
9149
9150 static int lfs_changelog_clear(int argc, char **argv)
9151 {
9152         long long endrec;
9153         int rc;
9154
9155         if (argc != 4)
9156                 return CMD_HELP;
9157
9158         errno = 0;
9159         endrec = strtoll(argv[3], NULL, 10);
9160         if (errno != 0 || endrec < 0) {
9161                 fprintf(stderr,
9162                         "%s: bad endrec '%s'\n",
9163                         argv[0], argv[3]);
9164                 return CMD_HELP;
9165         }
9166
9167         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
9168
9169         if (rc == -EINVAL)
9170                 fprintf(stderr, "%s: record out of range: %llu\n",
9171                         argv[0], endrec);
9172         else if (rc == -ENOENT)
9173                 fprintf(stderr, "%s: no changelog user: %s\n",
9174                         argv[0], argv[2]);
9175         else if (rc)
9176                 fprintf(stderr, "%s error: %s\n", argv[0],
9177                         strerror(-rc));
9178
9179         if (rc)
9180                 errno = -rc;
9181
9182         return rc;
9183 }
9184
9185 static void rstripc(char *str, int c)
9186 {
9187         char *end = str + strlen(str);
9188
9189         for (; str < end && end[-1] == c; --end)
9190                 end[-1] = '\0';
9191 }
9192
9193 static int lfs_fid2path(int argc, char **argv)
9194 {
9195         struct option long_opts[] = {
9196                 { .val = 'c',   .name = "cur",  .has_arg = no_argument },
9197                 { .val = 'c',   .name = "current",      .has_arg = no_argument },
9198                 { .val = 'c',   .name = "print-link",   .has_arg = no_argument },
9199                 { .val = 'f',   .name = "print-fid",    .has_arg = no_argument },
9200                 { .val = 'l',   .name = "link", .has_arg = required_argument },
9201                 { .name = NULL } };
9202         char short_opts[] = "cfl:pr:";
9203         bool print_link = false;
9204         bool print_fid = false;
9205         bool print_mnt_dir;
9206         char mnt_dir[PATH_MAX] = "";
9207         int mnt_fd = -1;
9208         char *path_or_fsname;
9209         long long recno = -1;
9210         int linkno = -1;
9211         char *endptr = NULL;
9212         int rc = 0;
9213         int c;
9214         int i;
9215
9216         while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
9217                 switch (c) {
9218                 case 'c':
9219                         print_link = true;
9220                         break;
9221                 case 'f':
9222                         print_fid = true;
9223                         break;
9224                 case 'l':
9225                         errno = 0;
9226                         linkno = strtol(optarg, &endptr, 10);
9227                         if (errno != 0 || *endptr != '\0' || linkno < 0) {
9228                                 fprintf(stderr,
9229                                         "%s fid2path: invalid linkno '%s'\n",
9230                                         progname, optarg);
9231                                 return CMD_HELP;
9232                         }
9233                         break;
9234                 case 'r':
9235                         /* recno is something to do with changelogs
9236                          * that was never implemented. We just pass it
9237                          * through for the MDT to ignore.
9238                          */
9239                         errno = 0;
9240                         recno = strtoll(optarg, &endptr, 10);
9241                         if (errno != 0 || *endptr != '\0' || recno < 0) {
9242                                 fprintf(stderr,
9243                                         "%s fid2path: invalid recno '%s'\n",
9244                                         progname, optarg);
9245                                 return CMD_HELP;
9246                         }
9247                         break;
9248                 default:
9249                         fprintf(stderr,
9250                                 "%s fid2path: unrecognized option '%s'\n",
9251                                 progname, argv[optind - 1]);
9252                         return CMD_HELP;
9253                 }
9254         }
9255
9256         if (argc - optind < 2) {
9257                 fprintf(stderr,
9258                         "Usage: %s fid2path FSNAME|ROOT FID...\n",
9259                         progname);
9260                 return CMD_HELP;
9261         }
9262
9263         path_or_fsname = argv[optind];
9264
9265         if (*path_or_fsname == '/') {
9266                 print_mnt_dir = true;
9267                 rc = llapi_search_mounts(path_or_fsname, 0, mnt_dir, NULL);
9268         } else {
9269                 print_mnt_dir = false;
9270                 rc = llapi_search_rootpath(mnt_dir, path_or_fsname);
9271         }
9272
9273         if (rc < 0) {
9274                 fprintf(stderr,
9275                         "%s fid2path: cannot resolve mount point for '%s': %s\n",
9276                         progname, path_or_fsname, strerror(-rc));
9277                 goto out;
9278         }
9279
9280         mnt_fd = open(mnt_dir, O_RDONLY | O_DIRECTORY);
9281         if (mnt_fd < 0) {
9282                 fprintf(stderr,
9283                         "%s fid2path: cannot open mount point for '%s': %s\n",
9284                         progname, path_or_fsname, strerror(-rc));
9285                 goto out;
9286         }
9287
9288         /* Strip trailing slashes from mnt_dir. */
9289         rstripc(mnt_dir + 1, '/');
9290
9291         for (i = optind + 1; i < argc; i++) {
9292                 const char *fid_str = argv[i];
9293                 struct lu_fid fid;
9294                 int rc2;
9295
9296                 rc2 = llapi_fid_parse(fid_str, &fid, NULL);
9297                 if (rc2 < 0) {
9298                         fprintf(stderr,
9299                                 "%s fid2path: invalid FID '%s'\n",
9300                                 progname, fid_str);
9301                         if (rc == 0)
9302                                 rc = rc2;
9303
9304                         continue;
9305                 }
9306
9307                 int linktmp = (linkno >= 0) ? linkno : 0;
9308                 while (1) {
9309                         int oldtmp = linktmp;
9310                         long long rectmp = recno;
9311                         char path_buf[PATH_MAX];
9312
9313                         rc2 = llapi_fid2path_at(mnt_fd, &fid,
9314                                 path_buf, sizeof(path_buf), &rectmp, &linktmp);
9315                         if (rc2 < 0) {
9316                                 fprintf(stderr,
9317                                         "%s fid2path: cannot find %s %s: %s\n",
9318                                         progname, path_or_fsname, fid_str,
9319                                         strerror(-rc2));
9320                                 if (rc == 0)
9321                                         rc = rc2;
9322                                 break;
9323                         }
9324
9325                         if (print_fid)
9326                                 printf("%s ", fid_str);
9327
9328                         if (print_link)
9329                                 printf("%d ", linktmp);
9330
9331                         /* You may think this looks wrong or weird (and it is!)
9332                          * but we are actually trying to preserve the old quirky
9333                          * behaviors (enforced by our old quirky tests!) that
9334                          * make lfs so much fun to work on:
9335                          *
9336                          *   lustre 0x200000007:0x1:0x0 => "/"
9337                          *   /mnt/lustre 0x200000007:0x1:0x0 => "/mnt/lustre//"
9338                          *
9339                          * Note that llapi_fid2path() returns "" for the root
9340                          * FID. */
9341
9342                         printf("%s%s%s\n",
9343                                print_mnt_dir ? mnt_dir : "",
9344                                (print_mnt_dir || *path_buf == '\0') ? "/" : "",
9345                                path_buf);
9346
9347                         if (linkno >= 0)
9348                                 /* specified linkno */
9349                                 break;
9350
9351                         if (oldtmp == linktmp)
9352                                 /* no more links */
9353                                 break;
9354                 }
9355         }
9356 out:
9357         if (!(mnt_fd < 0))
9358                 close(mnt_fd);
9359
9360         return rc;
9361 }
9362
9363 static int lfs_path2fid(int argc, char **argv)
9364 {
9365         struct option long_opts[] = {
9366                 { .val = 'p', .name = "parents", .has_arg = no_argument },
9367                 { .name = NULL } };
9368         char            **path;
9369         const char        short_opts[] = "p";
9370         const char       *sep = "";
9371         struct lu_fid     fid;
9372         int               rc = 0;
9373         bool              show_parents = false;
9374
9375         while ((rc = getopt_long(argc, argv, short_opts,
9376                                  long_opts, NULL)) != -1) {
9377                 switch (rc) {
9378                 case 'p':
9379                         show_parents = true;
9380                         break;
9381                 default:
9382                         fprintf(stderr,
9383                                 "%s path2fid: unrecognized option '%s'\n",
9384                                 progname, argv[optind - 1]);
9385                         return CMD_HELP;
9386                 }
9387         }
9388
9389         if (optind > argc - 1) {
9390                 fprintf(stderr, "%s path2fid: FILE... must be specified\n",
9391                         progname);
9392                 return CMD_HELP;
9393         } else if (optind < argc - 1) {
9394                 sep = ": ";
9395         }
9396
9397         rc = 0;
9398         for (path = argv + optind; *path != NULL; path++) {
9399                 int err = 0;
9400
9401                 if (!show_parents) {
9402                         err = llapi_path2fid(*path, &fid);
9403                         if (!err)
9404                                 printf("%s%s"DFID"\n",
9405                                        *sep != '\0' ? *path : "", sep,
9406                                        PFID(&fid));
9407                 } else {
9408                         char            name[NAME_MAX + 1];
9409                         unsigned int    linkno = 0;
9410
9411                         while ((err = llapi_path2parent(*path, linkno, &fid,
9412                                                 name, sizeof(name))) == 0) {
9413                                 if (*sep != '\0' && linkno == 0)
9414                                         printf("%s%s", *path, sep);
9415
9416                                 printf("%s"DFID"/%s", linkno != 0 ? "\t" : "",
9417                                        PFID(&fid), name);
9418                                 linkno++;
9419                         }
9420
9421                         /* err == -ENODATA is end-of-loop */
9422                         if (linkno > 0 && err == -ENODATA) {
9423                                 printf("\n");
9424                                 err = 0;
9425                         }
9426                 }
9427
9428                 if (err) {
9429                         fprintf(stderr,
9430                                 "%s path2fid: cannot get %sfid for '%s': %s\n",
9431                                 progname, show_parents ? "parent " : "", *path,
9432                                 strerror(-err));
9433                         if (rc == 0) {
9434                                 rc = err;
9435                                 errno = -err;
9436                         }
9437                 }
9438         }
9439
9440         return rc;
9441 }
9442
9443 #define MAX_ERRNO       4095
9444 #define IS_ERR_VALUE(x) ((unsigned long)(x) >= (unsigned long)-MAX_ERRNO)
9445
9446 static int lfs_rmfid_and_show_errors(const char *device, struct fid_array *fa)
9447 {
9448         int rc, rc2, k;
9449
9450         rc = llapi_rmfid(device, fa);
9451         if (rc < 0) {
9452                 fprintf(stderr, "%s rmfid: cannot remove FIDs: %s\n",
9453                         progname, strerror(-rc));
9454                 return rc;
9455         }
9456
9457         for (k = 0; k < fa->fa_nr; k++) {
9458                 rc2 = (__s32)fa->fa_fids[k].f_ver;
9459                 if (!IS_ERR_VALUE(rc2))
9460                         continue;
9461
9462                 if (rc == 0)
9463                         rc = rc2;
9464
9465                 fa->fa_fids[k].f_ver = 0;
9466                 fprintf(stderr, "%s rmfid: cannot remove "DFID": %s\n",
9467                         progname, PFID(&fa->fa_fids[k]), strerror(-rc2));
9468         }
9469
9470         return rc;
9471 }
9472
9473 static int lfs_rmfid(int argc, char **argv)
9474 {
9475         char *fidstr, *device;
9476         int rc = 0, rc2, nr;
9477         struct fid_array *fa;
9478
9479         if (optind > argc - 1) {
9480                 fprintf(stderr, "%s rmfid: missing dirname\n", progname);
9481                 return CMD_HELP;
9482         }
9483
9484         device = argv[optind++];
9485
9486         nr = argc - optind;
9487         fa = malloc(offsetof(struct fid_array, fa_fids[nr + 1]));
9488         if (!fa)
9489                 return -ENOMEM;
9490
9491         fa->fa_nr = 0;
9492         rc = 0;
9493         while (optind < argc) {
9494                 int found;
9495
9496                 fidstr = argv[optind++];
9497                 while (*fidstr == '[')
9498                         fidstr++;
9499                 found = sscanf(fidstr, SFID, RFID(&fa->fa_fids[fa->fa_nr]));
9500                 if (found != 3) {
9501                         fprintf(stderr, "unrecognized FID: %s\n",
9502                                 argv[optind - 1]);
9503                         exit(1);
9504                 }
9505                 fa->fa_nr++;
9506                 if (fa->fa_nr == OBD_MAX_FIDS_IN_ARRAY) {
9507                         /* start another batch */
9508                         rc2 = lfs_rmfid_and_show_errors(device, fa);
9509                         if (rc2 && !rc)
9510                                 rc = rc2;
9511                         fa->fa_nr = 0;
9512                 }
9513         }
9514         if (fa->fa_nr) {
9515                 rc2 = lfs_rmfid_and_show_errors(device, fa);
9516                 if (rc2 && !rc)
9517                         rc = rc2;
9518         }
9519
9520         return rc;
9521 }
9522
9523 static int lfs_data_version(int argc, char **argv)
9524 {
9525         int data_version_flags = LL_DV_RD_FLUSH; /* Read by default */
9526         __u64 data_version;
9527         char *path;
9528         int fd;
9529         int rc;
9530         int c;
9531
9532         if (argc < 2) {
9533                 fprintf(stderr, "%s: FILE must be specified\n",
9534                         progname);
9535                 return CMD_HELP;
9536         }
9537
9538         while ((c = getopt(argc, argv, "hnrw")) != -1) {
9539                 switch (c) {
9540                 case 'n':
9541                         data_version_flags = 0;
9542                         break;
9543                 case 'r':
9544                         data_version_flags |= LL_DV_RD_FLUSH;
9545                         break;
9546                 case 'w':
9547                         data_version_flags |= LL_DV_WR_FLUSH;
9548                         break;
9549                 default:
9550                         fprintf(stderr,
9551                                 "%s data_version: unrecognized option '%s'\n",
9552                                 progname, argv[optind - 1]);
9553                         /* fallthrough */
9554                 case 'h':
9555                         return CMD_HELP;
9556                 }
9557         }
9558         if (optind == argc) {
9559                 fprintf(stderr, "%s data_version: FILE must be specified\n",
9560                         progname);
9561                 return CMD_HELP;
9562         }
9563
9564         path = argv[optind];
9565         fd = open(path, O_RDONLY);
9566         if (fd < 0) {
9567                 rc = -errno;
9568                 fprintf(stderr, "%s data_version: cannot open file '%s': %s\n",
9569                         progname, path, strerror(-rc));
9570                 return rc;
9571         }
9572
9573         rc = llapi_get_data_version(fd, &data_version, data_version_flags);
9574         if (rc < 0)
9575                 fprintf(stderr,
9576                         "%s data_version: cannot get version for '%s': %s\n",
9577                         progname, path, strerror(-rc));
9578         else
9579                 printf("%ju" "\n", (uintmax_t)data_version);
9580
9581         close(fd);
9582         return rc;
9583 }
9584
9585 static int lfs_hsm_state(int argc, char **argv)
9586 {
9587         int rc;
9588         int i = 1;
9589         char *path;
9590         struct hsm_user_state hus;
9591
9592         if (argc < 2)
9593                 return CMD_HELP;
9594
9595         do {
9596                 path = argv[i];
9597
9598                 rc = llapi_hsm_state_get(path, &hus);
9599                 if (rc) {
9600                         fprintf(stderr, "can't get hsm state for %s: %s\n",
9601                                 path, strerror(errno = -rc));
9602                         return rc;
9603                 }
9604
9605                 /* Display path name and status flags */
9606                 printf("%s: (0x%08x)", path, hus.hus_states);
9607
9608                 if (hus.hus_states & HS_RELEASED)
9609                         printf(" released");
9610                 if (hus.hus_states & HS_EXISTS)
9611                         printf(" exists");
9612                 if (hus.hus_states & HS_DIRTY)
9613                         printf(" dirty");
9614                 if (hus.hus_states & HS_ARCHIVED)
9615                         printf(" archived");
9616                 /* Display user-settable flags */
9617                 if (hus.hus_states & HS_NORELEASE)
9618                         printf(" never_release");
9619                 if (hus.hus_states & HS_NOARCHIVE)
9620                         printf(" never_archive");
9621                 if (hus.hus_states & HS_LOST)
9622                         printf(" lost_from_hsm");
9623
9624                 if (hus.hus_archive_id != 0)
9625                         printf(", archive_id:%d", hus.hus_archive_id);
9626                 printf("\n");
9627
9628         } while (++i < argc);
9629
9630         return 0;
9631 }
9632
9633 #define LFS_HSM_SET   0
9634 #define LFS_HSM_CLEAR 1
9635
9636 /**
9637  * Generic function to set or clear HSM flags.
9638  * Used by hsm_set and hsm_clear.
9639  *
9640  * @mode  if LFS_HSM_SET, set the flags, if LFS_HSM_CLEAR, clear the flags.
9641  */
9642 static int lfs_hsm_change_flags(int argc, char **argv, int mode)
9643 {
9644         struct option long_opts[] = {
9645         { .val = 'A',   .name = "archived",     .has_arg = no_argument },
9646         { .val = 'a',   .name = "noarchive",    .has_arg = no_argument },
9647         { .val = 'd',   .name = "dirty",        .has_arg = no_argument },
9648         { .val = 'e',   .name = "exists",       .has_arg = no_argument },
9649         { .val = 'h',   .name = "help",         .has_arg = no_argument },
9650         { .val = 'i',   .name = "archive-id",   .has_arg = required_argument },
9651         { .val = 'l',   .name = "lost",         .has_arg = no_argument },
9652         { .val = 'r',   .name = "norelease",    .has_arg = no_argument },
9653         { .name = NULL } };
9654         __u64 mask = 0;
9655         int c, rc;
9656         char *path;
9657         __u32 archive_id = 0;
9658         char *end = NULL;
9659
9660         if (argc < 3)
9661                 return CMD_HELP;
9662
9663         while ((c = getopt_long(argc, argv, "aAdehi:lr",
9664                                 long_opts, NULL)) != -1) {
9665                 switch (c) {
9666                 case 'l':
9667                         mask |= HS_LOST;
9668                         break;
9669                 case 'a':
9670                         mask |= HS_NOARCHIVE;
9671                         break;
9672                 case 'A':
9673                         mask |= HS_ARCHIVED;
9674                         break;
9675                 case 'r':
9676                         mask |= HS_NORELEASE;
9677                         break;
9678                 case 'd':
9679                         mask |= HS_DIRTY;
9680                         break;
9681                 case 'e':
9682                         mask |= HS_EXISTS;
9683                         break;
9684                 case 'i':
9685                         errno = 0;
9686                         archive_id = strtol(optarg, &end, 10);
9687                         if (errno != 0 || *end != '\0' || archive_id < 0) {
9688                                 fprintf(stderr,
9689                                         "%s: invalid archive_id: '%s'\n",
9690                                         progname, end);
9691                                 return CMD_HELP;
9692                         }
9693                         break;
9694                 default:
9695                         fprintf(stderr, "%s: unrecognized option '%s'\n",
9696                                 progname, argv[optind - 1]);
9697                         /* fallthrough */
9698                 case 'h':
9699                         return CMD_HELP;
9700                 }
9701         }
9702
9703         /* User should have specified a flag */
9704         if (mask == 0)
9705                 return CMD_HELP;
9706
9707         while (optind < argc) {
9708                 path = argv[optind];
9709
9710                 /* If mode == 0, this means we apply the mask. */
9711                 if (mode == LFS_HSM_SET)
9712                         rc = llapi_hsm_state_set(path, mask, 0, archive_id);
9713                 else
9714                         rc = llapi_hsm_state_set(path, 0, mask, 0);
9715
9716                 if (rc != 0) {
9717                         fprintf(stderr, "Can't change hsm flags for %s: %s\n",
9718                                 path, strerror(errno = -rc));
9719                         return rc;
9720                 }
9721                 optind++;
9722         }
9723
9724         return 0;
9725 }
9726
9727 static int lfs_hsm_action(int argc, char **argv)
9728 {
9729         int                              rc;
9730         int                              i = 1;
9731         char                            *path;
9732         struct hsm_current_action        hca;
9733         struct hsm_extent                he;
9734         enum hsm_user_action             hua;
9735         enum hsm_progress_states         hps;
9736
9737         if (argc < 2)
9738                 return CMD_HELP;
9739
9740         do {
9741                 path = argv[i];
9742
9743                 rc = llapi_hsm_current_action(path, &hca);
9744                 if (rc) {
9745                         fprintf(stderr, "can't get hsm action for %s: %s\n",
9746                                 path, strerror(errno = -rc));
9747                         return rc;
9748                 }
9749                 he = hca.hca_location;
9750                 hua = hca.hca_action;
9751                 hps = hca.hca_state;
9752
9753                 printf("%s: %s", path, hsm_user_action2name(hua));
9754
9755                 /* Skip file without action */
9756                 if (hca.hca_action == HUA_NONE) {
9757                         printf("\n");
9758                         continue;
9759                 }
9760
9761                 printf(" %s ", hsm_progress_state2name(hps));
9762
9763                 if ((hps == HPS_RUNNING) &&
9764                     (hua == HUA_ARCHIVE || hua == HUA_RESTORE))
9765                         printf("(%llu bytes moved)\n",
9766                                (unsigned long long)he.length);
9767                 else if ((he.offset + he.length) == LUSTRE_EOF)
9768                         printf("(from %llu to EOF)\n",
9769                                (unsigned long long)he.offset);
9770                 else
9771                         printf("(from %llu to %llu)\n",
9772                                (unsigned long long)he.offset,
9773                                (unsigned long long)(he.offset + he.length));
9774
9775         } while (++i < argc);
9776
9777         return 0;
9778 }
9779
9780 static int lfs_hsm_set(int argc, char **argv)
9781 {
9782         return lfs_hsm_change_flags(argc, argv, LFS_HSM_SET);
9783 }
9784
9785 static int lfs_hsm_clear(int argc, char **argv)
9786 {
9787         return lfs_hsm_change_flags(argc, argv, LFS_HSM_CLEAR);
9788 }
9789
9790 /**
9791  * Check file state and return its fid, to be used by lfs_hsm_request().
9792  *
9793  * \param[in]     file      Path to file to check
9794  * \param[in,out] fid       Pointer to allocated lu_fid struct.
9795  * \param[in,out] last_dev  Pointer to last device id used.
9796  *
9797  * \return 0 on success.
9798  */
9799 static int lfs_hsm_prepare_file(const char *file, struct lu_fid *fid,
9800                                 dev_t *last_dev)
9801 {
9802         struct stat     st;
9803         int             rc;
9804
9805         rc = lstat(file, &st);
9806         if (rc) {
9807                 fprintf(stderr, "Cannot stat %s: %s\n", file, strerror(errno));
9808                 return -errno;
9809         }
9810         /*
9811          * Checking for regular file as archiving as posix copytool
9812          * rejects archiving files other than regular files
9813          */
9814         if (!S_ISREG(st.st_mode)) {
9815                 fprintf(stderr, "error: \"%s\" is not a regular file\n", file);
9816                 return CMD_HELP;
9817         }
9818         /* A request should be ... */
9819         if (*last_dev != st.st_dev && *last_dev != 0) {
9820                 fprintf(stderr,
9821                         "All files should be on the same filesystem: %s\n",
9822                         file);
9823                 return -EINVAL;
9824         }
9825         *last_dev = st.st_dev;
9826
9827         rc = llapi_path2fid(file, fid);
9828         if (rc) {
9829                 fprintf(stderr, "Cannot read FID of %s: %s\n",
9830                         file, strerror(-rc));
9831                 return rc;
9832         }
9833         return 0;
9834 }
9835
9836 /* Fill an HSM HUR item with a given file name.
9837  *
9838  * If mntpath is set, then the filename is actually a FID, and no
9839  * lookup on the filesystem will be performed.
9840  *
9841  * \param[in]  hur         the user request to fill
9842  * \param[in]  idx         index of the item inside the HUR to fill
9843  * \param[in]  mntpath     mountpoint of Lustre
9844  * \param[in]  fname       filename (if mtnpath is NULL)
9845  *                         or FID (if mntpath is set)
9846  * \param[in]  last_dev    pointer to last device id used
9847  *
9848  * \retval 0 on success
9849  * \retval CMD_HELP or a negative errno on error
9850  */
9851 static int fill_hur_item(struct hsm_user_request *hur, unsigned int idx,
9852                          const char *mntpath, const char *fname,
9853                          dev_t *last_dev)
9854 {
9855         struct hsm_user_item *hui = &hur->hur_user_item[idx];
9856         int rc;
9857
9858         hui->hui_extent.length = -1;
9859
9860         if (mntpath) {
9861                 rc = llapi_fid_parse(fname, &hui->hui_fid, NULL);
9862                 if (rc)
9863                         fprintf(stderr, "hsm: '%s' is not a valid FID\n",
9864                                 fname);
9865         } else {
9866                 rc = lfs_hsm_prepare_file(fname, &hui->hui_fid, last_dev);
9867         }
9868
9869         if (rc == 0)
9870                 hur->hur_request.hr_itemcount++;
9871
9872         return rc;
9873 }
9874
9875 static int lfs_hsm_request(int argc, char **argv, int action)
9876 {
9877         struct option long_opts[] = {
9878         { .val = 'a',   .name = "archive",      .has_arg = required_argument },
9879         { .val = 'D',   .name = "data",         .has_arg = required_argument },
9880         { .val = 'h',   .name = "help",         .has_arg = no_argument },
9881         { .val = 'l',   .name = "filelist",     .has_arg = required_argument },
9882         { .val = 'm',   .name = "mntpath",      .has_arg = required_argument },
9883         { .name = NULL } };
9884         dev_t last_dev = 0;
9885         struct hsm_user_request *hur, *oldhur;
9886         int c, i;
9887         size_t len;
9888         int nbfile;
9889         char *line = NULL;
9890         char *filelist = NULL;
9891         char fullpath[PATH_MAX];
9892         char *opaque = NULL;
9893         int opaque_len = 0;
9894         int archive_id = 0;
9895         FILE *fp;
9896         int nbfile_alloc = 0;
9897         char *some_file = NULL;
9898         char *mntpath = NULL;
9899         int rc;
9900
9901         if (argc < 2)
9902                 return CMD_HELP;
9903
9904         while ((c = getopt_long(argc, argv, "a:D:hl:m:",
9905                                 long_opts, NULL)) != -1) {
9906                 switch (c) {
9907                 case 'l':
9908                         filelist = optarg;
9909                         break;
9910                 case 'D':
9911                         opaque = optarg;
9912                         break;
9913                 case 'a':
9914                         if (action != HUA_ARCHIVE &&
9915                             action != HUA_REMOVE) {
9916                                 fprintf(stderr,
9917                                         "error: -a is supported only when archiving or removing\n");
9918                                 return CMD_HELP;
9919                         }
9920                         archive_id = atoi(optarg);
9921                         break;
9922                 case 'm':
9923                         if (!some_file) {
9924                                 mntpath = optarg;
9925                                 some_file = strdup(optarg);
9926                         }
9927                         break;
9928                 default:
9929                         fprintf(stderr, "%s: unrecognized option '%s'\n",
9930                                 progname, argv[optind - 1]);
9931                         /* fallthrough */
9932                 case 'h':
9933                         return CMD_HELP;
9934                 }
9935         }
9936
9937         /* All remaining args are files, so we have at least nbfile */
9938         nbfile = argc - optind;
9939
9940         if ((nbfile == 0) && (!filelist))
9941                 return CMD_HELP;
9942
9943         if (opaque)
9944                 opaque_len = strlen(opaque);
9945
9946         /*
9947          * Alloc the request structure with enough place to store all files
9948          * from command line.
9949          */
9950         hur = llapi_hsm_user_request_alloc(nbfile, opaque_len);
9951         if (!hur) {
9952                 fprintf(stderr, "Cannot create the request: %s\n",
9953                         strerror(errno));
9954                 return errno;
9955         }
9956         nbfile_alloc = nbfile;
9957
9958         hur->hur_request.hr_action = action;
9959         hur->hur_request.hr_archive_id = archive_id;
9960         hur->hur_request.hr_flags = 0;
9961
9962         /* All remaining args are files, add them */
9963         if (nbfile != 0 && some_file == NULL)
9964                 some_file = strdup(argv[optind]);
9965
9966         for (i = 0; i < nbfile; i++) {
9967                 rc = fill_hur_item(hur, i, mntpath, argv[optind + i],
9968                                    &last_dev);
9969                 if (rc)
9970                         goto out_free;
9971         }
9972
9973         /* from here stop using nb_file, use hur->hur_request.hr_itemcount */
9974
9975         /* If a filelist was specified, read the filelist from it. */
9976         if (filelist) {
9977                 fp = fopen(filelist, "r");
9978                 if (!fp) {
9979                         fprintf(stderr, "Cannot read the file list %s: %s\n",
9980                                 filelist, strerror(errno));
9981                         rc = -errno;
9982                         goto out_free;
9983                 }
9984
9985                 while ((rc = getline(&line, &len, fp)) != -1) {
9986                         /*
9987                          * If allocated buffer was too small, get something
9988                          * larger
9989                          */
9990                         if (nbfile_alloc <= hur->hur_request.hr_itemcount) {
9991                                 ssize_t size;
9992
9993                                 nbfile_alloc = nbfile_alloc * 2 + 1;
9994                                 oldhur = hur;
9995                                 hur = llapi_hsm_user_request_alloc(nbfile_alloc,
9996                                                                    opaque_len);
9997                                 if (!hur) {
9998                                         fprintf(stderr,
9999                                                 "hsm: cannot allocate the request: %s\n",
10000                                                 strerror(errno));
10001                                         hur = oldhur;
10002                                         rc = -errno;
10003                                         fclose(fp);
10004                                         goto out_free;
10005                                 }
10006                                 size = hur_len(oldhur);
10007                                 if (size < 0) {
10008                                         fprintf(stderr,
10009                                                 "hsm: cannot allocate %u files + %u bytes data\n",
10010                                                 oldhur->hur_request.hr_itemcount,
10011                                                 oldhur->hur_request.hr_data_len);
10012                                         free(hur);
10013                                         hur = oldhur;
10014                                         rc = -E2BIG;
10015                                         fclose(fp);
10016                                         goto out_free;
10017                                 }
10018                                 memcpy(hur, oldhur, size);
10019                                 free(oldhur);
10020                         }
10021
10022                         /* Chop CR */
10023                         if (line[strlen(line) - 1] == '\n')
10024                                 line[strlen(line) - 1] = '\0';
10025
10026                         rc = fill_hur_item(hur, hur->hur_request.hr_itemcount,
10027                                            mntpath, line, &last_dev);
10028                         if (rc) {
10029                                 fclose(fp);
10030                                 goto out_free;
10031                         }
10032
10033                         if (!some_file) {
10034                                 some_file = line;
10035                                 line = NULL;
10036                         }
10037                 }
10038
10039                 rc = fclose(fp);
10040                 free(line);
10041         }
10042
10043         /* If a --data was used, add it to the request */
10044         hur->hur_request.hr_data_len = opaque_len;
10045         if (opaque)
10046                 memcpy(hur_data(hur), opaque, opaque_len);
10047
10048         /* Send the HSM request */
10049         if (realpath(some_file, fullpath) == NULL) {
10050                 fprintf(stderr, "Could not find path '%s': %s\n",
10051                         some_file, strerror(errno));
10052         }
10053         rc = llapi_hsm_request(fullpath, hur);
10054         if (rc) {
10055                 fprintf(stderr, "Cannot send HSM request (use of %s): %s\n",
10056                         some_file, strerror(-rc));
10057                 goto out_free;
10058         }
10059
10060 out_free:
10061         free(some_file);
10062         free(hur);
10063         return rc;
10064 }
10065
10066 static int lfs_hsm_archive(int argc, char **argv)
10067 {
10068         return lfs_hsm_request(argc, argv, HUA_ARCHIVE);
10069 }
10070
10071 static int lfs_hsm_restore(int argc, char **argv)
10072 {
10073         return lfs_hsm_request(argc, argv, HUA_RESTORE);
10074 }
10075
10076 static int lfs_hsm_release(int argc, char **argv)
10077 {
10078         return lfs_hsm_request(argc, argv, HUA_RELEASE);
10079 }
10080
10081 static int lfs_hsm_remove(int argc, char **argv)
10082 {
10083         return lfs_hsm_request(argc, argv, HUA_REMOVE);
10084 }
10085
10086 static int lfs_hsm_cancel(int argc, char **argv)
10087 {
10088         return lfs_hsm_request(argc, argv, HUA_CANCEL);
10089 }
10090
10091 static int lfs_swap_layouts(int argc, char **argv)
10092 {
10093         if (argc != 3)
10094                 return CMD_HELP;
10095
10096         return llapi_swap_layouts(argv[1], argv[2], 0, 0,
10097                                   SWAP_LAYOUTS_KEEP_MTIME |
10098                                   SWAP_LAYOUTS_KEEP_ATIME);
10099 }
10100
10101 static const char *const ladvise_names[] = LU_LADVISE_NAMES;
10102
10103 static const char *const lock_mode_names[] = LOCK_MODE_NAMES;
10104
10105 int lfs_get_mode(const char *string)
10106 {
10107         enum lock_mode_user mode;
10108
10109         for (mode = 0; mode < ARRAY_SIZE(lock_mode_names); mode++) {
10110                 if (lock_mode_names[mode] == NULL)
10111                         continue;
10112                 if (strcasecmp(string, lock_mode_names[mode]) == 0)
10113                         return mode;
10114         }
10115
10116         return -EINVAL;
10117 }
10118
10119 static enum lu_ladvise_type lfs_get_ladvice(const char *string)
10120 {
10121         enum lu_ladvise_type advice;
10122
10123         for (advice = 0;
10124              advice < ARRAY_SIZE(ladvise_names); advice++) {
10125                 if (ladvise_names[advice] == NULL)
10126                         continue;
10127                 if (strcmp(string, ladvise_names[advice]) == 0)
10128                         return advice;
10129         }
10130
10131         return LU_LADVISE_INVALID;
10132 }
10133
10134 static int lfs_ladvise(int argc, char **argv)
10135 {
10136         struct option long_opts[] = {
10137         { .val = 'a',   .name = "advice",       .has_arg = required_argument },
10138         { .val = 'b',   .name = "background",   .has_arg = no_argument },
10139         { .val = 'e',   .name = "end",          .has_arg = required_argument },
10140         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10141         { .val = 'l',   .name = "length",       .has_arg = required_argument },
10142         { .val = 'm',   .name = "mode",         .has_arg = required_argument },
10143         { .val = 's',   .name = "start",        .has_arg = required_argument },
10144         { .val = 'u',   .name = "unset",        .has_arg = no_argument },
10145         { .name = NULL } };
10146         struct llapi_lu_ladvise advice;
10147         enum lu_ladvise_type advice_type = LU_LADVISE_INVALID;
10148         unsigned long long start = 0;
10149         unsigned long long end = LUSTRE_EOF;
10150         unsigned long long length = 0;
10151         unsigned long long size_units;
10152         unsigned long long flags = 0;
10153         int c, fd, rc = 0;
10154         const char *path;
10155         int mode = 0;
10156
10157         optind = 0;
10158         while ((c = getopt_long(argc, argv, "a:be:hl:m:s:u",
10159                                 long_opts, NULL)) != -1) {
10160                 switch (c) {
10161                 case 'a':
10162                         advice_type = lfs_get_ladvice(optarg);
10163                         if (advice_type == LU_LADVISE_INVALID) {
10164                                 fprintf(stderr,
10165                                         "%s: invalid advice type '%s'\n",
10166                                         progname, optarg);
10167                                 fprintf(stderr, "Valid types:");
10168
10169                                 for (advice_type = 0;
10170                                      advice_type < ARRAY_SIZE(ladvise_names);
10171                                      advice_type++) {
10172                                         if (ladvise_names[advice_type] == NULL)
10173                                                 continue;
10174                                         fprintf(stderr, " %s",
10175                                                 ladvise_names[advice_type]);
10176                                 }
10177                                 fprintf(stderr, "\n");
10178
10179                                 return CMD_HELP;
10180                         }
10181                         break;
10182                 case 'b':
10183                         flags |= LF_ASYNC;
10184                         break;
10185                 case 'u':
10186                         flags |= LF_UNSET;
10187                         break;
10188                 case 'e':
10189                         size_units = 1;
10190                         rc = llapi_parse_size(optarg, &end,
10191                                               &size_units, 0);
10192                         if (rc) {
10193                                 fprintf(stderr, "%s: bad end offset '%s'\n",
10194                                         argv[0], optarg);
10195                                 return CMD_HELP;
10196                         }
10197                         break;
10198                 case 's':
10199                         size_units = 1;
10200                         rc = llapi_parse_size(optarg, &start,
10201                                               &size_units, 0);
10202                         if (rc) {
10203                                 fprintf(stderr,
10204                                         "%s: bad start offset '%s'\n",
10205                                         argv[0], optarg);
10206                                 return CMD_HELP;
10207                         }
10208                         break;
10209                 case 'l':
10210                         size_units = 1;
10211                         rc = llapi_parse_size(optarg, &length,
10212                                               &size_units, 0);
10213                         if (rc) {
10214                                 fprintf(stderr, "%s: bad length '%s'\n",
10215                                         argv[0], optarg);
10216                                 return CMD_HELP;
10217                         }
10218                         break;
10219                 case 'm':
10220                         mode = lfs_get_mode(optarg);
10221                         if (mode < 0) {
10222                                 fprintf(stderr,
10223                                         "%s: bad mode '%s', valid modes are READ or WRITE\n",
10224                                         argv[0], optarg);
10225                                 return CMD_HELP;
10226                         }
10227                         break;
10228                 default:
10229                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10230                                 progname, argv[optind - 1]);
10231                         /* fallthrough */
10232                 case 'h':
10233                         return CMD_HELP;
10234                 }
10235         }
10236
10237         if (advice_type == LU_LADVISE_INVALID) {
10238                 fprintf(stderr, "%s: please give an advice type\n", argv[0]);
10239                 fprintf(stderr, "Valid types:");
10240                 for (advice_type = 0; advice_type < ARRAY_SIZE(ladvise_names);
10241                      advice_type++) {
10242                         if (ladvise_names[advice_type] == NULL)
10243                                 continue;
10244                         fprintf(stderr, " %s", ladvise_names[advice_type]);
10245                 }
10246                 fprintf(stderr, "\n");
10247                 return CMD_HELP;
10248         }
10249
10250         if (advice_type == LU_LADVISE_LOCKNOEXPAND) {
10251                 fprintf(stderr,
10252                         "%s: Lock no expand advice is a per file descriptor advice, so when called from lfs, it does nothing.\n",
10253                         argv[0]);
10254                 return CMD_HELP;
10255         }
10256
10257         if (argc <= optind) {
10258                 fprintf(stderr, "%s: please give one or more file names\n",
10259                         argv[0]);
10260                 return CMD_HELP;
10261         }
10262
10263         if (end != LUSTRE_EOF && length != 0 && end != start + length) {
10264                 fprintf(stderr, "%s: conflicting arguments of -l and -e\n",
10265                         argv[0]);
10266                 return CMD_HELP;
10267         }
10268
10269         if (end == LUSTRE_EOF && length != 0)
10270                 end = start + length;
10271
10272         if (end <= start) {
10273                 fprintf(stderr, "%s: range [%llu, %llu] is invalid\n",
10274                         argv[0], start, end);
10275                 return CMD_HELP;
10276         }
10277
10278         if (advice_type != LU_LADVISE_LOCKAHEAD && mode != 0) {
10279                 fprintf(stderr, "%s: mode is only valid with lockahead\n",
10280                         argv[0]);
10281                 return CMD_HELP;
10282         }
10283
10284         if (advice_type == LU_LADVISE_LOCKAHEAD && mode == 0) {
10285                 fprintf(stderr, "%s: mode is required with lockahead\n",
10286                         argv[0]);
10287                 return CMD_HELP;
10288         }
10289
10290         while (optind < argc) {
10291                 int rc2;
10292
10293                 path = argv[optind++];
10294
10295                 fd = open(path, O_RDONLY);
10296                 if (fd < 0) {
10297                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10298                                 argv[0], path, strerror(errno));
10299                         rc2 = -errno;
10300                         goto next;
10301                 }
10302
10303                 advice.lla_start = start;
10304                 advice.lla_end = end;
10305                 advice.lla_advice = advice_type;
10306                 advice.lla_value1 = 0;
10307                 advice.lla_value2 = 0;
10308                 advice.lla_value3 = 0;
10309                 advice.lla_value4 = 0;
10310                 if (advice_type == LU_LADVISE_LOCKAHEAD) {
10311                         advice.lla_lockahead_mode = mode;
10312                         advice.lla_peradvice_flags = flags;
10313                 }
10314
10315                 rc2 = llapi_ladvise(fd, flags, 1, &advice);
10316                 close(fd);
10317                 if (rc2 < 0) {
10318                         fprintf(stderr,
10319                                 "%s: cannot give advice '%s' to file '%s': %s\n",
10320                                 argv[0], ladvise_names[advice_type],
10321                                 path, strerror(errno));
10322
10323                         goto next;
10324                 }
10325
10326 next:
10327                 if (rc == 0 && rc2 < 0)
10328                         rc = rc2;
10329         }
10330         return rc;
10331 }
10332
10333 static const char *const heat_names[] = LU_HEAT_NAMES;
10334
10335 static int lfs_heat_get(int argc, char **argv)
10336 {
10337         struct lu_heat *heat;
10338         int rc = 0, rc2;
10339         char *path;
10340         int fd;
10341         int i;
10342
10343         if (argc <= 1)
10344                 return CMD_HELP;
10345
10346         heat = calloc(sizeof(*heat) + sizeof(__u64) * OBD_HEAT_COUNT, 1);
10347         if (!heat) {
10348                 fprintf(stderr, "%s: memory allocation failed\n", argv[0]);
10349                 return -ENOMEM;
10350         }
10351
10352         optind = 1;
10353         while (optind < argc) {
10354                 path = argv[optind++];
10355
10356                 fd = open(path, O_RDONLY);
10357                 if (fd < 0) {
10358                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10359                                 argv[0], path, strerror(errno));
10360                         rc2 = -errno;
10361                         goto next;
10362                 }
10363
10364                 heat->lh_count = OBD_HEAT_COUNT;
10365                 rc2 = llapi_heat_get(fd, heat);
10366                 close(fd);
10367                 if (rc2 < 0) {
10368                         fprintf(stderr,
10369                                 "%s: cannot get heat of file '%s': %s\n",
10370                                 argv[0], path, strerror(errno));
10371                         goto next;
10372                 }
10373
10374                 printf("flags: %x\n", heat->lh_flags);
10375                 for (i = 0; i < heat->lh_count; i++)
10376                         printf("%s: %llu\n", heat_names[i],
10377                                (unsigned long long)heat->lh_heat[i]);
10378 next:
10379                 if (rc == 0 && rc2 < 0)
10380                         rc = rc2;
10381         }
10382
10383         free(heat);
10384         return rc;
10385 }
10386
10387 static int lfs_heat_set(int argc, char **argv)
10388 {
10389         struct option long_opts[] = {
10390         { .val = 'c',   .name = "clear",        .has_arg = no_argument },
10391         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10392         { .val = 'o',   .name = "off",          .has_arg = no_argument },
10393         { .val = 'O',   .name = "on",           .has_arg = no_argument },
10394         { .name = NULL } };
10395         enum lu_heat_flag flags = 0;
10396         int rc = 0, rc2;
10397         char *path;
10398         int fd;
10399         int c;
10400
10401         if (argc <= 1)
10402                 return CMD_HELP;
10403
10404         optind = 0;
10405         while ((c = getopt_long(argc, argv, "choO", long_opts, NULL)) != -1) {
10406                 switch (c) {
10407                 case 'c':
10408                         flags |= LU_HEAT_FLAG_CLEAR;
10409                         break;
10410                 case 'o':
10411                         flags |= LU_HEAT_FLAG_CLEAR;
10412                         flags |= LU_HEAT_FLAG_OFF;
10413                         break;
10414                 case 'O':
10415                         flags &= ~LU_HEAT_FLAG_OFF;
10416                         break;
10417                 default:
10418                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10419                                 progname, argv[optind - 1]);
10420                         /* fallthrough */
10421                 case 'h':
10422                         return CMD_HELP;
10423                 }
10424         }
10425
10426         if (argc <= optind) {
10427                 fprintf(stderr, "%s: please give one or more file names\n",
10428                         argv[0]);
10429                 return CMD_HELP;
10430         }
10431
10432         while (optind < argc) {
10433                 path = argv[optind++];
10434
10435                 fd = open(path, O_RDONLY);
10436                 if (fd < 0) {
10437                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10438                                 argv[0], path, strerror(errno));
10439                         rc2 = -errno;
10440                         goto next;
10441                 }
10442
10443                 rc2 = llapi_heat_set(fd, flags);
10444                 close(fd);
10445                 if (rc2 < 0) {
10446                         fprintf(stderr,
10447                                 "%s: cannot setflags heat of file '%s': %s\n",
10448                                 argv[0], path, strerror(errno));
10449                         goto next;
10450                 }
10451 next:
10452                 if (rc == 0 && rc2 < 0)
10453                         rc = rc2;
10454         }
10455         return rc;
10456 }
10457
10458 /**
10459  * The input string contains a comma delimited list of component ids and
10460  * ranges, for example "1,2-4,7".
10461  */
10462 static int parse_mirror_ids(__u16 *ids, int size, char *arg)
10463 {
10464         bool end_of_loop = false;
10465         char *ptr = NULL;
10466         int nr = 0;
10467         int rc;
10468
10469         if (!arg)
10470                 return -EINVAL;
10471
10472         while (!end_of_loop) {
10473                 int start_index;
10474                 int end_index;
10475                 int i;
10476                 char *endptr = NULL;
10477
10478                 rc = -EINVAL;
10479                 ptr = strchrnul(arg, ',');
10480                 end_of_loop = *ptr == '\0';
10481                 *ptr = '\0';
10482
10483                 start_index = strtol(arg, &endptr, 0);
10484                 if (endptr == arg) /* no data at all */
10485                         break;
10486                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
10487                         break;
10488                 if (start_index < 0)
10489                         break;
10490
10491                 end_index = start_index;
10492                 if (*endptr == '-') {
10493                         end_index = strtol(endptr + 1, &endptr, 0);
10494                         if (*endptr != '\0')
10495                                 break;
10496                         if (end_index < start_index)
10497                                 break;
10498                 }
10499
10500                 for (i = start_index; i <= end_index && size > 0; i++) {
10501                         int j;
10502
10503                         /* remove duplicate */
10504                         for (j = 0; j < nr; j++) {
10505                                 if (ids[j] == i)
10506                                         break;
10507                         }
10508                         if (j == nr) { /* no duplicate */
10509                                 ids[nr++] = i;
10510                                 --size;
10511                         }
10512                 }
10513
10514                 if (size == 0 && i < end_index)
10515                         break;
10516
10517                 *ptr = ',';
10518                 arg = ++ptr;
10519                 rc = 0;
10520         }
10521         if (!end_of_loop && ptr)
10522                 *ptr = ',';
10523
10524         return rc < 0 ? rc : nr;
10525 }
10526
10527 /**
10528  * struct verify_mirror_id - Mirror id to be verified.
10529  * @mirror_id:   A specified mirror id.
10530  * @is_valid_id: @mirror_id is valid or not in the mirrored file.
10531  */
10532 struct verify_mirror_id {
10533         __u16 mirror_id;
10534         bool is_valid_id;
10535 };
10536
10537 /**
10538  * compare_mirror_ids() - Compare mirror ids.
10539  * @layout: Mirror component list.
10540  * @cbdata: Callback data in verify_mirror_id structure.
10541  *
10542  * This is a callback function called by llapi_layout_comp_iterate()
10543  * to compare the specified mirror id with the one in the current
10544  * component of @layout. If they are the same, then the specified
10545  * mirror id is valid.
10546  *
10547  * Return: a negative error code on failure or
10548  *         LLAPI_LAYOUT_ITER_CONT: Proceed iteration
10549  *         LLAPI_LAYOUT_ITER_STOP: Stop iteration
10550  */
10551 static inline
10552 int compare_mirror_ids(struct llapi_layout *layout, void *cbdata)
10553 {
10554         struct verify_mirror_id *mirror_id_cbdata =
10555                                  (struct verify_mirror_id *)cbdata;
10556         uint32_t mirror_id;
10557         int rc = 0;
10558
10559         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
10560         if (rc < 0) {
10561                 rc = -errno;
10562                 fprintf(stderr,
10563                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
10564                         progname, strerror(errno));
10565                 return rc;
10566         }
10567
10568         if (mirror_id_cbdata->mirror_id == mirror_id) {
10569                 mirror_id_cbdata->is_valid_id = true;
10570                 return LLAPI_LAYOUT_ITER_STOP;
10571         }
10572
10573         return LLAPI_LAYOUT_ITER_CONT;
10574 }
10575
10576 /**
10577  * verify_mirror_ids() - Verify specified mirror ids.
10578  * @fname:      Mirrored file name.
10579  * @mirror_ids: Specified mirror ids to be verified.
10580  * @ids_nr:     Number of specified mirror ids.
10581  *
10582  * This function verifies that specified @mirror_ids are valid
10583  * in the mirrored file @fname.
10584  *
10585  * Return: 0 on success or a negative error code on failure.
10586  */
10587 static inline
10588 int verify_mirror_ids(const char *fname, __u16 *mirror_ids, int ids_nr)
10589 {
10590         struct llapi_layout *layout = NULL;
10591         struct verify_mirror_id mirror_id_cbdata = { 0 };
10592         struct stat stbuf;
10593         uint32_t flr_state;
10594         int i;
10595         int fd;
10596         int rc = 0;
10597         int rc2 = 0;
10598
10599         if (ids_nr <= 0)
10600                 return -EINVAL;
10601
10602         if (stat(fname, &stbuf) < 0) {
10603                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
10604                         progname, fname, strerror(errno));
10605                 rc = -errno;
10606                 goto error;
10607         }
10608
10609         if (!S_ISREG(stbuf.st_mode)) {
10610                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
10611                         progname, fname);
10612                 rc = -EINVAL;
10613                 goto error;
10614         }
10615
10616         fd = open(fname, O_DIRECT | O_RDONLY);
10617         if (fd < 0) {
10618                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
10619                         progname, fname, strerror(errno));
10620                 rc = -errno;
10621                 goto error;
10622         }
10623
10624         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
10625         if (rc < 0) {
10626                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
10627                         progname, fname, strerror(errno));
10628                 goto close_fd;
10629         }
10630
10631         layout = llapi_layout_get_by_fd(fd, 0);
10632         if (!layout) {
10633                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
10634                         progname, fname, strerror(errno));
10635                 rc = -errno;
10636                 llapi_lease_release(fd);
10637                 goto close_fd;
10638         }
10639
10640         rc = llapi_layout_flags_get(layout, &flr_state);
10641         if (rc < 0) {
10642                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
10643                         progname, fname, strerror(errno));
10644                 rc = -errno;
10645                 goto free_layout;
10646         }
10647
10648         flr_state &= LCM_FL_FLR_MASK;
10649         switch (flr_state) {
10650         case LCM_FL_NONE:
10651                 rc = -EINVAL;
10652                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
10653                         progname, fname, llapi_layout_flags_string(flr_state));
10654                 goto free_layout;
10655         default:
10656                 break;
10657         }
10658
10659         rc2 = 0;
10660         for (i = 0; i < ids_nr; i++) {
10661                 mirror_id_cbdata.mirror_id = mirror_ids[i];
10662                 mirror_id_cbdata.is_valid_id = false;
10663
10664                 rc = llapi_layout_comp_iterate(layout, compare_mirror_ids,
10665                                                &mirror_id_cbdata);
10666                 if (rc < 0) {
10667                         rc = -errno;
10668                         fprintf(stderr,
10669                                 "%s: '%s' failed to verify mirror id: %u.\n",
10670                                 progname, fname, mirror_ids[i]);
10671                         goto free_layout;
10672                 }
10673
10674                 if (!mirror_id_cbdata.is_valid_id) {
10675                         rc2 = -EINVAL;
10676                         fprintf(stderr,
10677                                 "%s: '%s' invalid specified mirror id: %u.\n",
10678                                 progname, fname, mirror_ids[i]);
10679                 }
10680         }
10681         rc = rc2;
10682
10683 free_layout:
10684         llapi_layout_free(layout);
10685         llapi_lease_release(fd);
10686 close_fd:
10687         close(fd);
10688 error:
10689         return rc;
10690 }
10691
10692 static inline
10693 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
10694                            __u16 *mirror_ids, int ids_nr)
10695 {
10696         struct llapi_resync_comp comp_array[1024] = { { 0 } };
10697         struct llapi_layout *layout;
10698         struct stat stbuf;
10699         uint32_t flr_state;
10700         uint64_t start;
10701         uint64_t end;
10702         int comp_size = 0;
10703         int idx;
10704         int fd;
10705         int rc;
10706         int rc2;
10707
10708         if (stat(fname, &stbuf) < 0) {
10709                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
10710                         progname, fname, strerror(errno));
10711                 rc = -errno;
10712                 goto error;
10713         }
10714         if (!S_ISREG(stbuf.st_mode)) {
10715                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
10716                         progname, fname);
10717                 rc = -EINVAL;
10718                 goto error;
10719         }
10720
10721         fd = open(fname, O_DIRECT | O_RDWR);
10722         if (fd < 0) {
10723                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
10724                         progname, fname, strerror(errno));
10725                 rc = -errno;
10726                 goto error;
10727         }
10728
10729         layout = llapi_layout_get_by_fd(fd, 0);
10730         if (!layout) {
10731                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
10732                         progname, fname, strerror(errno));
10733                 rc = -errno;
10734                 goto close_fd;
10735         }
10736
10737         rc = llapi_layout_flags_get(layout, &flr_state);
10738         if (rc) {
10739                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
10740                         progname, fname, strerror(errno));
10741                 rc = -errno;
10742                 goto free_layout;
10743         }
10744
10745         flr_state &= LCM_FL_FLR_MASK;
10746         if (flr_state == LCM_FL_NONE) {
10747                 rc = -EINVAL;
10748                 fprintf(stderr, "%s: '%s' is not a FLR file.\n",
10749                         progname, fname);
10750                 goto free_layout;
10751         }
10752
10753         /* get stale component info */
10754         comp_size = llapi_mirror_find_stale(layout, comp_array,
10755                                             ARRAY_SIZE(comp_array),
10756                                             mirror_ids, ids_nr);
10757         if (comp_size <= 0) {
10758                 rc = comp_size;
10759                 goto free_layout;
10760         }
10761
10762         ioc->lil_mode = LL_LEASE_WRLCK;
10763         ioc->lil_flags = LL_LEASE_RESYNC;
10764         rc = llapi_lease_set(fd, ioc);
10765         if (rc < 0) {
10766                 if (rc == -EALREADY)
10767                         rc = 0;
10768                 else
10769                         fprintf(stderr,
10770                             "%s: '%s' llapi_lease_get_ext resync failed: %s.\n",
10771                                 progname, fname, strerror(-rc));
10772                 goto free_layout;
10773         }
10774
10775         /* get the read range [start, end) */
10776         start = comp_array[0].lrc_start;
10777         end = comp_array[0].lrc_end;
10778         for (idx = 1; idx < comp_size; idx++) {
10779                 if (comp_array[idx].lrc_start < start)
10780                         start = comp_array[idx].lrc_start;
10781                 if (end < comp_array[idx].lrc_end)
10782                         end = comp_array[idx].lrc_end;
10783         }
10784
10785         rc = llapi_lease_check(fd);
10786         if (rc != LL_LEASE_WRLCK) {
10787                 fprintf(stderr, "%s: '%s' lost lease lock.\n",
10788                         progname, fname);
10789                 goto free_layout;
10790         }
10791
10792         rc = llapi_mirror_resync_many(fd, layout, comp_array, comp_size,
10793                                       start, end);
10794         if (rc < 0)
10795                 fprintf(stderr, "%s: '%s' llapi_mirror_resync_many: %s.\n",
10796                         progname, fname, strerror(-rc));
10797
10798         rc = migrate_set_timestamps(fd, &stbuf);
10799         if (rc < 0) {
10800                 fprintf(stderr, "%s: '%s' cannot set timestamps: %s\n",
10801                         progname, fname, strerror(-rc));
10802                 goto free_layout;
10803         }
10804
10805         /* need to do the lease unlock even resync fails */
10806         ioc->lil_mode = LL_LEASE_UNLCK;
10807         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
10808         ioc->lil_count = 0;
10809         for (idx = 0; idx < comp_size; idx++) {
10810                 if (comp_array[idx].lrc_synced) {
10811                         ioc->lil_ids[ioc->lil_count] = comp_array[idx].lrc_id;
10812                         ioc->lil_count++;
10813                 }
10814         }
10815
10816         rc2 = llapi_lease_set(fd, ioc);
10817         /**
10818          * llapi_lease_set returns lease mode when it request to unlock
10819          * the lease lock.
10820          */
10821         if (rc2 <= 0) {
10822                 /* rc2 == 0 means lost lease lock */
10823                 if (rc2 == 0 && rc == 0)
10824                         rc = -EBUSY;
10825                 else
10826                         rc = rc2;
10827                 fprintf(stderr, "%s: resync file '%s' failed: %s.\n",
10828                         progname, fname,
10829                         rc2 == 0 ? "lost lease lock" : strerror(-rc2));
10830
10831                 llapi_lease_release(fd);
10832                 goto free_layout;
10833         }
10834
10835 free_layout:
10836         llapi_layout_free(layout);
10837 close_fd:
10838         close(fd);
10839 error:
10840         return rc;
10841 }
10842
10843 static inline int lfs_mirror_resync(int argc, char **argv)
10844 {
10845         struct option long_opts[] = {
10846         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10847         { .val = 'o',   .name = "only",         .has_arg = required_argument },
10848         { .name = NULL } };
10849         struct ll_ioc_lease *ioc = NULL;
10850         __u16 mirror_ids[128] = { 0 };
10851         int ids_nr = 0;
10852         int c;
10853         int rc = 0;
10854
10855         while ((c = getopt_long(argc, argv, "ho:", long_opts, NULL)) >= 0) {
10856                 switch (c) {
10857                 case 'o':
10858                         rc = parse_mirror_ids(mirror_ids,
10859                                         sizeof(mirror_ids) / sizeof(__u16),
10860                                         optarg);
10861                         if (rc < 0) {
10862                                 fprintf(stderr,
10863                                         "%s: bad mirror ids '%s'.\n",
10864                                         argv[0], optarg);
10865                                 goto error;
10866                         }
10867                         ids_nr = rc;
10868                         break;
10869                 default:
10870                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10871                                 progname, argv[optind - 1]);
10872                         /* fallthrough */
10873                 case 'h':
10874                         rc = CMD_HELP;
10875                         goto error;
10876                 }
10877         }
10878
10879         if (argc == optind) {
10880                 fprintf(stderr, "%s: no file name given.\n", argv[0]);
10881                 rc = CMD_HELP;
10882                 goto error;
10883         }
10884
10885         if (ids_nr > 0 && argc > optind + 1) {
10886                 fprintf(stderr,
10887                     "%s: option '--only' cannot be used upon multiple files.\n",
10888                         argv[0]);
10889                 rc = CMD_HELP;
10890                 goto error;
10891         }
10892
10893         if (ids_nr > 0) {
10894                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
10895                 if (rc < 0)
10896                         goto error;
10897         }
10898
10899         /* set the lease on the file */
10900         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
10901         if (!ioc) {
10902                 fprintf(stderr, "%s: cannot alloc id array for ioc: %s.\n",
10903                         argv[0], strerror(errno));
10904                 rc = -errno;
10905                 goto error;
10906         }
10907
10908         for (; optind < argc; optind++) {
10909                 rc = lfs_mirror_resync_file(argv[optind], ioc,
10910                                             mirror_ids, ids_nr);
10911                 /* ignore previous file's error, continue with next file */
10912
10913                 /* reset ioc */
10914                 memset(ioc, 0, sizeof(*ioc) + sizeof(__u32) * 4096);
10915         }
10916
10917         free(ioc);
10918 error:
10919         return rc;
10920 }
10921
10922 static inline int verify_mirror_id_by_fd(int fd, __u16 mirror_id)
10923 {
10924         struct llapi_layout *layout;
10925         int rc;
10926
10927         layout = llapi_layout_get_by_fd(fd, 0);
10928         if (!layout) {
10929                 fprintf(stderr, "could not get layout.\n");
10930                 return  -EINVAL;
10931         }
10932
10933         rc = llapi_layout_comp_iterate(layout, find_mirror_id, &mirror_id);
10934         if (rc < 0) {
10935                 fprintf(stderr, "failed to iterate layout\n");
10936                 llapi_layout_free(layout);
10937
10938                 return rc;
10939         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
10940                 fprintf(stderr, "does not find mirror with ID %u\n", mirror_id);
10941                 llapi_layout_free(layout);
10942
10943                 return -EINVAL;
10944         }
10945         llapi_layout_free(layout);
10946
10947         return 0;
10948 }
10949
10950 /**
10951  * Check whether two files are the same file
10952  * \retval      0  same file
10953  * \retval      1  not the same file
10954  * \retval      <0 error code
10955  */
10956 static inline int check_same_file(int fd, const char *f2)
10957 {
10958         struct stat stbuf1;
10959         struct stat stbuf2;
10960
10961         if (fstat(fd, &stbuf1) < 0)
10962                 return -errno;
10963
10964         if (stat(f2, &stbuf2) < 0)
10965                 return 1;
10966
10967         if (stbuf1.st_rdev == stbuf2.st_rdev &&
10968             stbuf1.st_ino == stbuf2.st_ino)
10969                 return 0;
10970
10971         return 1;
10972 }
10973
10974 static inline int lfs_mirror_read(int argc, char **argv)
10975 {
10976         int rc = CMD_HELP;
10977         __u16 mirror_id = 0;
10978         const char *outfile = NULL;
10979         char *fname;
10980         int fd = 0;
10981         int outfd;
10982         int c;
10983         void *buf;
10984         const size_t buflen = 4 << 20;
10985         off_t pos;
10986         struct option long_opts[] = {
10987         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10988         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
10989         { .val = 'o',   .name = "outfile",      .has_arg = required_argument },
10990         { .name = NULL } };
10991
10992         while ((c = getopt_long(argc, argv, "hN:o:", long_opts, NULL)) >= 0) {
10993                 char *end;
10994
10995                 switch (c) {
10996                 case 'N': {
10997                         unsigned long int id;
10998
10999                         errno = 0;
11000                         id = strtoul(optarg, &end, 0);
11001                         if (errno != 0 || *end != '\0' || id == 0 ||
11002                             id > UINT16_MAX) {
11003                                 fprintf(stderr,
11004                                         "%s %s: invalid mirror ID '%s'\n",
11005                                         progname, argv[0], optarg);
11006                                 return rc;
11007                         }
11008
11009                         mirror_id = (__u16)id;
11010                         break;
11011                 }
11012                 case 'o':
11013                         outfile = optarg;
11014                         break;
11015                 default:
11016                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11017                                 progname, argv[optind - 1]);
11018                         /* fallthrough */
11019                 case 'h':
11020                         return CMD_HELP;
11021                 }
11022         }
11023
11024         if (argc == optind) {
11025                 fprintf(stderr, "%s %s: no mirrored file provided\n",
11026                         progname, argv[0]);
11027                 return rc;
11028         } else if (argc > optind + 1) {
11029                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
11030                 return rc;
11031         }
11032
11033         if (mirror_id == 0) {
11034                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
11035                         progname, argv[0]);
11036                 return rc;
11037         }
11038
11039         /* open mirror file */
11040         fname = argv[optind];
11041         fd = open(fname, O_DIRECT | O_RDONLY);
11042         if (fd < 0) {
11043                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
11044                         progname, argv[0], fname, strerror(errno));
11045                 return rc;
11046         }
11047
11048         /* verify mirror id */
11049         rc = verify_mirror_id_by_fd(fd, mirror_id);
11050         if (rc) {
11051                 fprintf(stderr,
11052                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11053                         progname, argv[0], mirror_id, fname);
11054                 goto close_fd;
11055         }
11056
11057         /* open output file - O_EXCL ensures output is not the same as input */
11058         if (outfile) {
11059                 outfd = open(outfile, O_EXCL | O_WRONLY | O_CREAT, 0644);
11060                 if (outfd < 0) {
11061                         fprintf(stderr, "%s %s: cannot create file '%s': %s\n",
11062                                 progname, argv[0], outfile, strerror(errno));
11063                         rc = -errno;
11064                         goto close_fd;
11065                 }
11066         } else {
11067                 outfd = STDOUT_FILENO;
11068         }
11069
11070         /* allocate buffer */
11071         rc = posix_memalign(&buf, sysconf(_SC_PAGESIZE), buflen);
11072         if (rc) {
11073                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
11074                                 progname, argv[0], rc);
11075                 goto close_outfd;
11076         }
11077
11078         pos = 0;
11079         while (1) {
11080                 ssize_t bytes_read;
11081                 ssize_t written = 0;
11082
11083                 bytes_read = llapi_mirror_read(fd, mirror_id, buf, buflen, pos);
11084                 if (bytes_read < 0) {
11085                         rc = bytes_read;
11086                         fprintf(stderr,
11087                                 "%s %s: fail to read data from mirror %u: %s\n",
11088                                 progname, argv[0], mirror_id, strerror(-rc));
11089                         goto free_buf;
11090                 }
11091
11092                 /* EOF reached */
11093                 if (bytes_read == 0)
11094                         break;
11095
11096                 while (written < bytes_read) {
11097                         ssize_t written2;
11098
11099                         written2 = write(outfd, buf + written,
11100                                          bytes_read - written);
11101                         if (written2 < 0) {
11102                                 fprintf(stderr,
11103                                         "%s %s: fail to write %s: %s\n",
11104                                         progname, argv[0], outfile ? : "STDOUT",
11105                                         strerror(errno));
11106                                 rc = -errno;
11107                                 goto free_buf;
11108                         }
11109                         written += written2;
11110                 }
11111
11112                 if (written != bytes_read) {
11113                         fprintf(stderr,
11114                 "%s %s: written %ld bytes does not match with %ld read.\n",
11115                                 progname, argv[0], written, bytes_read);
11116                         rc = -EIO;
11117                         goto free_buf;
11118                 }
11119
11120                 pos += bytes_read;
11121         }
11122
11123         fsync(outfd);
11124         rc = 0;
11125
11126 free_buf:
11127         free(buf);
11128 close_outfd:
11129         if (outfile)
11130                 close(outfd);
11131 close_fd:
11132         close(fd);
11133
11134         return rc;
11135 }
11136
11137 static inline int lfs_mirror_write(int argc, char **argv)
11138 {
11139         int rc = CMD_HELP;
11140         __u16 mirror_id = 0;
11141         const char *inputfile = NULL;
11142         char *fname;
11143         int fd = 0;
11144         int inputfd;
11145         int c;
11146         void *buf;
11147         const size_t buflen = 4 << 20;
11148         off_t pos;
11149         size_t page_size = sysconf(_SC_PAGESIZE);
11150         struct ll_ioc_lease_id ioc;
11151         struct option long_opts[] = {
11152         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11153         { .val = 'i',   .name = "inputfile",    .has_arg = required_argument },
11154         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
11155         { .name = NULL } };
11156
11157         while ((c = getopt_long(argc, argv, "hi:N:", long_opts, NULL)) >= 0) {
11158                 char *end;
11159
11160                 switch (c) {
11161                 case 'N': {
11162                         unsigned long int id;
11163
11164                         errno = 0;
11165                         id = strtoul(optarg, &end, 0);
11166                         if (errno != 0 || *end != '\0' || id == 0 ||
11167                             id > UINT16_MAX) {
11168                                 fprintf(stderr,
11169                                         "%s %s: invalid mirror ID '%s'\n",
11170                                         progname, argv[0], optarg);
11171                                 return rc;
11172                         }
11173
11174                         mirror_id = (__u16)id;
11175                         break;
11176                 }
11177                 case 'i':
11178                         inputfile = optarg;
11179                         break;
11180                 default:
11181                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11182                                 progname, argv[optind - 1]);
11183                         /* fallthrough */
11184                 case 'h':
11185                         return CMD_HELP;
11186                 }
11187         }
11188
11189         if (argc == optind) {
11190                 fprintf(stderr, "%s %s: no mirrored file provided\n",
11191                         progname, argv[0]);
11192                 return rc;
11193         } else if (argc > optind + 1) {
11194                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
11195                 return rc;
11196         }
11197
11198         if (mirror_id == 0) {
11199                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
11200                         progname, argv[0]);
11201                 return rc;
11202         }
11203
11204         /* open mirror file */
11205         fname = argv[optind];
11206         fd = open(fname, O_DIRECT | O_WRONLY);
11207         if (fd < 0) {
11208                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
11209                         progname, argv[0], fname, strerror(errno));
11210                 return rc;
11211         }
11212
11213         /* verify mirror id */
11214         rc = verify_mirror_id_by_fd(fd, mirror_id);
11215         if (rc) {
11216                 fprintf(stderr,
11217                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11218                         progname, argv[0], mirror_id, fname);
11219                 goto close_fd;
11220         }
11221
11222         /* open input file */
11223         if (inputfile) {
11224                 rc = check_same_file(fd, inputfile);
11225                 if (rc == 0) {
11226                         fprintf(stderr,
11227                         "%s %s: input file cannot be the mirrored file\n",
11228                                 progname, argv[0]);
11229                         goto close_fd;
11230                 }
11231                 if (rc < 0)
11232                         goto close_fd;
11233
11234                 inputfd = open(inputfile, O_RDONLY, 0644);
11235                 if (inputfd < 0) {
11236                         fprintf(stderr, "%s %s: cannot open file '%s': %s\n",
11237                                 progname, argv[0], inputfile, strerror(errno));
11238                         rc = -errno;
11239                         goto close_fd;
11240                 }
11241         } else {
11242                 inputfd = STDIN_FILENO;
11243         }
11244
11245         /* allocate buffer */
11246         rc = posix_memalign(&buf, page_size, buflen);
11247         if (rc) {
11248                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
11249                         progname, argv[0], rc);
11250                 goto close_inputfd;
11251         }
11252
11253         /* prepare target mirror components instantiation */
11254         ioc.lil_mode = LL_LEASE_WRLCK;
11255         ioc.lil_flags = LL_LEASE_RESYNC;
11256         ioc.lil_mirror_id = mirror_id;
11257         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
11258         if (rc < 0) {
11259                 fprintf(stderr,
11260                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
11261                         progname, argv[0], fname, strerror(errno));
11262                 goto free_buf;
11263         }
11264
11265         pos = 0;
11266         while (1) {
11267                 ssize_t bytes_read;
11268                 ssize_t written;
11269                 size_t to_write;
11270
11271                 rc = llapi_lease_check(fd);
11272                 if (rc != LL_LEASE_WRLCK) {
11273                         fprintf(stderr, "%s %s: '%s' lost lease lock\n",
11274                                 progname, argv[0], fname);
11275                         goto free_buf;
11276                 }
11277
11278                 bytes_read = read(inputfd, buf, buflen);
11279                 if (bytes_read < 0) {
11280                         rc = bytes_read;
11281                         fprintf(stderr,
11282                                 "%s %s: fail to read data from '%s': %s\n",
11283                                 progname, argv[0], inputfile ? : "STDIN",
11284                                 strerror(errno));
11285                         rc = -errno;
11286                         goto free_buf;
11287                 }
11288
11289                 /* EOF reached */
11290                 if (bytes_read == 0)
11291                         break;
11292
11293                 /* round up to page align to make direct IO happy. */
11294                 to_write = (bytes_read + page_size - 1) & ~(page_size - 1);
11295
11296                 written = llapi_mirror_write(fd, mirror_id, buf, to_write,
11297                                              pos);
11298                 if (written < 0) {
11299                         rc = written;
11300                         fprintf(stderr,
11301                               "%s %s: fail to write to mirror %u: %s\n",
11302                                 progname, argv[0], mirror_id,
11303                                 strerror(-rc));
11304                         goto free_buf;
11305                 }
11306
11307                 pos += bytes_read;
11308         }
11309
11310         if (pos & (page_size - 1)) {
11311                 rc = llapi_mirror_truncate(fd, mirror_id, pos);
11312                 if (rc < 0)
11313                         goto free_buf;
11314         }
11315
11316         ioc.lil_mode = LL_LEASE_UNLCK;
11317         ioc.lil_flags = LL_LEASE_RESYNC_DONE;
11318         ioc.lil_count = 0;
11319         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
11320         if (rc <= 0) {
11321                 if (rc == 0)
11322                         rc = -EBUSY;
11323                 fprintf(stderr,
11324                         "%s %s: release lease lock of '%s' failed: %s\n",
11325                         progname, argv[0], fname, strerror(errno));
11326                 goto free_buf;
11327         }
11328
11329         rc = 0;
11330
11331 free_buf:
11332         free(buf);
11333 close_inputfd:
11334         if (inputfile)
11335                 close(inputfd);
11336 close_fd:
11337         close(fd);
11338
11339         return rc;
11340 }
11341
11342 static inline int get_other_mirror_ids(int fd, __u16 *ids, __u16 exclude_id)
11343 {
11344         struct llapi_layout *layout;
11345         struct collect_ids_data cid = { .cid_ids = ids,
11346                                         .cid_count = 0,
11347                                         .cid_exclude = exclude_id, };
11348         int rc;
11349
11350         layout = llapi_layout_get_by_fd(fd, 0);
11351         if (!layout) {
11352                 fprintf(stderr, "could not get layout\n");
11353                 return -EINVAL;
11354         }
11355
11356         rc = llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
11357         if (rc < 0) {
11358                 fprintf(stderr, "failed to iterate layout\n");
11359                 llapi_layout_free(layout);
11360
11361                 return rc;
11362         }
11363         llapi_layout_free(layout);
11364
11365         return cid.cid_count;
11366 }
11367
11368 #ifndef MIRROR_ID_NEG
11369 #define MIRROR_ID_NEG         0x8000
11370 #endif
11371
11372 static inline int lfs_mirror_copy(int argc, char **argv)
11373 {
11374         int rc = CMD_HELP;
11375         __u16 read_mirror_id = 0;
11376         __u16 ids[128] = { 0 };
11377         int count = 0;
11378         struct llapi_layout *layout = NULL;
11379         struct llapi_resync_comp comp_array[1024] = { { 0 } };
11380         int comp_size = 0;
11381         char *fname;
11382         int fd = 0;
11383         int c;
11384         int i;
11385         ssize_t copied;
11386         struct ll_ioc_lease *ioc = NULL;
11387         struct ll_ioc_lease_id *resync_ioc;
11388         struct option long_opts[] = {
11389         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11390         { .val = 'i',   .name = "read-mirror",  .has_arg = required_argument },
11391         { .val = 'o',   .name = "write-mirror", .has_arg = required_argument },
11392         { .name = NULL } };
11393         char cmd[PATH_MAX];
11394
11395         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
11396         progname = cmd;
11397         while ((c = getopt_long(argc, argv, "hi:o:", long_opts, NULL)) >= 0) {
11398                 char *end;
11399
11400                 switch (c) {
11401                 case 'i': {
11402                         unsigned long int id;
11403
11404                         errno = 0;
11405                         id = strtoul(optarg, &end, 0);
11406                         if (errno != 0 || *end != '\0' || id == 0 ||
11407                             id > UINT16_MAX) {
11408                                 fprintf(stderr,
11409                                         "%s: invalid read mirror ID '%s'\n",
11410                                         progname, optarg);
11411                                 return rc;
11412                         }
11413
11414                         read_mirror_id = (__u16)id;
11415                         break;
11416                 }
11417                 case 'o':
11418                         if (!strcmp(optarg, "-1")) {
11419                                 /* specify all other mirrors */
11420                                 ids[0] = (__u16)-1;
11421                                 count = 1;
11422                         } else {
11423                                 count = parse_mirror_ids((__u16 *)ids,
11424                                                          ARRAY_SIZE(ids),
11425                                                          optarg);
11426                                 if (count < 0)
11427                                         return rc;
11428                         }
11429                         break;
11430                 default:
11431                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11432                                 progname, argv[optind - 1]);
11433                         /* fallthrough */
11434                 case 'h':
11435                         return CMD_HELP;
11436                 }
11437         }
11438
11439         if (argc == optind) {
11440                 fprintf(stderr, "%s %s: no mirrored file provided\n",
11441                         progname, argv[0]);
11442                 return rc;
11443         } else if (argc > optind + 1) {
11444                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
11445                 return rc;
11446         }
11447
11448         if (read_mirror_id == 0) {
11449                 fprintf(stderr,
11450                         "%s %s: no valid read mirror ID %d is provided\n",
11451                         progname, argv[0], read_mirror_id);
11452                 return rc;
11453         }
11454
11455         if (count == 0) {
11456                 fprintf(stderr,
11457                         "%s %s: no write mirror ID is provided\n",
11458                         progname, argv[0]);
11459                 return rc;
11460         }
11461
11462         for (i = 0; i < count; i++) {
11463                 if (read_mirror_id == ids[i]) {
11464                         fprintf(stderr,
11465                         "%s %s: read and write mirror ID cannot be the same\n",
11466                                 progname, argv[0]);
11467                         return rc;
11468                 }
11469         }
11470
11471         /* open mirror file */
11472         fname = argv[optind];
11473
11474         fd = open(fname, O_DIRECT | O_RDWR);
11475         if (fd < 0) {
11476                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
11477                         progname, argv[0], fname, strerror(errno));
11478                 return rc;
11479         }
11480
11481         /* write to all other mirrors */
11482         if (ids[0] == (__u16)-1) {
11483                 count = get_other_mirror_ids(fd, ids, read_mirror_id);
11484                 if (count <= 0) {
11485                         rc = count;
11486                         fprintf(stderr,
11487                         "%s %s: failed to get other mirror ids in '%s': %d\n",
11488                                 progname, argv[0], fname, rc);
11489                         goto close_fd;
11490                 }
11491         }
11492
11493         /* verify mirror id */
11494         rc = verify_mirror_id_by_fd(fd, read_mirror_id);
11495         if (rc) {
11496                 fprintf(stderr,
11497                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11498                         progname, argv[0], read_mirror_id, fname);
11499                 goto close_fd;
11500         }
11501
11502         for (i = 0; i < count; i++) {
11503                 rc = verify_mirror_id_by_fd(fd, ids[i]);
11504                 if (rc) {
11505                         fprintf(stderr,
11506                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11507                                 progname, argv[0], ids[i], fname);
11508                         goto close_fd;
11509                 }
11510         }
11511
11512         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
11513         if (!ioc) {
11514                 fprintf(stderr,
11515                         "%s %s: cannot alloc comp id array for ioc: %s\n",
11516                         progname, argv[0], strerror(errno));
11517                 rc = -errno;
11518                 goto close_fd;
11519         }
11520
11521         /* get stale component info */
11522         layout = llapi_layout_get_by_fd(fd, 0);
11523         if (!layout) {
11524                 fprintf(stderr, "%s %s: failed to get layout of '%s': %s\n",
11525                         progname, argv[0], fname, strerror(errno));
11526                 rc = -errno;
11527                 goto free_ioc;
11528         }
11529         comp_size = llapi_mirror_find_stale(layout, comp_array,
11530                                             ARRAY_SIZE(comp_array),
11531                                             ids, count);
11532         llapi_layout_free(layout);
11533         if (comp_size < 0) {
11534                 rc = comp_size;
11535                 goto free_ioc;
11536         }
11537
11538         /* prepare target mirror components instantiation */
11539         resync_ioc = (struct ll_ioc_lease_id *)ioc;
11540         resync_ioc->lil_mode = LL_LEASE_WRLCK;
11541         resync_ioc->lil_flags = LL_LEASE_RESYNC;
11542         if (count == 1)
11543                 resync_ioc->lil_mirror_id = ids[0];
11544         else
11545                 resync_ioc->lil_mirror_id = read_mirror_id | MIRROR_ID_NEG;
11546         rc = llapi_lease_set(fd, ioc);
11547         if (rc < 0) {
11548                 fprintf(stderr,
11549                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
11550                         progname, argv[0], fname, strerror(errno));
11551                 goto free_ioc;
11552         }
11553
11554         copied = llapi_mirror_copy_many(fd, read_mirror_id, ids, count);
11555         if (copied < 0) {
11556                 rc = copied;
11557                 fprintf(stderr, "%s %s: copy error: %d\n",
11558                         progname, argv[0], rc);
11559                 goto free_ioc;
11560         }
11561
11562         fprintf(stdout, "mirror copied successfully: ");
11563         for (i = 0; i < copied; i++)
11564                 fprintf(stdout, "%d ", ids[i]);
11565         fprintf(stdout, "\n");
11566
11567         ioc->lil_mode = LL_LEASE_UNLCK;
11568         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
11569         ioc->lil_count = 0;
11570         for (i = 0; i < comp_size; i++) {
11571                 int j;
11572
11573                 for (j = 0; j < copied; j++) {
11574                         if (comp_array[i].lrc_mirror_id != ids[j])
11575                                 continue;
11576
11577                         ioc->lil_ids[ioc->lil_count] = comp_array[i].lrc_id;
11578                         ioc->lil_count++;
11579                 }
11580         }
11581         rc = llapi_lease_set(fd, ioc);
11582         if (rc <= 0) {
11583                 if (rc == 0)
11584                         rc = -EBUSY;
11585                 fprintf(stderr,
11586                         "%s %s: release lease lock of '%s' failed: %s\n",
11587                         progname, argv[0], fname, strerror(errno));
11588                 goto free_ioc;
11589         }
11590
11591         rc = 0;
11592
11593 free_ioc:
11594         free(ioc);
11595 close_fd:
11596         close(fd);
11597
11598         return rc;
11599 }
11600
11601 /**
11602  * struct verify_chunk - Mirror chunk to be verified.
11603  * @chunk:        [start, end) of the chunk.
11604  * @mirror_count: Number of mirror ids in @mirror_id array.
11605  * @mirror_id:    Array of valid mirror ids that cover the chunk.
11606  */
11607 struct verify_chunk {
11608         struct lu_extent chunk;
11609         unsigned int mirror_count;
11610         __u16 mirror_id[LUSTRE_MIRROR_COUNT_MAX];
11611 };
11612
11613 /**
11614  * print_chunks() - Print chunk information.
11615  * @fname:       Mirrored file name.
11616  * @chunks:      Array of chunks.
11617  * @chunk_count: Number of chunks in @chunks array.
11618  *
11619  * This function prints [start, end) of each chunk in @chunks
11620  * for mirrored file @fname, and also prints the valid mirror ids
11621  * that cover the chunk.
11622  *
11623  * Return: void.
11624  */
11625 static inline
11626 void print_chunks(const char *fname, struct verify_chunk *chunks,
11627                   int chunk_count)
11628 {
11629         int i;
11630         int j;
11631
11632         fprintf(stdout, "Chunks to be verified in %s:\n", fname);
11633         for (i = 0; i < chunk_count; i++) {
11634                 fprintf(stdout, DEXT, PEXT(&chunks[i].chunk));
11635
11636                 if (chunks[i].mirror_count == 0)
11637                         fprintf(stdout, "\t[");
11638                 else {
11639                         fprintf(stdout, "\t[%u", chunks[i].mirror_id[0]);
11640                         for (j = 1; j < chunks[i].mirror_count; j++)
11641                                 fprintf(stdout, ", %u", chunks[i].mirror_id[j]);
11642                 }
11643                 fprintf(stdout, "]\t%u\n", chunks[i].mirror_count);
11644         }
11645         fprintf(stdout, "\n");
11646 }
11647
11648 /**
11649  * print_checksums() - Print CRC-32 checksum values.
11650  * @chunk: A chunk and its corresponding valid mirror ids.
11651  * @crc:   CRC-32 checksum values on the chunk for each valid mirror.
11652  *
11653  * This function prints CRC-32 checksum values on @chunk for
11654  * each valid mirror that covers it.
11655  *
11656  * Return: void.
11657  */
11658 static inline
11659 void print_checksums(struct verify_chunk *chunk, unsigned long *crc)
11660 {
11661         int i;
11662
11663         fprintf(stdout,
11664                 "CRC-32 checksum value for chunk "DEXT":\n",
11665                 PEXT(&chunk->chunk));
11666         for (i = 0; i < chunk->mirror_count; i++)
11667                 fprintf(stdout, "Mirror %u:\t%#lx\n",
11668                         chunk->mirror_id[i], crc[i]);
11669         fprintf(stdout, "\n");
11670 }
11671
11672 /**
11673  * filter_mirror_id() - Filter specified mirror ids.
11674  * @chunks:      Array of chunks.
11675  * @chunk_count: Number of chunks in @chunks array.
11676  * @mirror_ids:  Specified mirror ids to be verified.
11677  * @ids_nr:      Number of specified mirror ids.
11678  *
11679  * This function scans valid mirror ids that cover each chunk in @chunks
11680  * and filters specified mirror ids.
11681  *
11682  * Return: void.
11683  */
11684 static inline
11685 void filter_mirror_id(struct verify_chunk *chunks, int chunk_count,
11686                       __u16 *mirror_ids, int ids_nr)
11687 {
11688         int i;
11689         int j;
11690         int k;
11691         __u16 valid_id[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
11692         unsigned int valid_count = 0;
11693
11694         for (i = 0; i < chunk_count; i++) {
11695                 if (chunks[i].mirror_count == 0)
11696                         continue;
11697
11698                 valid_count = 0;
11699                 for (j = 0; j < ids_nr; j++) {
11700                         for (k = 0; k < chunks[i].mirror_count; k++) {
11701                                 if (chunks[i].mirror_id[k] == mirror_ids[j]) {
11702                                         valid_id[valid_count] = mirror_ids[j];
11703                                         valid_count++;
11704                                         break;
11705                                 }
11706                         }
11707                 }
11708
11709                 memcpy(chunks[i].mirror_id, valid_id,
11710                        sizeof(__u16) * valid_count);
11711                 chunks[i].mirror_count = valid_count;
11712         }
11713 }
11714
11715 /**
11716  * lfs_mirror_prepare_chunk() - Find mirror chunks to be verified.
11717  * @layout:      Mirror component list.
11718  * @chunks:      Array of chunks.
11719  * @chunks_size: Array size of @chunks.
11720  *
11721  * This function scans the components in @layout from offset 0 to LUSTRE_EOF
11722  * to find out chunk segments and store them in @chunks array.
11723  *
11724  * The @mirror_id array in each element of @chunks will store the valid
11725  * mirror ids that cover the chunk. If a mirror component covering the
11726  * chunk has LCME_FL_STALE or LCME_FL_OFFLINE flag, then the mirror id
11727  * will not be stored into the @mirror_id array, and the chunk for that
11728  * mirror will not be verified.
11729  *
11730  * The @mirror_count in each element of @chunks will store the number of
11731  * mirror ids in @mirror_id array. If @mirror_count is 0, it indicates the
11732  * chunk is invalid in all of the mirrors. And if @mirror_count is 1, it
11733  * indicates the chunk is valid in only one mirror. In both cases, the
11734  * chunk will not be verified.
11735  *
11736  * Here is an example:
11737  *
11738  *  0      1M     2M     3M     4M           EOF
11739  *  +------+-------------+--------------------+
11740  *  |      |             |      S             |       mirror1
11741  *  +------+------+------+------+-------------+
11742  *  |             |   S  |   S  |             |       mirror2
11743  *  +-------------+------+------+-------------+
11744  *
11745  * prepared @chunks array will contain 5 elements:
11746  * (([0, 1M), [1, 2], 2),
11747  *  ([1M, 2M), [1, 2], 2),
11748  *  ([2M, 3M), [1], 1),
11749  *  ([3M, 4M], [], 0),
11750  *  ([4M, EOF), [2], 1))
11751  *
11752  * Return: the actual array size of @chunks on success
11753  *         or a negative error code on failure.
11754  */
11755 static inline
11756 int lfs_mirror_prepare_chunk(struct llapi_layout *layout,
11757                              struct verify_chunk *chunks,
11758                              size_t chunks_size)
11759 {
11760         uint64_t start;
11761         uint64_t end;
11762         uint32_t mirror_id;
11763         uint32_t flags;
11764         int idx = 0;
11765         int i = 0;
11766         int rc = 0;
11767
11768         memset(chunks, 0, sizeof(*chunks) * chunks_size);
11769
11770         while (1) {
11771                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
11772                 if (rc < 0) {
11773                         fprintf(stderr,
11774                                 "%s: move to the first layout component: %s.\n",
11775                                 progname, strerror(errno));
11776                         goto error;
11777                 }
11778
11779                 i = 0;
11780                 rc = 0;
11781                 chunks[idx].chunk.e_end = LUSTRE_EOF;
11782                 while (rc == 0) {
11783                         rc = llapi_layout_comp_extent_get(layout, &start, &end);
11784                         if (rc < 0) {
11785                                 fprintf(stderr,
11786                                         "%s: llapi_layout_comp_extent_get failed: %s.\n",
11787                                         progname, strerror(errno));
11788                                 goto error;
11789                         }
11790
11791                         if (start > chunks[idx].chunk.e_start ||
11792                             end <= chunks[idx].chunk.e_start)
11793                                 goto next;
11794
11795                         if (end < chunks[idx].chunk.e_end)
11796                                 chunks[idx].chunk.e_end = end;
11797
11798                         rc = llapi_layout_comp_flags_get(layout, &flags);
11799                         if (rc < 0) {
11800                                 fprintf(stderr,
11801                                         "%s: llapi_layout_comp_flags_get failed: %s.\n",
11802                                         progname, strerror(errno));
11803                                 goto error;
11804                         }
11805
11806                         if (flags & LCME_FL_STALE || flags & LCME_FL_OFFLINE)
11807                                 goto next;
11808
11809                         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
11810                         if (rc < 0) {
11811                                 fprintf(stderr,
11812                                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
11813                                         progname, strerror(errno));
11814                                 goto error;
11815                         }
11816
11817                         chunks[idx].mirror_id[i] = mirror_id;
11818                         i++;
11819                         if (i >= ARRAY_SIZE(chunks[idx].mirror_id)) {
11820                                 fprintf(stderr,
11821                                         "%s: mirror_id array is too small.\n",
11822                                         progname);
11823                                 rc = -EINVAL;
11824                                 goto error;
11825                         }
11826
11827 next:
11828                         rc = llapi_layout_comp_use(layout,
11829                                                    LLAPI_LAYOUT_COMP_USE_NEXT);
11830                         if (rc < 0) {
11831                                 fprintf(stderr,
11832                                         "%s: move to the next layout component: %s.\n",
11833                                         progname, strerror(errno));
11834                                 goto error;
11835                         }
11836                 } /* loop through all components */
11837
11838                 chunks[idx].mirror_count = i;
11839
11840                 if (chunks[idx].chunk.e_end == LUSTRE_EOF)
11841                         break;
11842
11843                 idx++;
11844                 if (idx >= chunks_size) {
11845                         fprintf(stderr, "%s: chunks array is too small.\n",
11846                                 progname);
11847                         rc = -EINVAL;
11848                         goto error;
11849                 }
11850
11851                 chunks[idx].chunk.e_start = chunks[idx - 1].chunk.e_end;
11852         }
11853
11854 error:
11855         return rc < 0 ? rc : idx + 1;
11856 }
11857
11858 /**
11859  * lfs_mirror_verify_chunk() - Verify a chunk.
11860  * @fd:        File descriptor of the mirrored file.
11861  * @file_size: Size of the mirrored file.
11862  * @chunk:     A chunk and its corresponding valid mirror ids.
11863  * @verbose:   Verbose mode.
11864  *
11865  * This function verifies a @chunk contains exactly the same data
11866  * ammong the mirrors that cover it.
11867  *
11868  * If @verbose is specified, then the function will print where the
11869  * differences are if the data do not match. Otherwise, it will
11870  * just return an error in that case.
11871  *
11872  * Return: 0 on success or a negative error code on failure.
11873  */
11874 static inline
11875 int lfs_mirror_verify_chunk(int fd, size_t file_size,
11876                             struct verify_chunk *chunk, int verbose)
11877 {
11878         const size_t buflen = 4 * 1024 * 1024; /* 4M */
11879         void *buf;
11880         size_t page_size = sysconf(_SC_PAGESIZE);
11881         ssize_t bytes_read;
11882         ssize_t bytes_done;
11883         size_t count;
11884         off_t pos;
11885         unsigned long crc;
11886         unsigned long crc_array[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
11887         int i;
11888         int rc = 0;
11889
11890         if (file_size == 0)
11891                 return 0;
11892
11893         rc = posix_memalign(&buf, page_size, buflen);
11894         if (rc) /* error code is returned directly */
11895                 return -rc;
11896
11897         if (verbose > 1) {
11898                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
11899                         PEXT(&chunk->chunk));
11900                 for (i = 0; i < chunk->mirror_count; i++)
11901                         fprintf(stdout, " %u", chunk->mirror_id[i]);
11902                 fprintf(stdout, "\n");
11903         }
11904
11905         bytes_done = 0;
11906         count = MIN(chunk->chunk.e_end, file_size) - chunk->chunk.e_start;
11907         pos = chunk->chunk.e_start;
11908         while (bytes_done < count) {
11909                 /* compute initial CRC-32 checksum */
11910                 crc = crc32(0L, Z_NULL, 0);
11911                 memset(crc_array, 0, sizeof(crc_array));
11912
11913                 bytes_read = 0;
11914                 for (i = 0; i < chunk->mirror_count; i++) {
11915                         bytes_read = llapi_mirror_read(fd, chunk->mirror_id[i],
11916                                                        buf, buflen, pos);
11917                         if (bytes_read < 0) {
11918                                 rc = bytes_read;
11919                                 fprintf(stderr,
11920                                         "%s: failed to read data from mirror %u: %s.\n",
11921                                         progname, chunk->mirror_id[i],
11922                                         strerror(-rc));
11923                                 goto error;
11924                         }
11925
11926                         /* compute new CRC-32 checksum */
11927                         crc_array[i] = crc32(crc, buf, bytes_read);
11928                 }
11929
11930                 if (verbose)
11931                         print_checksums(chunk, crc_array);
11932
11933                 /* compare CRC-32 checksum values */
11934                 for (i = 1; i < chunk->mirror_count; i++) {
11935                         if (crc_array[i] != crc_array[0]) {
11936                                 rc = -EINVAL;
11937
11938                                 fprintf(stderr,
11939                                         "%s: chunk "DEXT" has different checksum value on mirror %u and mirror %u.\n",
11940                                         progname, PEXT(&chunk->chunk),
11941                                         chunk->mirror_id[0],
11942                                         chunk->mirror_id[i]);
11943                         }
11944                 }
11945
11946                 pos += bytes_read;
11947                 bytes_done += bytes_read;
11948         }
11949
11950         if (verbose > 1 && rc == 0) {
11951                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
11952                         PEXT(&chunk->chunk));
11953                 for (i = 0; i < chunk->mirror_count; i++)
11954                         fprintf(stdout, " %u", chunk->mirror_id[i]);
11955                 fprintf(stdout, " PASS\n\n");
11956         }
11957
11958 error:
11959         free(buf);
11960         return rc;
11961 }
11962
11963 /**
11964  * lfs_mirror_verify_file() - Verify a mirrored file.
11965  * @fname:      Mirrored file name.
11966  * @mirror_ids: Specified mirror ids to be verified.
11967  * @ids_nr:     Number of specified mirror ids.
11968  * @verbose:    Verbose mode.
11969  *
11970  * This function verifies that each SYNC mirror of a mirrored file
11971  * specified by @fname contains exactly the same data.
11972  *
11973  * If @mirror_ids is specified, then the function will verify the
11974  * mirrors specified by @mirror_ids contain exactly the same data.
11975  *
11976  * If @verbose is specified, then the function will print where the
11977  * differences are if the data do not match. Otherwise, it will
11978  * just return an error in that case.
11979  *
11980  * Return: 0 on success or a negative error code on failure.
11981  */
11982 static inline
11983 int lfs_mirror_verify_file(const char *fname, __u16 *mirror_ids, int ids_nr,
11984                            int verbose)
11985 {
11986         struct verify_chunk chunks_array[1024] = { };
11987         struct llapi_layout *layout = NULL;
11988         struct stat stbuf;
11989         uint32_t flr_state;
11990         int fd;
11991         int chunk_count = 0;
11992         int idx = 0;
11993         int rc = 0;
11994         int rc1 = 0;
11995         int rc2 = 0;
11996
11997         if (stat(fname, &stbuf) < 0) {
11998                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
11999                         progname, fname, strerror(errno));
12000                 rc = -errno;
12001                 goto error;
12002         }
12003
12004         if (!S_ISREG(stbuf.st_mode)) {
12005                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
12006                         progname, fname);
12007                 rc = -EINVAL;
12008                 goto error;
12009         }
12010
12011         if (stbuf.st_size == 0) {
12012                 if (verbose)
12013                         fprintf(stdout, "%s: '%s' file size is 0.\n",
12014                                 progname, fname);
12015                 rc = 0;
12016                 goto error;
12017         }
12018
12019         fd = open(fname, O_DIRECT | O_RDONLY);
12020         if (fd < 0) {
12021                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
12022                         progname, fname, strerror(errno));
12023                 rc = -errno;
12024                 goto error;
12025         }
12026
12027         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
12028         if (rc < 0) {
12029                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
12030                         progname, fname, strerror(errno));
12031                 goto close_fd;
12032         }
12033
12034         layout = llapi_layout_get_by_fd(fd, 0);
12035         if (!layout) {
12036                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
12037                         progname, fname, strerror(errno));
12038                 rc = -errno;
12039                 llapi_lease_release(fd);
12040                 goto close_fd;
12041         }
12042
12043         rc = llapi_layout_flags_get(layout, &flr_state);
12044         if (rc < 0) {
12045                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
12046                         progname, fname, strerror(errno));
12047                 rc = -errno;
12048                 goto free_layout;
12049         }
12050
12051         flr_state &= LCM_FL_FLR_MASK;
12052         switch (flr_state) {
12053         case LCM_FL_NONE:
12054                 rc = -EINVAL;
12055                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
12056                         progname, fname, llapi_layout_flags_string(flr_state));
12057                 goto free_layout;
12058         default:
12059                 break;
12060         }
12061
12062         /* find out mirror chunks to be verified */
12063         chunk_count = lfs_mirror_prepare_chunk(layout, chunks_array,
12064                                                ARRAY_SIZE(chunks_array));
12065         if (chunk_count < 0) {
12066                 rc = chunk_count;
12067                 goto free_layout;
12068         }
12069
12070         if (ids_nr > 0)
12071                 /* filter specified mirror ids */
12072                 filter_mirror_id(chunks_array, chunk_count, mirror_ids, ids_nr);
12073
12074         if (verbose > 2)
12075                 print_chunks(fname, chunks_array, chunk_count);
12076
12077         for (idx = 0; idx < chunk_count; idx++) {
12078                 if (chunks_array[idx].chunk.e_start >= stbuf.st_size) {
12079                         if (verbose)
12080                                 fprintf(stdout,
12081                                         "%s: '%s' chunk "DEXT" exceeds file size %#llx: skipped\n",
12082                                         progname, fname,
12083                                         PEXT(&chunks_array[idx].chunk),
12084                                         (unsigned long long)stbuf.st_size);
12085                         break;
12086                 }
12087
12088                 if (chunks_array[idx].mirror_count == 0) {
12089                         fprintf(stderr,
12090                                 "%s: '%s' chunk "DEXT" is invalid in all of the mirrors: ",
12091                                 progname, fname,
12092                                 PEXT(&chunks_array[idx].chunk));
12093                         if (verbose) {
12094                                 fprintf(stderr, "skipped\n");
12095                                 continue;
12096                         }
12097                         rc = -EINVAL;
12098                         fprintf(stderr, "failed\n");
12099                         goto free_layout;
12100                 }
12101
12102                 if (chunks_array[idx].mirror_count == 1) {
12103                         if (verbose)
12104                                 fprintf(stdout,
12105                                         "%s: '%s' chunk "DEXT" is only valid in mirror %u: skipped\n",
12106                                         progname, fname,
12107                                         PEXT(&chunks_array[idx].chunk),
12108                                         chunks_array[idx].mirror_id[0]);
12109                         continue;
12110                 }
12111
12112                 rc = llapi_lease_check(fd);
12113                 if (rc != LL_LEASE_RDLCK) {
12114                         fprintf(stderr, "%s: '%s' lost lease lock.\n",
12115                                 progname, fname);
12116                         goto free_layout;
12117                 }
12118
12119                 /* verify one chunk */
12120                 rc1 = lfs_mirror_verify_chunk(fd, stbuf.st_size,
12121                                               &chunks_array[idx], verbose);
12122                 if (rc1 < 0) {
12123                         rc2 = rc1;
12124                         if (!verbose) {
12125                                 rc = rc1;
12126                                 goto free_layout;
12127                         }
12128                 }
12129         }
12130
12131         if (rc2 < 0)
12132                 rc = rc2;
12133
12134 free_layout:
12135         llapi_layout_free(layout);
12136         llapi_lease_release(fd);
12137 close_fd:
12138         close(fd);
12139 error:
12140         return rc;
12141 }
12142
12143 /**
12144  * lfs_mirror_verify() - Parse and execute lfs mirror verify command.
12145  * @argc: The count of lfs mirror verify command line arguments.
12146  * @argv: Array of strings for lfs mirror verify command line arguments.
12147  *
12148  * This function parses lfs mirror verify command and verifies the
12149  * specified mirrored file(s).
12150  *
12151  * Return: 0 on success or a negative error code on failure.
12152  */
12153 static inline int lfs_mirror_verify(int argc, char **argv)
12154 {
12155         __u16 mirror_ids[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
12156         int ids_nr = 0;
12157         int c;
12158         int verbose = 0;
12159         int rc = 0;
12160         int rc1 = 0;
12161         char cmd[PATH_MAX];
12162
12163         struct option long_opts[] = {
12164         { .val = 'h',   .name = "help",         .has_arg = no_argument },
12165         { .val = 'o',   .name = "only",         .has_arg = required_argument },
12166         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
12167         { .name = NULL } };
12168
12169         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
12170         progname = cmd;
12171         while ((c = getopt_long(argc, argv, "ho:v", long_opts, NULL)) >= 0) {
12172                 switch (c) {
12173                 case 'o':
12174                         rc = parse_mirror_ids(mirror_ids,
12175                                               ARRAY_SIZE(mirror_ids),
12176                                               optarg);
12177                         if (rc < 0) {
12178                                 fprintf(stderr,
12179                                         "%s: bad mirror ids '%s'.\n",
12180                                         progname, optarg);
12181                                 goto error;
12182                         }
12183                         ids_nr = rc;
12184                         if (ids_nr < 2) {
12185                                 fprintf(stderr,
12186                                         "%s: at least 2 mirror ids needed with '--only' option.\n",
12187                                         progname);
12188                                 rc = CMD_HELP;
12189                                 goto error;
12190                         }
12191                         break;
12192                 case 'v':
12193                         verbose++;
12194                         break;
12195                 default:
12196                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12197                                 progname, argv[optind - 1]);
12198                         /* fallthrough */
12199                 case 'h':
12200                         rc = CMD_HELP;
12201                         goto error;
12202                 }
12203         }
12204
12205         if (argc == optind) {
12206                 fprintf(stderr, "%s: no file name given.\n", progname);
12207                 rc = CMD_HELP;
12208                 goto error;
12209         }
12210
12211         if (ids_nr > 0 && argc > optind + 1) {
12212                 fprintf(stderr,
12213                         "%s: '--only' cannot be used upon multiple files.\n",
12214                         progname);
12215                 rc = CMD_HELP;
12216                 goto error;
12217         }
12218
12219         if (ids_nr > 0) {
12220                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
12221                 if (rc < 0)
12222                         goto error;
12223         }
12224
12225         rc = 0;
12226         for (; optind < argc; optind++) {
12227                 rc1 = lfs_mirror_verify_file(argv[optind], mirror_ids, ids_nr,
12228                                              verbose);
12229                 if (rc1 < 0)
12230                         rc = rc1;
12231         }
12232 error:
12233         return rc;
12234 }
12235
12236 /**
12237  * lfs_mirror() - Parse and execute lfs mirror commands.
12238  * @argc: The count of lfs mirror command line arguments.
12239  * @argv: Array of strings for lfs mirror command line arguments.
12240  *
12241  * This function parses lfs mirror commands and performs the
12242  * corresponding functions specified in mirror_cmdlist[].
12243  *
12244  * Return: 0 on success or an error code on failure.
12245  */
12246 static int lfs_mirror(int argc, char **argv)
12247 {
12248         char cmd[PATH_MAX];
12249         int rc = 0;
12250
12251         setlinebuf(stdout);
12252
12253         Parser_init("lfs-mirror > ", mirror_cmdlist);
12254
12255         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
12256         progname = cmd;
12257         program_invocation_short_name = cmd;
12258         if (argc > 1)
12259                 rc = Parser_execarg(argc - 1, argv + 1, mirror_cmdlist);
12260         else
12261                 rc = Parser_commands();
12262
12263         return rc < 0 ? -rc : rc;
12264 }
12265
12266 static void lustre_som_swab(struct lustre_som_attrs *attrs)
12267 {
12268 #if __BYTE_ORDER == __BIG_ENDIAN
12269         __swab16s(&attrs->lsa_valid);
12270         __swab64s(&attrs->lsa_size);
12271         __swab64s(&attrs->lsa_blocks);
12272 #endif
12273 }
12274
12275 enum lfs_som_type {
12276         LFS_SOM_SIZE = 0x1,
12277         LFS_SOM_BLOCKS = 0x2,
12278         LFS_SOM_FLAGS = 0x4,
12279         LFS_SOM_ATTR_ALL = LFS_SOM_SIZE | LFS_SOM_BLOCKS |
12280                            LFS_SOM_FLAGS,
12281 };
12282
12283 static int lfs_getsom(int argc, char **argv)
12284 {
12285         const char *path;
12286         struct lustre_som_attrs *attrs;
12287         char buf[sizeof(*attrs) + 64];
12288         enum lfs_som_type type = LFS_SOM_ATTR_ALL;
12289         int rc = 0, c;
12290
12291         while ((c = getopt(argc, argv, "bfhs")) != -1) {
12292                 switch (c) {
12293                 case 'b':
12294                         type = LFS_SOM_BLOCKS;
12295                         break;
12296                 case 'f':
12297                         type = LFS_SOM_FLAGS;
12298                         break;
12299                 case 's':
12300                         type = LFS_SOM_SIZE;
12301                         break;
12302                 default:
12303                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12304                                 progname, argv[optind - 1]);
12305                         /* fallthrough */
12306                 case 'h':
12307                         return CMD_HELP;
12308                 }
12309         }
12310
12311         argc -= optind;
12312         argv += optind;
12313
12314         if (argc != 1) {
12315                 fprintf(stderr, "%s: %s\n",
12316                         progname, argc == 0 ? "miss file target" :
12317                         "input more than 2 files");
12318                 return CMD_HELP;
12319         }
12320
12321         path = argv[0];
12322         attrs = (void *)buf;
12323         rc = lgetxattr(path, "trusted.som", attrs, sizeof(buf));
12324         if (rc < 0) {
12325                 rc = -errno;
12326                 fprintf(stderr, "%s failed to get som xattr: %s (%d)\n",
12327                         argv[0], strerror(errno), errno);
12328                 return rc;
12329         }
12330
12331         lustre_som_swab(attrs);
12332
12333         switch (type) {
12334         case LFS_SOM_ATTR_ALL:
12335                 printf("file: %s size: %llu blocks: %llu flags: %x\n",
12336                        path, (unsigned long long)attrs->lsa_size,
12337                        (unsigned long long)attrs->lsa_blocks,
12338                        attrs->lsa_valid);
12339                 break;
12340         case LFS_SOM_SIZE:
12341                 printf("%llu\n", (unsigned long long)attrs->lsa_size);
12342                 break;
12343         case LFS_SOM_BLOCKS:
12344                 printf("%llu\n", (unsigned long long)attrs->lsa_blocks);
12345                 break;
12346         case LFS_SOM_FLAGS:
12347                 printf("%x\n", attrs->lsa_valid);
12348                 break;
12349         default:
12350                 fprintf(stderr, "%s: unknown option\n", progname);
12351                 return CMD_HELP;
12352         }
12353
12354         return 0;
12355 }
12356
12357 /**
12358  * lfs_mirror_list_commands() - List lfs mirror commands.
12359  * @argc: The count of command line arguments.
12360  * @argv: Array of strings for command line arguments.
12361  *
12362  * This function lists lfs mirror commands defined in mirror_cmdlist[].
12363  *
12364  * Return: 0 on success.
12365  */
12366 static int lfs_mirror_list_commands(int argc, char **argv)
12367 {
12368         char buffer[81] = "";
12369
12370         Parser_list_commands(mirror_cmdlist, buffer, sizeof(buffer),
12371                              NULL, 0, 4);
12372
12373         return 0;
12374 }
12375
12376 static int lfs_pcc_attach(int argc, char **argv)
12377 {
12378         struct option long_opts[] = {
12379         { .val = 'h',   .name = "help", .has_arg = no_argument },
12380         { .val = 'i',   .name = "id",   .has_arg = required_argument },
12381         { .name = NULL } };
12382         int c;
12383         int rc = 0;
12384         __u32 archive_id = 0;
12385         const char *path;
12386         char *end;
12387         char fullpath[PATH_MAX];
12388         enum lu_pcc_type type = LU_PCC_READWRITE;
12389
12390         optind = 0;
12391         while ((c = getopt_long(argc, argv, "hi:",
12392                                 long_opts, NULL)) != -1) {
12393                 switch (c) {
12394                 case 'i':
12395                         errno = 0;
12396                         archive_id = strtoul(optarg, &end, 0);
12397                         if (errno != 0 || *end != '\0' ||
12398                             archive_id == 0 || archive_id > UINT32_MAX) {
12399                                 fprintf(stderr,
12400                                         "error: %s: bad archive ID '%s'\n",
12401                                         progname, optarg);
12402                                 return CMD_HELP;
12403                         }
12404                         break;
12405                 default:
12406                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12407                                 progname, argv[optind - 1]);
12408                         /* fallthrough */
12409                 case 'h':
12410                         return CMD_HELP;
12411                 }
12412         }
12413
12414         if (archive_id == 0) {
12415                 fprintf(stderr, "%s: must specify attach ID\n", argv[0]);
12416                 return CMD_HELP;
12417         }
12418
12419         if (argc <= optind) {
12420                 fprintf(stderr, "%s: must specify one or more file names\n",
12421                         argv[0]);
12422                 return CMD_HELP;
12423         }
12424
12425         while (optind < argc) {
12426                 int rc2;
12427
12428                 path = argv[optind++];
12429                 if (!realpath(path, fullpath)) {
12430                         fprintf(stderr, "%s: could not find path '%s': %s\n",
12431                                 argv[0], path, strerror(errno));
12432                         if (rc == 0)
12433                                 rc = -EINVAL;
12434                         continue;
12435                 }
12436
12437                 rc2 = llapi_pcc_attach(fullpath, archive_id, type);
12438                 if (rc2 < 0) {
12439                         fprintf(stderr,
12440                                 "%s: cannot attach '%s' to PCC with archive ID '%u': %s\n",
12441                                 argv[0], path, archive_id, strerror(-rc2));
12442                         if (rc == 0)
12443                                 rc = rc2;
12444                 }
12445         }
12446         return rc;
12447 }
12448
12449 static int lfs_pcc_attach_fid(int argc, char **argv)
12450 {
12451         struct option long_opts[] = {
12452         { .val = 'h',   .name = "help", .has_arg = no_argument },
12453         { .val = 'i',   .name = "id",   .has_arg = required_argument },
12454         { .val = 'm',   .name = "mnt",  .has_arg = required_argument },
12455         { .name = NULL } };
12456         int c;
12457         int rc = 0;
12458         __u32 archive_id = 0;
12459         char *end;
12460         const char *mntpath = NULL;
12461         const char *fidstr;
12462         enum lu_pcc_type type = LU_PCC_READWRITE;
12463
12464         optind = 0;
12465         while ((c = getopt_long(argc, argv, "hi:m:",
12466                                 long_opts, NULL)) != -1) {
12467                 switch (c) {
12468                 case 'i':
12469                         errno = 0;
12470                         archive_id = strtoul(optarg, &end, 0);
12471                         if (errno != 0 || *end != '\0' ||
12472                             archive_id > UINT32_MAX) {
12473                                 fprintf(stderr,
12474                                         "error: %s: bad archive ID '%s'\n",
12475                                         argv[0], optarg);
12476                                 return CMD_HELP;
12477                         }
12478                         break;
12479                 case 'm':
12480                         mntpath = optarg;
12481                         break;
12482                 default:
12483                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12484                                 progname, argv[optind - 1]);
12485                         /* fallthrough */
12486                 case 'h':
12487                         return CMD_HELP;
12488                 }
12489         }
12490
12491         if (archive_id == 0) {
12492                 fprintf(stderr, "%s: must specify an archive ID\n", argv[0]);
12493                 return CMD_HELP;
12494         }
12495
12496         if (!mntpath) {
12497                 fprintf(stderr, "%s: must specify Lustre mount point\n",
12498                         argv[0]);
12499                 return CMD_HELP;
12500         }
12501
12502         if (argc <= optind) {
12503                 fprintf(stderr, "%s: must specify one or more fids\n", argv[0]);
12504                 return CMD_HELP;
12505         }
12506
12507         while (optind < argc) {
12508                 int rc2;
12509
12510                 fidstr = argv[optind++];
12511
12512                 rc2 = llapi_pcc_attach_fid_str(mntpath, fidstr,
12513                                                archive_id, type);
12514                 if (rc2 < 0) {
12515                         fprintf(stderr,
12516                                 "%s: cannot attach '%s' on '%s' to PCC with archive ID '%u': %s\n",
12517                                 argv[0], fidstr, mntpath, archive_id,
12518                                 strerror(rc2));
12519                 }
12520                 if (rc == 0 && rc2 < 0)
12521                         rc = rc2;
12522         }
12523         return rc;
12524 }
12525
12526 static int lfs_pcc_detach(int argc, char **argv)
12527 {
12528         struct option long_opts[] = {
12529         { .val = 'h',   .name = "help", .has_arg = no_argument },
12530         { .val = 'k',   .name = "keep", .has_arg = no_argument },
12531         { .name = NULL } };
12532         int c;
12533         int rc = 0;
12534         const char *path;
12535         char fullpath[PATH_MAX];
12536         __u32 detach_opt = PCC_DETACH_OPT_UNCACHE;
12537
12538         optind = 0;
12539         while ((c = getopt_long(argc, argv, "hk",
12540                                 long_opts, NULL)) != -1) {
12541                 switch (c) {
12542                 case 'k':
12543                         detach_opt = PCC_DETACH_OPT_NONE;
12544                         break;
12545                 default:
12546                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12547                                 progname, argv[optind - 1]);
12548                         /* fallthrough */
12549                 case 'h':
12550                         return CMD_HELP;
12551                 }
12552         }
12553
12554         while (optind < argc) {
12555                 int rc2;
12556
12557                 path = argv[optind++];
12558                 if (!realpath(path, fullpath)) {
12559                         fprintf(stderr, "%s: could not find path '%s': %s\n",
12560                                 argv[0], path, strerror(errno));
12561                         if (rc == 0)
12562                                 rc = -EINVAL;
12563                         continue;
12564                 }
12565
12566                 rc2 = llapi_pcc_detach_file(fullpath, detach_opt);
12567                 if (rc2 < 0) {
12568                         rc2 = -errno;
12569                         fprintf(stderr,
12570                                 "%s: cannot detach '%s' from PCC: %s\n",
12571                                 argv[0], path, strerror(errno));
12572                         if (rc == 0)
12573                                 rc = rc2;
12574                 }
12575         }
12576         return rc;
12577 }
12578
12579 static int lfs_pcc_detach_fid(int argc, char **argv)
12580 {
12581         struct option long_opts[] = {
12582         { .val = 'h',   .name = "help", .has_arg = no_argument },
12583         { .val = 'k',   .name = "keep", .has_arg = no_argument },
12584         { .name = NULL } };
12585         int c;
12586         int rc = 0;
12587         const char *fid;
12588         const char *mntpath;
12589         __u32 detach_opt = PCC_DETACH_OPT_UNCACHE;
12590
12591         optind = 0;
12592         while ((c = getopt_long(argc, argv, "hk",
12593                                 long_opts, NULL)) != -1) {
12594                 switch (c) {
12595                 case 'k':
12596                         detach_opt = PCC_DETACH_OPT_NONE;
12597                         break;
12598                 default:
12599                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12600                                 progname, argv[optind - 1]);
12601                         /* fallthrough */
12602                 case 'h':
12603                         return CMD_HELP;
12604                 }
12605         }
12606
12607         mntpath = argv[optind++];
12608
12609         while (optind < argc) {
12610                 int rc2;
12611
12612                 fid = argv[optind++];
12613
12614                 rc2 = llapi_pcc_detach_fid_str(mntpath, fid, detach_opt);
12615                 if (rc2 < 0) {
12616                         fprintf(stderr,
12617                                 "%s: cannot detach '%s' on '%s' from PCC: %s\n",
12618                                 argv[0], fid, mntpath, strerror(-rc2));
12619                         if (rc == 0)
12620                                 rc = rc2;
12621                 }
12622         }
12623         return rc;
12624 }
12625
12626 static int lfs_pcc_state(int argc, char **argv)
12627 {
12628         int rc = 0;
12629         const char *path;
12630         char fullpath[PATH_MAX];
12631         struct lu_pcc_state state;
12632
12633         optind = 1;
12634
12635         if (argc <= 1) {
12636                 fprintf(stderr, "%s: must specify one or more file names\n",
12637                         progname);
12638                 return CMD_HELP;
12639         }
12640
12641         while (optind < argc) {
12642                 int rc2;
12643
12644                 path = argv[optind++];
12645                 if (!realpath(path, fullpath)) {
12646                         fprintf(stderr, "%s: could not find path '%s': %s\n",
12647                                 argv[0], path, strerror(errno));
12648                         if (rc == 0)
12649                                 rc = -EINVAL;
12650                         continue;
12651                 }
12652
12653                 rc2 = llapi_pcc_state_get(fullpath, &state);
12654                 if (rc2 < 0) {
12655                         if (rc == 0)
12656                                 rc = rc2;
12657                         fprintf(stderr,
12658                                 "%s: cannot get PCC state of '%s': %s\n",
12659                                 argv[0], path, strerror(-rc2));
12660                         continue;
12661                 }
12662
12663                 printf("file: %s", path);
12664                 printf(", type: %s", pcc_type2string(state.pccs_type));
12665                 if (state.pccs_type == LU_PCC_NONE &&
12666                     state.pccs_open_count == 0) {
12667                         printf("\n");
12668                         continue;
12669                 }
12670
12671                 printf(", PCC file: %s", state.pccs_path);
12672                 printf(", user number: %u", state.pccs_open_count);
12673                 printf(", flags: %x", state.pccs_flags);
12674                 printf("\n");
12675         }
12676         return rc;
12677 }
12678
12679 /**
12680  * lfs_pcc_list_commands() - List lfs pcc commands.
12681  * @argc: The count of command line arguments.
12682  * @argv: Array of strings for command line arguments.
12683  *
12684  * This function lists lfs pcc commands defined in pcc_cmdlist[].
12685  *
12686  * Return: 0 on success.
12687  */
12688 static int lfs_pcc_list_commands(int argc, char **argv)
12689 {
12690         char buffer[81] = "";
12691
12692         Parser_list_commands(pcc_cmdlist, buffer, sizeof(buffer),
12693                              NULL, 0, 4);
12694
12695         return 0;
12696 }
12697
12698 /**
12699  * lfs_pcc() - Parse and execute lfs pcc commands.
12700  * @argc: The count of lfs pcc command line arguments.
12701  * @argv: Array of strings for lfs pcc command line arguments.
12702  *
12703  * This function parses lfs pcc commands and performs the
12704  * corresponding functions specified in pcc_cmdlist[].
12705  *
12706  * Return: 0 on success or an error code on failure.
12707  */
12708 static int lfs_pcc(int argc, char **argv)
12709 {
12710         char cmd[PATH_MAX];
12711         int rc = 0;
12712
12713         setlinebuf(stdout);
12714
12715         Parser_init("lfs-pcc > ", pcc_cmdlist);
12716
12717         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
12718         progname = cmd;
12719         program_invocation_short_name = cmd;
12720         if (argc > 1)
12721                 rc = Parser_execarg(argc - 1, argv + 1, pcc_cmdlist);
12722         else
12723                 rc = Parser_commands();
12724
12725         return rc < 0 ? -rc : rc;
12726 }
12727
12728 static int lfs_list_commands(int argc, char **argv)
12729 {
12730         char buffer[81] = ""; /* 80 printable chars + terminating NUL */
12731
12732         Parser_list_commands(cmdlist, buffer, sizeof(buffer), NULL, 0, 4);
12733
12734         return 0;
12735 }
12736
12737 int main(int argc, char **argv)
12738 {
12739         int rc;
12740
12741         /* Ensure that liblustreapi constructor has run */
12742         if (!llapi_liblustreapi_initialized())
12743                 fprintf(stderr, "liblustreapi was not properly initialized\n");
12744
12745         setlinebuf(stdout);
12746         opterr = 0;
12747
12748         Parser_init("lfs > ", cmdlist);
12749
12750         progname = program_invocation_short_name; /* Used in error messages */
12751         if (argc > 1) {
12752                 llapi_set_command_name(argv[1]);
12753                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
12754                 llapi_clear_command_name();
12755         } else {
12756                 rc = Parser_commands();
12757         }
12758
12759         return rc < 0 ? -rc : rc;
12760 }
12761
12762 #ifdef _LUSTRE_IDL_H_
12763 /* Everything we need here should be included by lustreapi.h. */
12764 # error "lfs should not depend on lustre_idl.h"
12765 #endif /* _LUSTRE_IDL_H_ */