Whamcloud - gitweb
LU-14786 lod: create missing debugfs file
[fs/lustre-release.git] / lustre / utils / lfs.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * lustre/utils/lfs.c
32  *
33  * Author: Peter J. Braam <braam@clusterfs.com>
34  * Author: Phil Schwan <phil@clusterfs.com>
35  * Author: Robert Read <rread@clusterfs.com>
36  */
37
38 /* for O_DIRECTORY */
39 #ifndef _GNU_SOURCE
40 #define _GNU_SOURCE
41 #endif
42
43 #include <stdlib.h>
44 #include <stdio.h>
45 #include <inttypes.h>
46 #include <getopt.h>
47 #include <string.h>
48 #include <mntent.h>
49 #include <unistd.h>
50 #include <errno.h>
51 #include <err.h>
52 #include <pwd.h>
53 #include <grp.h>
54 #include <sys/ioctl.h>
55 #include <sys/quota.h>
56 #include <sys/time.h>
57 #include <sys/types.h>
58 #include <sys/stat.h>
59 #include <sys/param.h>
60 #include <sys/xattr.h>
61 #include <fcntl.h>
62 #include <dirent.h>
63 #include <time.h>
64 #include <ctype.h>
65 #include <zlib.h>
66 #include <libgen.h>
67 #include <asm/byteorder.h>
68 #include "lfs_project.h"
69
70 #include <libcfs/util/string.h>
71 #include <libcfs/util/ioctl.h>
72 #include <libcfs/util/parser.h>
73 #include <libcfs/util/string.h>
74 #include <lustre/lustreapi.h>
75 #include <linux/lustre/lustre_ver.h>
76 #include <linux/lustre/lustre_param.h>
77 #include <linux/lnet/nidstr.h>
78 #include <lnetconfig/cyaml.h>
79 #include "lstddef.h"
80
81 /* all functions */
82 static int lfs_find(int argc, char **argv);
83 static int lfs_getstripe(int argc, char **argv);
84 static int lfs_getdirstripe(int argc, char **argv);
85 static int lfs_setdirstripe(int argc, char **argv);
86 static int lfs_rmentry(int argc, char **argv);
87 static int lfs_unlink_foreign(int argc, char **argv);
88 static int lfs_osts(int argc, char **argv);
89 static int lfs_mdts(int argc, char **argv);
90 static int lfs_df(int argc, char **argv);
91 static int lfs_getname(int argc, char **argv);
92 static int lfs_check(int argc, char **argv);
93 #ifdef HAVE_SYS_QUOTA_H
94 static int lfs_setquota(int argc, char **argv);
95 static int lfs_quota(int argc, char **argv);
96 static int lfs_project(int argc, char **argv);
97 #endif
98 static int lfs_flushctx(int argc, char **argv);
99 static int lfs_poollist(int argc, char **argv);
100 static int lfs_changelog(int argc, char **argv);
101 static int lfs_changelog_clear(int argc, char **argv);
102 static int lfs_fid2path(int argc, char **argv);
103 static int lfs_path2fid(int argc, char **argv);
104 static int lfs_rmfid(int argc, char **argv);
105 static int lfs_data_version(int argc, char **argv);
106 static int lfs_hsm_state(int argc, char **argv);
107 static int lfs_hsm_set(int argc, char **argv);
108 static int lfs_hsm_clear(int argc, char **argv);
109 static int lfs_hsm_action(int argc, char **argv);
110 static int lfs_hsm_archive(int argc, char **argv);
111 static int lfs_hsm_restore(int argc, char **argv);
112 static int lfs_hsm_release(int argc, char **argv);
113 static int lfs_hsm_remove(int argc, char **argv);
114 static int lfs_hsm_cancel(int argc, char **argv);
115 static int lfs_swap_layouts(int argc, char **argv);
116 static int lfs_mv(int argc, char **argv);
117 static int lfs_ladvise(int argc, char **argv);
118 static int lfs_getsom(int argc, char **argv);
119 static int lfs_heat_get(int argc, char **argv);
120 static int lfs_heat_set(int argc, char **argv);
121 static int lfs_mirror(int argc, char **argv);
122 static int lfs_mirror_list_commands(int argc, char **argv);
123 static int lfs_list_commands(int argc, char **argv);
124 static inline int lfs_mirror_resync(int argc, char **argv);
125 static inline int lfs_mirror_verify(int argc, char **argv);
126 static inline int lfs_mirror_read(int argc, char **argv);
127 static inline int lfs_mirror_write(int argc, char **argv);
128 static inline int lfs_mirror_copy(int argc, char **argv);
129 static int lfs_pcc_attach(int argc, char **argv);
130 static int lfs_pcc_attach_fid(int argc, char **argv);
131 static int lfs_pcc_detach(int argc, char **argv);
132 static int lfs_pcc_detach_fid(int argc, char **argv);
133 static int lfs_pcc_state(int argc, char **argv);
134 static int lfs_pcc(int argc, char **argv);
135 static int lfs_pcc_list_commands(int argc, char **argv);
136 static int lfs_migrate_to_dom(int fd, int fdv, char *name,
137                               __u64 migration_flags,
138                               struct llapi_stripe_param *param,
139                               struct llapi_layout *layout);
140
141 struct pool_to_id_cbdata {
142         const char *pool;
143         __u32 id;
144 };
145 static int find_comp_id_by_pool(struct llapi_layout *layout, void *cbdata);
146 static int find_mirror_id_by_pool(struct llapi_layout *layout, void *cbdata);
147
148 enum setstripe_origin {
149         SO_SETSTRIPE,
150         SO_MIGRATE,
151         SO_MIGRATE_MDT,
152         SO_MIRROR_CREATE,
153         SO_MIRROR_EXTEND,
154         SO_MIRROR_SPLIT,
155         SO_MIRROR_DELETE,
156 };
157
158 static int lfs_setstripe_internal(int argc, char **argv,
159                                   enum setstripe_origin opc);
160
161 static inline int lfs_setstripe(int argc, char **argv)
162 {
163         return lfs_setstripe_internal(argc, argv, SO_SETSTRIPE);
164 }
165
166 static inline int lfs_setstripe_migrate(int argc, char **argv)
167 {
168         return lfs_setstripe_internal(argc, argv, SO_MIGRATE);
169 }
170
171 static inline int lfs_mirror_create(int argc, char **argv)
172 {
173         return lfs_setstripe_internal(argc, argv, SO_MIRROR_CREATE);
174 }
175
176 static inline int lfs_mirror_extend(int argc, char **argv)
177 {
178         return lfs_setstripe_internal(argc, argv, SO_MIRROR_EXTEND);
179 }
180
181 static inline int lfs_mirror_split(int argc, char **argv)
182 {
183         return lfs_setstripe_internal(argc, argv, SO_MIRROR_SPLIT);
184 }
185
186 static inline int lfs_mirror_delete(int argc, char **argv)
187 {
188         return lfs_setstripe_internal(argc, argv, SO_MIRROR_DELETE);
189 }
190
191 /* Setstripe and migrate share mostly the same parameters */
192 #define SSM_CMD_COMMON(cmd) \
193         "usage: "cmd" [--component-end|-E COMP_END]\n"                  \
194         "                 [--stripe-count|-c STRIPE_COUNT]\n"           \
195         "                 [--overstripe-count|-C STRIPE_COUNT]\n"       \
196         "                 [--stripe-index|-i START_OST_IDX]\n"          \
197         "                 [--stripe-size|-S STRIPE_SIZE]\n"             \
198         "                 [--extension-size|--ext-size|-z]\n"           \
199         "                 [--help|-h] [--layout|-L PATTERN]\n"          \
200         "                 [--mirror_count|-N[MIRROR_COUNT]]\n"          \
201         "                 [--ost|-o OST_INDICES]\n"                     \
202         "                 [--pool|-p POOL_NAME]\n"                      \
203         "                 [--yaml|-y YAML_TEMPLATE_FILE]\n"             \
204         "                 [--copy=LUSTRE_SRC]\n"
205
206 #define SSM_HELP_COMMON \
207         "\tSTRIPE_COUNT: Number of OSTs to stripe on (0=fs default, -1 all)\n" \
208         "\t              Using -C instead of -c allows overstriping, which\n"  \
209         "\t              will place more than one stripe per OST if\n"         \
210         "\t              stripe_count is greater than the number of OSTs.\n"   \
211         "\tSTART_OST_IDX: OST index of first stripe (-1=default round robin)\n"\
212         "\tSTRIPE_SIZE:  Number of bytes on each OST (0=fs default)\n"         \
213         "\t              Optional K, M, or G suffix (for KB, MB, GB\n"         \
214         "\t              respectively).  Must be a multiple of 64KiB.\n"       \
215         "\tEXTENSION_SIZE:\n"                                                  \
216         "\t              Number of bytes the previous component is extended\n" \
217         "\t              each time. Optional K, M, or G suffix (for KB,\n"     \
218         "\t              MB, GB respectively)\n"                               \
219         "\tPOOL_NAME:    Name of OST pool to use (default none)\n"             \
220         "\tLAYOUT:       stripe pattern type: raid0, mdt (default raid0)\n"    \
221         "\tOST_INDICES:  List of OST indices, can be repeated multiple times\n"\
222         "\t              Indices be specified in a format of:\n"               \
223         "\t                -o OST_1,OST_I-OST_J,OST_N\n"                       \
224         "\t              Or:\n"                                                \
225         "\t                -o OST_1 -o OST_I-OST_J -o OST_N\n"                 \
226         "\t              If --pool is set with --ost then the OSTs\n"          \
227         "\t              must be the members of the pool.\n"                   \
228         "\tCOMP_END:     Extent end of component, start after previous end.\n" \
229         "\t              Optional K, M, or G suffix (for KiB, MiB, GiB), or\n" \
230         "\t              -1 or 'eof' for max file size). Must be a multiple\n" \
231         "\t              of stripe_size and a multiple of 64KiB.\n"            \
232         "\tYAML_TEMPLATE_FILE:\n"                                              \
233         "\t              YAML layout template file, can't be used with -c,\n"  \
234         "\t              -i, -S, -p, -o, or -E arguments.\n"                   \
235         "\tLUSTRE_SRC:   Lustre file/dir whose layout info is used to set\n"   \
236         "\t              another lustre file or directory, can't used with\n"  \
237         "\t              -c, -i, -S, -p, -o, or -E arguments.\n"
238
239 #define MIRROR_CREATE_HELP                                                     \
240         "\tMIRROR_COUNT: Number of mirrors to be created with the upcoming\n"  \
241         "\t              setstripe layout options\n"                           \
242         "\t              It defaults to 1 if not specified; if specified,\n"   \
243         "\t              it must follow the option without a space.\n"         \
244         "\t              The option can also be repeated multiple times to\n"  \
245         "\t              separate mirrors that have different layouts.\n"      \
246         "\tSETSTRIPE_OPTIONS: Mirror layout as with 'setstripe'\n"             \
247         "\t              It can be a plain layout or a composite layout.\n"    \
248         "\t              If not specified, the stripe options inherited\n"     \
249         "\t              from the previous component will be used.\n"          \
250         "\tFLAGS:        set flags to the component of the current mirror.\n"  \
251         "\t              Only \"prefer\" flag is supported so far.\n"
252
253 #define MIRROR_EXTEND_HELP                                                     \
254         MIRROR_CREATE_HELP                                                     \
255         "\tVICTIM_FILE:  The layout of victim_file will be split and used\n"   \
256         "\t              as a mirror added to the mirrored file.\n"            \
257         "\tno-verify:    This option indicates not to verify the mirror(s)\n"  \
258         "\t              from victim file(s) in case the victim file(s)\n"     \
259         "\t              contains the same data as the original mirrored\n"    \
260         "\t              file.\n"
261
262 #define MIRROR_EXTEND_USAGE                                                    \
263         "                 {--mirror-count|-N[mirror_count]}\n"                 \
264         "                 [SETSTRIPE_OPTIONS|-f|--file VICTIM_FILE]\n"         \
265         "                 [--no-verify]\n"
266
267 #define SETSTRIPE_USAGE                                                 \
268         SSM_CMD_COMMON("setstripe")                                     \
269         MIRROR_EXTEND_USAGE                                             \
270         "                 <directory|filename>\n"                       \
271         SSM_HELP_COMMON                                                 \
272         MIRROR_EXTEND_HELP
273
274 #define MIGRATE_USAGE                                                   \
275         SSM_CMD_COMMON("migrate  ")                                     \
276         "                 [--block|-b] [--non-block|-n]\n"              \
277         "                 [--non-direct|-D] [--verbose|-v]\n"           \
278         "                 <filename>\n"                                 \
279         SSM_HELP_COMMON                                                 \
280         "\n"                                                            \
281         "\tblock:        Block file access during data migration (default)\n" \
282         "\tnon-block:    Abort migrations if concurrent access is detected\n" \
283         "\tnon-direct:   Do not use direct I/O to copy file contents\n" \
284         "\tverbose:      Print each filename as it is migrated\n"       \
285
286 #define SETDIRSTRIPE_USAGE                                              \
287         "               [--mdt-count|-c stripe_count>\n"                \
288         "               [--help|-h] [--mdt-hash|-H mdt_hash]\n"         \
289         "               [--mdt-index|-i mdt_index[,mdt_index,...]\n"    \
290         "               [--default|-D] [--mode|-o mode]\n"              \
291         "               [--max-inherit|-X max_inherit]\n"               \
292         "               [--max-inherit-rr max_inherit_rr] <dir>\n"      \
293         "\tstripe_count: stripe count of the striped directory\n"       \
294         "\tmdt_index: MDT index of first stripe\n"                      \
295         "\tmdt_hash:  hash type of the striped directory. mdt types:\n" \
296         "       crush     CRUSH hash algorithm (default)\n" \
297         "       fnv_1a_64 FNV-1a hash algorithm\n"              \
298         "       all_char  sum of characters % MDT_COUNT (not recommended)\n" \
299         "\tdefault_stripe: set default dirstripe of the directory\n"    \
300         "\tmode: the file access permission of the directory (octal)\n" \
301         "To create dir with a foreign (free format) layout :\n"         \
302         "setdirstripe|mkdir --foreign[=FOREIGN_TYPE] -x|-xattr STRING " \
303                 "[--mode|-o MODE] [--flags HEX] <dir>\n" \
304         "\tmode: the file access permissions of the directory\n"        \
305         "\tforeign_type: none, daos, symlink, or numeric value\n"
306
307 /**
308  * command_t mirror_cmdlist - lfs mirror commands.
309  */
310 command_t mirror_cmdlist[] = {
311         { .pc_name = "create", .pc_func = lfs_mirror_create,
312           .pc_help = "Create a mirrored file.\n"
313                 "usage: lfs mirror create {--mirror-count|-N[MIRROR_COUNT]}\n"
314                 "\t\t[SETSTRIPE_OPTIONS] <filename|directory> ...\n"
315           MIRROR_CREATE_HELP },
316         { .pc_name = "delete", .pc_func = lfs_mirror_delete,
317           .pc_help = "Delete a mirror from a file.\n"
318         "usage: lfs mirror delete {--mirror-id MIRROR_ID|-p POOL|\n"
319         "\t               --component-id|--comp-id|-I COMP_ID} <mirror_file>\n"
320         },
321         { .pc_name = "extend", .pc_func = lfs_mirror_extend,
322           .pc_help = "Extend a mirrored file.\n"
323                 "usage: lfs mirror extend {--mirror-count|-N[MIRROR_COUNT]}\n"
324                 "\t\t[--no-verify] [SETSTRIPE_OPTIONS|-f VICTIM_FILE] ... <filename> ...\n"
325           MIRROR_EXTEND_HELP },
326         { .pc_name = "split", .pc_func = lfs_mirror_split,
327           .pc_help = "Split a mirrored file.\n"
328         "usage: lfs mirror split [--destroy|-d] [-f NEW_FILE] [--help|-h]\n"
329         "\t\t{--mirror-id MIRROR_ID|--component-id|-I COMP_ID|-p POOL}\n"
330         "\t\t<mirrored file> ...\n"
331         "\tMIRROR_ID: The numerical unique identifier for a mirror.\n"
332         "\t           It can be fetched by the 'lfs getstripe' command.\n"
333         "\tCOMP_ID:   Unique component ID within a mirror.\n"
334         "\tPOOL:      Components using specified pool.\n"
335         "\tNEW_FILE:  This option indicates the layout of the split\n"
336         "\t           mirror will be stored into. If not specified,\n"
337         "\t           a new file named <mirrored_file>.mirror~MIRROR_ID\n"
338         "\t           will be used.\n" },
339         { .pc_name = "read", .pc_func = lfs_mirror_read,
340           .pc_help = "Read the content of a specified mirror of a file.\n"
341                 "usage: lfs mirror read {--mirror-id|-N MIRROR_ID}\n"
342                 "\t\t[--outfile|-o <output_file>] <mirrored_file>\n" },
343         { .pc_name = "write", .pc_func = lfs_mirror_write,
344           .pc_help = "Write to a specified mirror of a file.\n"
345                 "usage: lfs mirror write {--mirror-id|-N MIRROR_ID}\n"
346                 "\t\t[--inputfile|-i <input_file>] <mirrored_file>\n" },
347         { .pc_name = "copy", .pc_func = lfs_mirror_copy,
348           .pc_help = "Copy a specified mirror to other mirror(s) of a file.\n"
349                 "usage: lfs mirror copy {--read-mirror|-i MIRROR_ID0}\n"
350                 "\t\t{--write-mirror|-o MIRROR_ID1[,...]} <mirrored_file>\n" },
351         { .pc_name = "resync", .pc_func = lfs_mirror_resync,
352           .pc_help = "Resynchronizes out-of-sync mirrored file(s).\n"
353                 "usage: lfs mirror resync [--only MIRROR_ID[,...]>]\n"
354                 "\t\t<mirrored_file> [<mirrored_file2>...]\n" },
355         { .pc_name = "verify", .pc_func = lfs_mirror_verify,
356           .pc_help = "Verify mirrored file(s).\n"
357                 "usage: lfs mirror verify [--only MIRROR_ID[,...]]\n"
358                 "\t\t[--verbose|-v] <mirrored_file> [<mirrored_file2> ...]\n" },
359         { .pc_name = "list-commands", .pc_func = lfs_mirror_list_commands,
360           .pc_help = "list commands supported by lfs mirror"},
361         { .pc_name = "help", .pc_func = Parser_help, .pc_help = "help" },
362         { .pc_name = "exit", .pc_func = Parser_quit, .pc_help = "quit" },
363         { .pc_name = "quit", .pc_func = Parser_quit, .pc_help = "quit" },
364         { .pc_help = NULL }
365 };
366
367 /**
368  * command_t pcc_cmdlist - lfs pcc commands.
369  */
370 command_t pcc_cmdlist[] = {
371         { .pc_name = "attach", .pc_func = lfs_pcc_attach,
372           .pc_help = "Attach given files to the Persistent Client Cache.\n"
373                 "usage: lfs pcc attach <--id|-i NUM> <file> ...\n"
374                 "\t-i: archive id for RW-PCC\n" },
375         { .pc_name = "attach_fid", .pc_func = lfs_pcc_attach_fid,
376           .pc_help = "Attach given files into PCC by FID(s).\n"
377                 "usage: lfs pcc attach_id {--id|-i NUM} {--mnt|-m MOUNTPOINT} FID ...\n"
378                 "\t-i: archive id for RW-PCC\n"
379                 "\t-m: Lustre mount point\n" },
380         { .pc_name = "state", .pc_func = lfs_pcc_state,
381           .pc_help = "Display the PCC state for given files.\n"
382                 "usage: lfs pcc state <file> ...\n" },
383         { .pc_name = "detach", .pc_func = lfs_pcc_detach,
384           .pc_help = "Detach given files from the Persistent Client Cache.\n"
385                 "usage: lfs pcc detach <file> ...\n" },
386         { .pc_name = "detach_fid", .pc_func = lfs_pcc_detach_fid,
387           .pc_help = "Detach given files from PCC by FID(s).\n"
388                 "usage: lfs pcc detach_fid <mntpath> <fid>...\n" },
389         { .pc_name = "list-commands", .pc_func = lfs_pcc_list_commands,
390           .pc_help = "list commands supported by lfs pcc"},
391         { .pc_name = "help", .pc_func = Parser_help, .pc_help = "help" },
392         { .pc_name = "exit", .pc_func = Parser_quit, .pc_help = "quit" },
393         { .pc_name = "quit", .pc_func = Parser_quit, .pc_help = "quit" },
394         { .pc_help = NULL }
395 };
396
397 /* all available commands */
398 command_t cmdlist[] = {
399         {"setstripe", lfs_setstripe, 0,
400          "To create a file with specified striping/composite layout, or\n"
401          "create/replace the default layout on an existing directory:\n"
402          SSM_CMD_COMMON("setstripe")
403          "                 [--mode MODE]\n"
404          "                 <directory|filename>\n"
405          " or\n"
406          "To add component(s) to an existing composite file:\n"
407          SSM_CMD_COMMON("setstripe --component-add")
408          SSM_HELP_COMMON
409          "To totally delete the default striping from an existing directory:\n"
410          "usage: setstripe [--delete|-d] <directory>\n"
411          " or\n"
412          "To create a mirrored file or set s default mirror layout on a directory:\n"
413          "usage: setstripe {--mirror-count|-N}[MIRROR_COUNT] [SETSTRIPE_OPTIONS] <directory|filename>\n"
414          " or\n"
415          "To delete the last component(s) from an existing composite file\n"
416          "(note that this will also delete any data in those components):\n"
417          "usage: setstripe --component-del [--component-id|-I COMP_ID]\n"
418          "                               [--component-flags|-F COMP_FLAGS]\n"
419          "                               <filename>\n"
420          "\tCOMP_ID:     Unique component ID to delete\n"
421          "\tCOMP_FLAGS:  'init' indicating all instantiated components\n"
422          "\t             '^init' indicating all uninstantiated components\n"
423          "\t-I and -F cannot be specified at the same time\n"
424          " or\n"
425          "To set or clear flags on a specific component\n"
426          "(note that this command can only be applied to mirrored files:\n"
427          "usage: setstripe --comp-set {-I COMP_ID|--comp-flags=COMP_FLAGS}\n"
428          "                            <filename>\n"
429          " or\n"
430          "To create a file with a foreign (free format) layout:\n"
431          "usage: setstripe --foreign[=FOREIGN_TYPE]\n"
432          "                 --xattr|-x LAYOUT_STRING [--flags HEX]\n"
433          "                 [--mode MODE] <filename>\n"},
434         {"getstripe", lfs_getstripe, 0,
435          "To list the layout pattern for a given file or files in a\n"
436          "directory or recursively for all files in a directory tree.\n"
437          "usage: getstripe [--ost|-O UUID] [--quiet|-q] [--verbose|-v]\n"
438          "                 [--stripe-count|-c] [--stripe-index|-i] [--fid|-F]\n"
439          "                 [--pool|-p] [--stripe-size|-S] [--directory|-d]\n"
440          "                 [--mdt-index|-m] [--recursive|-r] [--raw|-R]\n"
441          "                 [--layout|-L] [--generation|-g] [--yaml|-y]\n"
442          "                 [--help|-h] [--component-id|-I[=COMP_ID]]\n"
443          "                 [--component-flags[=COMP_FLAGS]]\n"
444          "                 [--component-count]\n"
445          "                 [--extension-size|--ext-size|-z]\n"
446          "                 [--component-start[=[+-]COMP_START]]\n"
447          "                 [--component-end[=[+-]COMP_END]|-E[[+-]comp_end]]\n"
448          "                 [[!] --mirror-index=[+-]INDEX |\n"
449          "                 [!] --mirror-id=[+-]MIRROR_ID] [--mirror-count|-N]\n"
450          "                 <directory|filename> ..."},
451         {"setdirstripe", lfs_setdirstripe, 0,
452          "Create striped directory on specified MDT, same as mkdir.\n"
453          "May be restricted to root or group users, depending on settings.\n"
454          "usage: setdirstripe [OPTION] <directory>\n"
455          SETDIRSTRIPE_USAGE},
456         {"getdirstripe", lfs_getdirstripe, 0,
457          "To list the layout pattern info for a given directory\n"
458          "or recursively for all directories in a directory tree.\n"
459          "usage: getdirstripe [--mdt-count|-c] [--mdt-index|-m|-i]\n"
460          "                    [--help|-h] [--mdt-hash|-H] [--obd|-O UUID]\n"
461          "                    [--recursive|-r] [--yaml|-y]\n"
462          "                    [--verbose|-v] [--default|-D]\n"
463          "                    [--max-inherit|-X]\n"
464          "                    [--max-inherit-rr] <dir> ..."},
465         {"mkdir", lfs_setdirstripe, 0,
466          "Create striped directory on specified MDT, same as setdirstripe.\n"
467          "usage: mkdir [OPTION] <directory>\n"
468          SETDIRSTRIPE_USAGE},
469         {"rm_entry", lfs_rmentry, 0,
470          "To remove the name entry of the remote directory. Note: This\n"
471          "command will only delete the name entry, i.e. the remote directory\n"
472          "will become inaccessable after this command. This can only be done\n"
473          "by the administrator\n"
474          "usage: rm_entry <dir>\n"},
475         {"unlink_foreign", lfs_unlink_foreign, 0,
476          "To remove the foreign file/dir.\n"
477          "Note: This is for files/dirs prevented to be removed using\n"
478          "unlink/rmdir, but works also for regular ones\n"
479          "usage: unlink_foreign <foreign_dir/file> [<foreign_dir/file> ...]\n"},
480         {"pool_list", lfs_poollist, 0,
481          "List pools or pool OSTs\n"
482          "usage: pool_list <fsname>[.<pool>] | <pathname>\n"},
483         {"find", lfs_find, 0,
484          "find files matching given attributes recursively in directory tree.\n"
485          "usage: find <directory|filename> ...\n"
486          "     [[!] --atime|-A [+-]N[smhdwy]] [[!] --ctime|-C [+-]N[smhdwy]]\n"
487          "     [[!] --mtime|-M [+-]N[smhdwy]]\n"
488          "     [[!] --btime|--Btime|-B [+-]N[smhdwy]] [--help|-h]\n"
489          "     [[!] --newer[XY] <reference>] [[!] --blocks|-b N]\n"
490          "     [--maxdepth|-D N] [[!] --mdt-index|--mdt|-m <uuid|index,...>]\n"
491          "     [[!] --name|-n <pattern>] [[!] --ost|-O <uuid|index,...>]\n"
492          "     [[!] --perm [/-]mode] [[!] --pool <pool>] [--print|-P]\n"
493          "     [--print0|-0] [[!] --projid <projid>]\n"
494          "     [[!] --size|-s [+-]N[bkMGTPE]]\n"
495          "     [[!] --stripe-count|-c [+-]<stripes>]\n"
496          "     [[!] --stripe-index|-i <index,...>]\n"
497          "     [[!] --stripe-size|-S [+-]N[kMGT]] [[!] --type|-t <filetype>]\n"
498          "     [[!] --extension-size|--ext-size|-z [+-]N[kMGT]]\n"
499          "     [[!] --gid|-g|--group|-G <gid>|<gname>]\n"
500          "     [[!] --uid|-u|--user|-U <uid>|<uname>]\n"
501          "     [[!] --layout|-L released,raid0,mdt]\n"
502          "     [[!] --foreign[=<foreign_type>]]\n"
503          "     [[!] --component-count [+-]<comp_cnt>]\n"
504          "     [[!] --component-start [+-]N[kMGTPE]]\n"
505          "     [[!] --component-end|-E [+-]N[kMGTPE]]\n"
506          "     [[!] --component-flags {init,stale,prefer,offline,nosync,extension}]\n"
507          "     [[!] --mirror-count|-N [+-]<n>]\n"
508          "     [[!] --mirror-state <[^]state>]\n"
509          "     [[!] --mdt-count|-T [+-]<stripes>]\n"
510          "     [[!] --mdt-hash|-H <[^][blm],[^]fnv_1a_64,all_char,crush,...>\n"
511          "     [[!] --mdt-index|-m <uuid|index,...>]\n"
512          "\t !: used before an option indicates 'NOT' requested attribute\n"
513          "\t -: used before a value indicates less than requested value\n"
514          "\t +: used before a value indicates more than requested value\n"
515          "\t ^: used before a flag indicates to exclude it\n"},
516         {"check", lfs_check, 0,
517          "Display the status of MGTs, MDTs or OSTs (as specified in the command)\n"
518          "or all the servers (MGTs, MDTs and OSTs).\n"
519          "usage: check {mgts|osts|mdts|all}"},
520         {"osts", lfs_osts, 0, "list OSTs connected to client "
521          "[for specified path only]\n" "usage: osts [path]"},
522         {"mdts", lfs_mdts, 0, "list MDTs connected to client "
523          "[for specified path only]\n" "usage: mdts [path]"},
524         {"df", lfs_df, 0,
525          "report filesystem disk space usage or inodes usage "
526          "of each MDS and all OSDs or a batch belonging to a specific pool.\n"
527          "Usage: df [--inodes|-i] [--human-readable|-h] [--lazy|-l]\n"
528          "          [--pool|-p <fsname>[.<pool>]] [path]"},
529         {"getname", lfs_getname, 0,
530          "list instances and specified mount points [for specified path only]\n"
531          "Usage: getname [--help|-h] [--instance|-i] [--fsname|-n] [path ...]"},
532 #ifdef HAVE_SYS_QUOTA_H
533         {"setquota", lfs_setquota, 0, "Set filesystem quotas.\n"
534          "usage: setquota {-u|-g|-p} UNAME|UID|GNAME|GID|PROJID\n"
535          "                -b BLOCK_SOFTLIMIT -B BLOCK_HARDLIMIT\n"
536          "                -i INODE_SOFTLIMIT -I INODE_HARDLIMIT <filesystem>\n"
537          "       setquota {-u|--user USER|UID|-g|--group GROUP|GID|-p|--projid PROJID}\n"
538          "                [--block-softlimit BLOCK_SOFTLIMIT]\n"
539          "                [--block-hardlimit BLOCK_HARDLIMIT]\n"
540          "                [--inode-softlimit INODE_SOFTLIMIT]\n"
541          "                [--inode-hardlimit INODE_HARDLIMIT] <filesystem>\n"
542          "       setquota [-t] {-h|--help|-u|--user|-g|--group|-p|--projid}\n"
543          "                [--block-grace 'notify'|BLOCK_GRACE]\n"
544          "                [--inode-grace 'notify'|INODE_GRACE] <filesystem>\n"
545          "       setquota {-U|-G|-P}\n"
546          "                -b BLOCK_SOFTLIMIT -B BLOCK_HARDLIMIT\n"
547          "                -i INODE_SOFTLIMIT -I INODE_HARDLIMIT <filesystem>\n"
548          "       setquota {-U|--default-usr|-G|--default-grp|-P|--default-prj}\n"
549          "                [--block-softlimit BLOCK_SOFTLIMIT]\n"
550          "                [--block-hardlimit BLOCK_HARDLIMIT]\n"
551          "                [--inode-softlimit INODE_SOFTLIMIT]\n"
552          "                [--inode-hardlimit INODE_HARDLIMIT] <filesystem>\n"
553          "       setquota {-u|-g|-p} UNAME|UID|GNAME|GID|PROJID\n"
554          "                {-d|--default}\n"
555          "       -b can be used instead of --block-softlimit/--block-grace\n"
556          "       -B can be used instead of --block-hardlimit\n"
557          "       -i can be used instead of --inode-softlimit/--inode-grace\n"
558          "       -I can be used instead of --inode-hardlimit\n"
559          "       -d can be used instead of --default\n\n"
560          "Note: The total quota space will be split into many qunits and\n"
561          "      balanced over all server targets, the minimal qunit size is\n"
562          "      1M bytes for block space and 1K inodes for inode space.\n\n"
563          "      The maximum quota grace time is 2^48 - 1 seconds.\n\n"
564          "      Quota space rebalancing process will stop when this mininum\n"
565          "      value is reached. As a result, quota exceeded can be returned\n"
566          "      while many targets still have 1MB or 1K inodes of spare\n"
567          "      quota space.\n\n"
568          "      When setting the grace time, 'notify' can be used as grace to\n"
569          "      be notified after the quota is over soft limit but prevents\n"
570          "      the soft limit from becoming the hard limit."},
571         {"quota", lfs_quota, 0, "Display disk usage and limits.\n"
572          "usage: quota [-q] [-v] [-h] [-o OBD_UUID|-i MDT_IDX|-I OST_IDX]\n"
573          "             [{-u|-g|-p} UNAME|UID|GNAME|GID|PROJID] <filesystem>\n"
574          "       quota [-o OBD_UUID|-i MDT_IDX|-I OST_IDX] -t {-u|-g|-p} <filesystem>\n"
575         "        quota [-q] [-v] [h] {-U|-G|-P} <filesystem>"},
576         {"project", lfs_project, 0,
577          "Change or list project attribute for specified file or directory.\n"
578          "usage: project [-d|-r] <file|directory...>\n"
579          "         list project ID and flags on file(s) or directories\n"
580          "       project [-p id] [-s] [-r] <file|directory...>\n"
581          "         set project ID and/or inherit flag for specified file(s) or directories\n"
582          "       project -c [-d|-r [-p id] [-0]] <file|directory...>\n"
583          "         check project ID and flags on file(s) or directories, print outliers\n"
584          "       project -C [-r] [-k] <file|directory...>\n"
585          "         clear the project inherit flag and ID on the file or directory\n"
586         },
587 #endif
588         {"flushctx", lfs_flushctx, 0,
589          "Flush security context for current user.\n"
590          "usage: flushctx [-k] [-r] [mountpoint...]"},
591         {"changelog", lfs_changelog, 0,
592          "Show the metadata changes on an MDT."
593          "\nusage: changelog <mdtname> [startrec [endrec]]"},
594         {"changelog_clear", lfs_changelog_clear, 0,
595          "Indicate that old changelog records up to <endrec> are no longer of "
596          "interest to consumer <id>, allowing the system to free up space.\n"
597          "An <endrec> of 0 means all records.\n"
598          "usage: changelog_clear <mdtname> <id> <endrec>"},
599         {"fid2path", lfs_fid2path, 0,
600          "Resolve the full path(s) for given FID(s). For a specific hardlink "
601          "specify link number <linkno>.\n"
602          "usage: fid2path [--print-fid|-f] [--print-link|-c] [--link|-l <linkno>] "
603          "<fsname|root> <fid>..."},
604         {"path2fid", lfs_path2fid, 0, "Display the fid(s) for a given path(s).\n"
605          "usage: path2fid [--parents] <path> ..."},
606         {"rmfid", lfs_rmfid, 0, "Remove file(s) by FID(s)\n"
607          "usage: rmfid <fsname|rootpath> <fid> ..."},
608         {"data_version", lfs_data_version, 0, "Display file data version for "
609          "a given path.\n" "usage: data_version [-n|-r|-w] <path>"},
610         {"hsm_state", lfs_hsm_state, 0, "Display the HSM information (states, "
611          "undergoing actions) for given files.\n usage: hsm_state <file> ..."},
612         {"hsm_set", lfs_hsm_set, 0, "Set HSM user flag on specified files.\n"
613          "usage: hsm_set [--norelease] [--noarchive] [--dirty] [--exists] "
614          "[--archived] [--lost] [--archive-id NUM] <file> ..."},
615         {"hsm_clear", lfs_hsm_clear, 0, "Clear HSM user flag on specified "
616          "files.\n"
617          "usage: hsm_clear [--norelease] [--noarchive] [--dirty] [--exists] "
618          "[--archived] [--lost] <file> ..."},
619         {"hsm_action", lfs_hsm_action, 0, "Display current HSM request for "
620          "given files.\n" "usage: hsm_action <file> ..."},
621         {"hsm_archive", lfs_hsm_archive, 0,
622          "Archive file to external storage.\n"
623          "usage: hsm_archive [--filelist FILELIST] [--data DATA] [--archive NUM] "
624          "<file> ..."},
625         {"hsm_restore", lfs_hsm_restore, 0,
626          "Restore file from external storage.\n"
627          "usage: hsm_restore [--filelist FILELIST] [--data DATA] <file> ..."},
628         {"hsm_release", lfs_hsm_release, 0,
629          "Release files from Lustre.\n"
630          "usage: hsm_release [--filelist FILELIST] [--data DATA] <file> ..."},
631         {"hsm_remove", lfs_hsm_remove, 0,
632          "Remove file copy from external storage.\n"
633          "usage: hsm_remove [--filelist FILELIST] [--data DATA] "
634          "[--archive NUM]\n"
635          "                  (FILE [FILE ...] | "
636          "--mntpath MOUNTPATH FID [FID ...])\n"
637          "\n"
638          "Note: To remove an archived copy of a file already deleted from a "
639          "Lustre FS, the\n"
640          "--mntpath option and a list of FIDs must be specified"
641         },
642         {"hsm_cancel", lfs_hsm_cancel, 0,
643          "Cancel requests related to specified files.\n"
644          "usage: hsm_cancel [--filelist FILELIST] [--data DATA] <file> ..."},
645         {"swap_layouts", lfs_swap_layouts, 0, "Swap layouts between 2 files.\n"
646          "usage: swap_layouts <path1> <path2>"},
647         {"migrate", lfs_setstripe_migrate, 0,
648          "migrate a directory between MDTs.\n"
649          "usage: migrate [--mdt-count|-c STRIPE_COUNT]\n"
650          "               [--mdt-hash|-H HASH_TYPE]\n"
651          "               [--mdt-index|-m START_MDT_INDEX] [--verbose|-v]\n"
652          "               <directory>\n"
653          "\tmdt:        MDTs to stripe over, if only one MDT is specified\n"
654          "                      it's the MDT index of first stripe\n"
655          "\tmdt_count:  number of MDTs to stripe a directory over\n"
656          "\tmdt_hash:   hash type of the striped directory. mdt types:\n"
657          "              all_char  (type 1)sum of characters % MDT_COUNT\n"
658          "              fnv_1a_64 (type 2)FNV-1a hash algorithm (default)\n"
659          "              crush     (type 3)CRUSH hash algorithm\n"
660          "\n"
661          "migrate file objects from one OST "
662          "layout\nto another (may be not safe with concurent writes).\n"
663          "usage: migrate [--stripe-count|-c STRIPE_COUNT]\n"
664          "               [--overstripe-count|-C STRIPE_COUNT]\n"
665          "               [--stripe-index|-i START_OST_INDEX]\n"
666          "               [--stripe-size|-S STRIPE_SIZE]\n"
667          "               [--pool|-p <pool_name>] [--ost|-o OST_INDICES]\n"
668          "               [--block|-b] [--non-block|-n] [--non-direct|-D]\n"
669          "               <file|directory>\n"
670          "\tstripe_count:   number of OSTs to stripe a file over\n"
671          "\t                Using -C instead of -c allows overstriping, which\n"
672          "\t                will place more than one stripe per OST if\n"
673          "\t                stripe_count is greater than the number of OSTs\n"
674          "\tstripe_ost_index: index of the first OST to stripe a file over\n"
675          "\tstripe_size:      number of bytes to store before moving to the next OST\n"
676          "\tpool_name:        name of the predefined pool of OSTs\n"
677          "\tost_indices:      OSTs to stripe over, in order\n"
678          "\tblock:        Block file access during data migration (default)\n"
679          "\tnon-block:    Abort migrations if concurrent access is detected\n"
680          "\tnon-direct:       do not use direct I/O to copy file contents.\n"},
681         {"mv", lfs_mv, 0,
682          "To move directories between MDTs. This command is deprecated, "
683          "use \"migrate\" instead.\n"
684          "usage: mv <directory|filename> [--mdt-index|-m MDT_INDEX] "
685          "[--verbose|-v]\n"},
686         {"ladvise", lfs_ladvise, 0,
687          "Provide servers with advice about access patterns for a file.\n"
688          "usage: ladvise [--advice|-a ADVICE] [--start|-s START[kMGT]]\n"
689          "               [--background|-b] [--unset|-u]\n\n"
690          "               {--end|-e END[kMGT]|--length|-l LENGTH[kMGT]}\n"
691          "               {[--mode|-m [READ,WRITE]}\n"
692          "               <file> ...\n"},
693         {"mirror", lfs_mirror, mirror_cmdlist,
694          "lfs commands used to manage files with mirrored components:\n"
695          "lfs mirror create - create a mirrored file or directory\n"
696          "lfs mirror extend - add mirror(s) to an existing file\n"
697          "lfs mirror split  - split a mirror from an existing mirrored file\n"
698          "lfs mirror resync - resynchronize out-of-sync mirrored file(s)\n"
699          "lfs mirror read   - read a mirror content of a mirrored file\n"
700          "lfs mirror write  - write to a mirror of a mirrored file\n"
701          "lfs mirror copy   - copy a mirror to other mirror(s) of a file\n"
702          "lfs mirror verify - verify mirrored file(s)\n"},
703         {"getsom", lfs_getsom, 0, "To list the SOM info for a given file.\n"
704          "usage: getsom [-s] [-b] [-f] <path>\n"
705          "\t-s: Only show the size value of the SOM data for a given file\n"
706          "\t-b: Only show the blocks value of the SOM data for a given file\n"
707          "\t-f: Only show the flags value of the SOM data for a given file\n"},
708         {"heat_get", lfs_heat_get, 0,
709          "To get heat of files.\n"
710          "usage: heat_get <file> ...\n"},
711         {"heat_set", lfs_heat_set, 0,
712          "To set heat flags of files.\n"
713          "usage: heat_set [--clear|-c] [--off|-o] [--on|-O] <file> ...\n"
714          "\t--clear|-c: Clear file heat for given files\n"
715          "\t--off|-o:   Turn off file heat for given files\n"
716          "\t--on|-O:    Turn on file heat for given files\n"},
717         {"pcc", lfs_pcc, pcc_cmdlist,
718          "lfs commands used to interact with PCC features:\n"
719          "lfs pcc attach - attach given files to Persistent Client Cache\n"
720          "lfs pcc attach_fid - attach given files into PCC by FID(s)\n"
721          "lfs pcc state  - display the PCC state for given files\n"
722          "lfs pcc detach - detach given files from Persistent Client Cache\n"
723          "lfs pcc detach_fid - detach given files from PCC by FID(s)\n"},
724         {"help", Parser_help, 0, "help"},
725         {"exit", Parser_quit, 0, "quit"},
726         {"quit", Parser_quit, 0, "quit"},
727         {"--version", Parser_version, 0,
728          "output build version of the utility and exit"},
729         {"--list-commands", lfs_list_commands, 0,
730          "list commands supported by the utility and exit"},
731         { 0, 0, 0, NULL }
732 };
733
734 static int check_hashtype(const char *hashtype)
735 {
736         int type_num = atoi(hashtype);
737         int i;
738
739         /* numeric hash type */
740         if (hashtype && strlen(hashtype) == 1 &&
741             (type_num > 0 && type_num < LMV_HASH_TYPE_MAX))
742                 return type_num;
743         /* string hash type */
744         for (i = LMV_HASH_TYPE_ALL_CHARS; i < LMV_HASH_TYPE_MAX; i++)
745                 if (strcmp(hashtype, mdt_hash_name[i]) == 0)
746                         return i;
747
748         return 0;
749 }
750
751 static uint32_t check_foreign_type_name(const char *foreign_type_name)
752 {
753         uint32_t i;
754
755         for (i = 0; i < LU_FOREIGN_TYPE_UNKNOWN; i++) {
756                 if (!lu_foreign_types[i].lft_name)
757                         break;
758                 if (strcmp(foreign_type_name,
759                            lu_foreign_types[i].lft_name) == 0)
760                         return lu_foreign_types[i].lft_type;
761         }
762
763         return LU_FOREIGN_TYPE_UNKNOWN;
764 }
765
766 static const char *error_loc = "syserror";
767
768 enum {
769         MIGRATION_NONBLOCK      = 0x0001,
770         MIGRATION_MIRROR        = 0x0002,
771         MIGRATION_NONDIRECT     = 0x0004,
772         MIGRATION_VERBOSE       = 0x0008,
773 };
774
775 static int
776 migrate_open_files(const char *name, __u64 migration_flags,
777                    const struct llapi_stripe_param *param,
778                    struct llapi_layout *layout, int *fd_src, int *fd_tgt)
779 {
780         int                      fd = -1;
781         int                      fdv = -1;
782         int                      rflags;
783         int                      mdt_index;
784         int                      random_value;
785         char                     parent[PATH_MAX];
786         char                     volatile_file[PATH_MAX];
787         char                    *ptr;
788         int                      rc;
789         struct stat              st;
790         struct stat              stv;
791
792         if (!param && !layout) {
793                 error_loc = "layout information";
794                 return -EINVAL;
795         }
796
797         /* search for file directory pathname */
798         if (strlen(name) > sizeof(parent) - 1) {
799                 error_loc = "source file name";
800                 return -ERANGE;
801         }
802
803         strncpy(parent, name, sizeof(parent));
804         ptr = strrchr(parent, '/');
805         if (!ptr) {
806                 if (!getcwd(parent, sizeof(parent))) {
807                         error_loc = "getcwd";
808                         return -errno;
809                 }
810         } else {
811                 if (ptr == parent) /* leading '/' */
812                         ptr = parent + 1;
813                 *ptr = '\0';
814         }
815
816         /* open file, direct io */
817         /* even if the file is only read, WR mode is nedeed to allow
818          * layout swap on fd
819          */
820         rflags = O_RDWR;
821         if (!(migration_flags & MIGRATION_NONDIRECT))
822                 rflags |= O_DIRECT;
823         fd = open(name, rflags);
824         if (fd < 0) {
825                 rc = -errno;
826                 error_loc = "cannot open source file";
827                 return rc;
828         }
829
830         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
831         if (rc < 0) {
832                 error_loc = "cannot get MDT index";
833                 goto out;
834         }
835
836         do {
837                 int open_flags = O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW;
838                 mode_t open_mode = S_IRUSR | S_IWUSR;
839
840                 random_value = random();
841                 rc = snprintf(volatile_file, sizeof(volatile_file),
842                               "%s/%s:%.4X:%.4X:fd=%.2d", parent,
843                               LUSTRE_VOLATILE_HDR, mdt_index,
844                               random_value, fd);
845                 if (rc >= sizeof(volatile_file)) {
846                         rc = -ENAMETOOLONG;
847                         break;
848                 }
849
850                 /* create, open a volatile file, use caching (ie no directio) */
851                 if (layout) {
852                         /* Returns -1 and sets errno on error: */
853                         fdv = llapi_layout_file_open(volatile_file, open_flags,
854                                                      open_mode, layout);
855                         if (fdv < 0)
856                                 fdv = -errno;
857                 } else {
858                         /* Does the right thing on error: */
859                         fdv = llapi_file_open_param(volatile_file, open_flags,
860                                                     open_mode, param);
861                 }
862         } while (fdv < 0 && (rc = fdv) == -EEXIST);
863
864         if (rc < 0) {
865                 error_loc = "cannot create volatile file";
866                 goto out;
867         }
868
869         /*
870          * In case the MDT does not support creation of volatile files
871          * we should try to unlink it.
872          */
873         (void)unlink(volatile_file);
874
875         /*
876          * Not-owner (root?) special case.
877          * Need to set owner/group of volatile file like original.
878          * This will allow to pass related check during layout_swap.
879          */
880         rc = fstat(fd, &st);
881         if (rc != 0) {
882                 rc = -errno;
883                 error_loc = "cannot stat source file";
884                 goto out;
885         }
886
887         rc = fstat(fdv, &stv);
888         if (rc != 0) {
889                 rc = -errno;
890                 error_loc = "cannot stat volatile";
891                 goto out;
892         }
893
894         if (st.st_uid != stv.st_uid || st.st_gid != stv.st_gid) {
895                 rc = fchown(fdv, st.st_uid, st.st_gid);
896                 if (rc != 0) {
897                         rc = -errno;
898                         error_loc = "cannot change ownwership of volatile";
899                         goto out;
900                 }
901         }
902
903 out:
904         if (rc < 0) {
905                 if (fd > 0)
906                         close(fd);
907                 if (fdv > 0)
908                         close(fdv);
909         } else {
910                 *fd_src = fd;
911                 *fd_tgt = fdv;
912                 error_loc = NULL;
913         }
914         return rc;
915 }
916
917 static int migrate_copy_data(int fd_src, int fd_dst, int (*check_file)(int))
918 {
919         struct llapi_layout *layout;
920         size_t buf_size = 4 * 1024 * 1024;
921         void *buf = NULL;
922         off_t pos = 0;
923         off_t data_end = 0;
924         size_t page_size = sysconf(_SC_PAGESIZE);
925         bool sparse;
926         int rc;
927
928         layout = llapi_layout_get_by_fd(fd_src, 0);
929         if (layout) {
930                 uint64_t stripe_size;
931
932                 rc = llapi_layout_stripe_size_get(layout, &stripe_size);
933                 if (rc == 0)
934                         buf_size = stripe_size;
935
936                 llapi_layout_free(layout);
937         }
938
939         /* Use a page-aligned buffer for direct I/O */
940         rc = posix_memalign(&buf, page_size, buf_size);
941         if (rc != 0)
942                 return -rc;
943
944         sparse = llapi_file_is_sparse(fd_src);
945         if (sparse) {
946                 rc = ftruncate(fd_dst, pos);
947                 if (rc < 0) {
948                         rc = -errno;
949                         return rc;
950                 }
951         }
952
953         while (1) {
954                 off_t data_off;
955                 size_t to_read, to_write;
956                 ssize_t rsize;
957
958                 if (sparse && pos >= data_end) {
959                         size_t data_size;
960
961                         data_off = llapi_data_seek(fd_src, pos, &data_size);
962                         if (data_off < 0) {
963                                 /* Non-fatal, switch to full copy */
964                                 sparse = false;
965                                 continue;
966                         }
967                         /* hole at the end of file, truncate up to it */
968                         if (!data_size) {
969                                 rc = ftruncate(fd_dst, data_off);
970                                 if (rc < 0)
971                                         goto out;
972                         }
973                         pos = data_off & ~(page_size - 1);
974                         data_end = data_off + data_size;
975                         to_read = ((data_end - pos - 1) | (page_size - 1)) + 1;
976                         to_read = MIN(to_read, buf_size);
977                 } else {
978                         to_read = buf_size;
979                 }
980
981                 if (check_file) {
982                         rc = check_file(fd_src);
983                         if (rc < 0)
984                                 goto out;
985                 }
986
987                 rsize = pread(fd_src, buf, to_read, pos);
988                 if (rsize < 0) {
989                         rc = -errno;
990                         goto out;
991                 }
992                 /* EOF */
993                 if (rsize == 0)
994                         break;
995
996                 to_write = rsize;
997                 while (to_write > 0) {
998                         ssize_t written;
999
1000                         written = pwrite(fd_dst, buf, to_write, pos);
1001                         if (written < 0) {
1002                                 rc = -errno;
1003                                 goto out;
1004                         }
1005                         pos += written;
1006                         to_write -= written;
1007                 }
1008                 if (rc || rsize < to_read)
1009                         break;
1010         }
1011
1012         rc = fsync(fd_dst);
1013         if (rc < 0)
1014                 rc = -errno;
1015 out:
1016         /* Try to avoid page cache pollution after migration. */
1017         (void)posix_fadvise(fd_src, 0, 0, POSIX_FADV_DONTNEED);
1018         (void)posix_fadvise(fd_dst, 0, 0, POSIX_FADV_DONTNEED);
1019
1020         free(buf);
1021         return rc;
1022 }
1023
1024 static int migrate_copy_timestamps(int fd, int fdv)
1025 {
1026         struct stat st;
1027
1028         if (fstat(fd, &st) == 0) {
1029                 struct timeval tv[2] = {
1030                         {.tv_sec = st.st_atime},
1031                         {.tv_sec = st.st_mtime}
1032                 };
1033
1034                 return futimes(fdv, tv);
1035         }
1036
1037         return -errno;
1038 }
1039
1040 static int migrate_block(int fd, int fdv)
1041 {
1042         __u64   dv1;
1043         int     gid;
1044         int     rc;
1045         int     rc2;
1046
1047         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
1048         if (rc < 0) {
1049                 error_loc = "cannot get dataversion";
1050                 return rc;
1051         }
1052
1053         do
1054                 gid = random();
1055         while (gid == 0);
1056
1057         /*
1058          * The grouplock blocks all concurrent accesses to the file.
1059          * It has to be taken after llapi_get_data_version as it would
1060          * block it too.
1061          */
1062         rc = llapi_group_lock(fd, gid);
1063         if (rc < 0) {
1064                 error_loc = "cannot get group lock";
1065                 return rc;
1066         }
1067
1068         rc = migrate_copy_data(fd, fdv, NULL);
1069         if (rc < 0) {
1070                 error_loc = "data copy failed";
1071                 goto out_unlock;
1072         }
1073
1074         /* Make sure we keep original atime/mtime values */
1075         rc = migrate_copy_timestamps(fd, fdv);
1076         if (rc < 0) {
1077                 error_loc = "timestamp copy failed";
1078                 goto out_unlock;
1079         }
1080
1081         /*
1082          * swap layouts
1083          * for a migration we need to check data version on file did
1084          * not change.
1085          *
1086          * Pass in gid=0 since we already own grouplock.
1087          */
1088         rc = llapi_fswap_layouts_grouplock(fd, fdv, dv1, 0, 0,
1089                                            SWAP_LAYOUTS_CHECK_DV1);
1090         if (rc == -EAGAIN) {
1091                 error_loc = "file changed";
1092                 goto out_unlock;
1093         } else if (rc < 0) {
1094                 error_loc = "cannot swap layout";
1095                 goto out_unlock;
1096         }
1097
1098 out_unlock:
1099         rc2 = llapi_group_unlock(fd, gid);
1100         if (rc2 < 0 && rc == 0) {
1101                 error_loc = "unlock group lock";
1102                 rc = rc2;
1103         }
1104
1105         return rc;
1106 }
1107
1108 /**
1109  * Internal helper for migrate_copy_data(). Check lease and report error if
1110  * need be.
1111  *
1112  * \param[in]  fd           File descriptor on which to check the lease.
1113  *
1114  * \retval 0       Migration can keep on going.
1115  * \retval -errno  Error occurred, abort migration.
1116  */
1117 static int check_lease(int fd)
1118 {
1119         int rc;
1120
1121         rc = llapi_lease_check(fd);
1122         if (rc > 0)
1123                 return 0; /* llapi_check_lease returns > 0 on success. */
1124
1125         return -EBUSY;
1126 }
1127
1128 static int migrate_nonblock(int fd, int fdv)
1129 {
1130         __u64   dv1;
1131         __u64   dv2;
1132         int     rc;
1133
1134         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
1135         if (rc < 0) {
1136                 error_loc = "cannot get data version";
1137                 return rc;
1138         }
1139
1140         rc = migrate_copy_data(fd, fdv, check_lease);
1141         if (rc < 0) {
1142                 error_loc = "data copy failed";
1143                 return rc;
1144         }
1145
1146         rc = llapi_get_data_version(fd, &dv2, LL_DV_RD_FLUSH);
1147         if (rc != 0) {
1148                 error_loc = "cannot get data version";
1149                 return rc;
1150         }
1151
1152         if (dv1 != dv2) {
1153                 rc = -EAGAIN;
1154                 error_loc = "source file changed";
1155                 return rc;
1156         }
1157
1158         /* Make sure we keep original atime/mtime values */
1159         rc = migrate_copy_timestamps(fd, fdv);
1160         if (rc < 0) {
1161                 error_loc = "timestamp copy failed";
1162                 return rc;
1163         }
1164
1165         return 0;
1166 }
1167
1168 static
1169 int lfs_layout_compid_by_pool(char *fname, const char *pool, int *comp_id)
1170 {
1171         struct pool_to_id_cbdata data = { .pool = pool };
1172         struct llapi_layout *layout = NULL;
1173         int rc;
1174
1175         layout = llapi_layout_get_by_path(fname, 0);
1176         if (!layout) {
1177                 fprintf(stderr,
1178                         "error %s: file '%s' couldn't get layout: rc=%d\n",
1179                         progname, fname, errno);
1180                 rc = -errno;
1181                 goto free_layout;
1182         }
1183         rc = llapi_layout_sanity(layout, fname, false, true);
1184         if (rc < 0) {
1185                 llapi_layout_sanity_perror(errno);
1186                 goto free_layout;
1187         }
1188         rc = llapi_layout_comp_iterate(layout, find_comp_id_by_pool, &data);
1189         if (rc < 0)
1190                 goto free_layout;
1191
1192         *comp_id = data.id;
1193         rc = 0;
1194
1195 free_layout:
1196         if (layout)
1197                 llapi_layout_free(layout);
1198         return rc;
1199 }
1200
1201 static int lfs_component_set(char *fname, int comp_id, const char *pool,
1202                              __u32 flags, __u32 neg_flags)
1203 {
1204         __u32 ids[2];
1205         __u32 flags_array[2];
1206         size_t count = 0;
1207         int rc;
1208
1209         if (!comp_id) {
1210                 if (pool == NULL) {
1211                         fprintf(stderr,
1212                                 "error %s: neither component id nor pool is specified\n",
1213                                 progname);
1214                         return -EINVAL;
1215                 }
1216                 rc = lfs_layout_compid_by_pool(fname, pool, &comp_id);
1217                 if (rc)
1218                         return rc;
1219         }
1220
1221         if (flags) {
1222                 ids[count] = comp_id;
1223                 flags_array[count] = flags;
1224                 ++count;
1225         }
1226
1227         if (neg_flags) {
1228                 if (neg_flags & LCME_FL_STALE) {
1229                         fprintf(stderr,
1230                                 "%s: cannot clear 'stale' flags from component. Please use lfs-mirror-resync(1) instead\n",
1231                                 progname);
1232                         return -EINVAL;
1233                 }
1234
1235                 ids[count] = comp_id;
1236                 flags_array[count] = neg_flags | LCME_FL_NEG;
1237                 ++count;
1238         }
1239
1240         rc = llapi_layout_file_comp_set(fname, ids, flags_array, count);
1241         if (rc) {
1242                 if (errno == EUCLEAN) {
1243                         rc = -errno;
1244                         fprintf(stderr,
1245                                 "%s: cannot set 'stale' flag on component '%#x' of the last non-stale mirror of '%s'\n",
1246                                 progname, comp_id, fname);
1247                 } else {
1248                         fprintf(stderr,
1249                                 "%s: cannot change the flags of component '%#x' of file '%s': %x / ^(%x)\n",
1250                                 progname, comp_id, fname, flags, neg_flags);
1251                 }
1252         }
1253
1254         return rc;
1255 }
1256
1257 static int lfs_component_del(char *fname, __u32 comp_id,
1258                              __u32 flags, __u32 neg_flags)
1259 {
1260         int     rc = 0;
1261
1262         if (flags && neg_flags)
1263                 return -EINVAL;
1264
1265         if (!flags && neg_flags)
1266                 flags = neg_flags | LCME_FL_NEG;
1267
1268         if ((flags && comp_id) || (!flags && !comp_id))
1269                 return -EINVAL;
1270
1271         if (flags) {
1272                 if (flags & ~LCME_KNOWN_FLAGS) {
1273                         fprintf(stderr,
1274                                 "%s setstripe: unknown flags %#x\n",
1275                                 progname, flags);
1276                         return -EINVAL;
1277                 }
1278         } else if (comp_id > LCME_ID_MAX) {
1279                 fprintf(stderr, "%s setstripe: invalid component id %u\n",
1280                         progname, comp_id);
1281                 return -EINVAL;
1282         }
1283
1284         rc = llapi_layout_file_comp_del(fname, comp_id, flags);
1285         if (rc)
1286                 fprintf(stderr,
1287                         "%s setstripe: cannot delete component %#x from '%s': %s\n",
1288                         progname, comp_id, fname, strerror(errno));
1289         return rc;
1290 }
1291
1292 static int lfs_component_add(char *fname, struct llapi_layout *layout)
1293 {
1294         int     rc;
1295
1296         if (!layout)
1297                 return -EINVAL;
1298
1299         rc = llapi_layout_file_comp_add(fname, layout);
1300         if (rc)
1301                 fprintf(stderr, "Add layout component(s) to %s failed. %s\n",
1302                         fname, strerror(errno));
1303         return rc;
1304 }
1305
1306 static int lfs_component_create(char *fname, int open_flags, mode_t open_mode,
1307                                 struct llapi_layout *layout)
1308 {
1309         struct stat     st;
1310         int     fd;
1311
1312         if (!layout)
1313                 return -EINVAL;
1314
1315         fd = lstat(fname, &st);
1316         if (fd == 0 && S_ISDIR(st.st_mode))
1317                 open_flags = O_DIRECTORY | O_RDONLY;
1318
1319         fd = llapi_layout_file_open(fname, open_flags, open_mode, layout);
1320         if (fd < 0)
1321                 fprintf(stderr, "%s: cannot %s '%s': %s\n", progname,
1322                         S_ISDIR(st.st_mode) ?
1323                                 "set default composite layout for" :
1324                                 "create composite file",
1325                         fname, strerror(errno));
1326         return fd;
1327 }
1328
1329 static int lfs_migrate(char *name, __u64 migration_flags,
1330                        struct llapi_stripe_param *param,
1331                        struct llapi_layout *layout)
1332 {
1333         struct llapi_layout *existing;
1334         uint64_t dom_new, dom_cur;
1335         int fd = -1;
1336         int fdv = -1;
1337         int rc;
1338
1339         rc = migrate_open_files(name, migration_flags, param, layout,
1340                                 &fd, &fdv);
1341         if (rc < 0)
1342                 goto out;
1343
1344         rc = llapi_layout_dom_size(layout, &dom_new);
1345         if (rc) {
1346                 error_loc = "cannot get new layout DoM size";
1347                 goto out;
1348         }
1349         /* special case for migration to DOM layout*/
1350         existing = llapi_layout_get_by_fd(fd, 0);
1351         if (!existing) {
1352                 error_loc = "cannot get existing layout";
1353                 goto out;
1354         }
1355
1356         rc = llapi_layout_dom_size(existing, &dom_cur);
1357         if (rc) {
1358                 error_loc = "cannot get current layout DoM size";
1359                 goto out;
1360         }
1361
1362         /*
1363          * if file has DoM layout already then migration is possible to
1364          * the new layout with the same DoM component via swap layout,
1365          * if new layout used bigger DOM size, then mirroring is used
1366          */
1367         if (dom_new > dom_cur) {
1368                 rc = lfs_migrate_to_dom(fd, fdv, name, migration_flags, param,
1369                                         layout);
1370                 if (rc)
1371                         error_loc = "cannot migrate to DOM layout";
1372                 goto out_closed;
1373         }
1374
1375         if (!(migration_flags & MIGRATION_NONBLOCK)) {
1376                 /*
1377                  * Blocking mode (forced if servers do not support file lease).
1378                  * It is also the default mode, since we cannot distinguish
1379                  * between a broken lease and a server that does not support
1380                  * atomic swap/close (LU-6785)
1381                  */
1382                 rc = migrate_block(fd, fdv);
1383                 goto out;
1384         }
1385
1386         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1387         if (rc < 0) {
1388                 error_loc = "cannot get lease";
1389                 goto out;
1390         }
1391
1392         rc = migrate_nonblock(fd, fdv);
1393         if (rc < 0) {
1394                 llapi_lease_release(fd);
1395                 goto out;
1396         }
1397
1398         /*
1399          * Atomically put lease, swap layouts and close.
1400          * for a migration we need to check data version on file did
1401          * not change.
1402          */
1403         rc = llapi_fswap_layouts(fd, fdv, 0, 0, SWAP_LAYOUTS_CLOSE);
1404         if (rc < 0) {
1405                 error_loc = "cannot swap layout";
1406                 goto out;
1407         }
1408
1409 out:
1410         if (fd >= 0)
1411                 close(fd);
1412
1413         if (fdv >= 0)
1414                 close(fdv);
1415 out_closed:
1416         if (rc < 0)
1417                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1418                         progname, name, error_loc, strerror(-rc));
1419         else if (migration_flags & MIGRATION_VERBOSE)
1420                 printf("%s\n", name);
1421
1422         return rc;
1423 }
1424
1425 static int comp_str2flags(char *string, __u32 *flags, __u32 *neg_flags)
1426 {
1427         char *name;
1428         char *dup_string = NULL;
1429         int rc = 0;
1430
1431         *flags = 0;
1432         *neg_flags = 0;
1433
1434         if (!string || !string[0])
1435                 return -EINVAL;
1436
1437         dup_string = strdup(string);
1438         if (!dup_string) {
1439                 llapi_printf(LLAPI_MSG_ERROR,
1440                              "%s: insufficient memory\n",
1441                              progname);
1442                 return -ENOMEM;
1443         }
1444
1445         for (name = strtok(dup_string, ","); name; name = strtok(NULL, ",")) {
1446                 bool found = false;
1447                 int i;
1448
1449                 for (i = 0; i < ARRAY_SIZE(comp_flags_table); i++) {
1450                         __u32 comp_flag = comp_flags_table[i].cfn_flag;
1451                         const char *comp_name = comp_flags_table[i].cfn_name;
1452
1453                         if (strcmp(name, comp_name) == 0) {
1454                                 *flags |= comp_flag;
1455                                 found = true;
1456                         } else if (strncmp(name, "^", 1) == 0 &&
1457                                    strcmp(name + 1, comp_name) == 0) {
1458                                 *neg_flags |= comp_flag;
1459                                 found = true;
1460                         }
1461                 }
1462                 if (!found) {
1463                         llapi_printf(LLAPI_MSG_ERROR,
1464                                      "%s: component flag '%s' not supported\n",
1465                                      progname, name);
1466                         rc = -EINVAL;
1467                         goto out_free;
1468                 }
1469         }
1470
1471         if (!*flags && !*neg_flags)
1472                 rc = -EINVAL;
1473
1474         /* don't allow to set and exclude the same flag */
1475         if (*flags & *neg_flags)
1476                 rc = -EINVAL;
1477
1478 out_free:
1479         free(dup_string);
1480         return rc;
1481 }
1482
1483 static int mdthash_input(char *string, __u32 *inflags,
1484                          __u32 *exflags, __u32 *type)
1485 {
1486         char *name;
1487         struct mhf_list {
1488                 char *name;
1489                 __u32 flag;
1490         } mhflist[] = {
1491                 {"migrating", LMV_HASH_FLAG_MIGRATION},
1492                 {"badtype", LMV_HASH_FLAG_BAD_TYPE},
1493                 {"lostlmv", LMV_HASH_FLAG_LOST_LMV},
1494         };
1495
1496         if (string == NULL)
1497                 return -EINVAL;
1498
1499         *inflags = 0;
1500         *exflags = 0;
1501         *type = 0;
1502         for (name = strtok(string, ","); name; name = strtok(NULL, ",")) {
1503                 bool found = false;
1504                 int i;
1505
1506                 for (i = 0; i < ARRAY_SIZE(mhflist); i++) {
1507                         if (strcmp(name, mhflist[i].name) == 0 ||
1508                             name[0] == mhflist[i].name[0]) {
1509                                 *inflags |= mhflist[i].flag;
1510                                 found = true;
1511                         } else if (name[0] == '^' &&
1512                                    (strcmp(name + 1, mhflist[i].name) == 0 ||
1513                                     name[1] == mhflist[i].name[0])) {
1514                                 *exflags |= mhflist[i].flag;
1515                                 found = true;
1516                         }
1517                 }
1518                 if (!found) {
1519                         i = check_hashtype(name);
1520                         if (i > 0) {
1521                                 *type |= 1 << i;
1522                                 continue;
1523                         }
1524                         llapi_printf(LLAPI_MSG_ERROR,
1525                                      "%s: invalid mdt_hash value '%s'\n",
1526                                      progname, name);
1527                         return -EINVAL;
1528                 }
1529         }
1530
1531         /* don't allow to include and exclude the same flag */
1532         if (*inflags & *exflags) {
1533                 llapi_printf(LLAPI_MSG_ERROR,
1534                              "%s: include and exclude same flag '%s'\n",
1535                              progname, string);
1536                 return -EINVAL;
1537         }
1538
1539         return 0;
1540 }
1541
1542 static int mirror_str2state(char *string, __u16 *state, __u16 *neg_state)
1543 {
1544         if (!string)
1545                 return -EINVAL;
1546
1547         *state = 0;
1548         *neg_state = 0;
1549
1550         if (strncmp(string, "^", 1) == 0) {
1551                 *neg_state = llapi_layout_string_flags(string + 1);
1552                 if (*neg_state != 0)
1553                         return 0;
1554         } else {
1555                 *state = llapi_layout_string_flags(string);
1556                 if (*state != 0)
1557                         return 0;
1558         }
1559
1560         llapi_printf(LLAPI_MSG_ERROR,
1561                      "%s: mirrored file state '%s' not supported\n",
1562                      progname, string);
1563         return -EINVAL;
1564 }
1565
1566 /**
1567  * struct mirror_args - Command-line arguments for mirror(s).
1568  * @m_count:  Number of mirrors to be created with this layout.
1569  * @m_flags:  Mirror level flags, only 'prefer' is supported.
1570  * @m_layout: Mirror layout.
1571  * @m_file:   A victim file. Its layout will be split and used as a mirror.
1572  * @m_next:   Point to the next node of the list.
1573  *
1574  * Command-line arguments for mirror(s) will be parsed and stored in
1575  * a linked list that consists of this structure.
1576  */
1577 struct mirror_args {
1578         __u32                   m_count;
1579         __u32                   m_flags;
1580         struct llapi_layout     *m_layout;
1581         const char              *m_file;
1582         struct mirror_args      *m_next;
1583         bool                    m_inherit;
1584 };
1585
1586 /**
1587  * enum mirror_flags - Flags for extending a mirrored file.
1588  * @MF_NO_VERIFY: Indicates not to verify the mirror(s) from victim file(s)
1589  *             in case the victim file(s) contains the same data as the
1590  *             original mirrored file.
1591  * @MF_DESTROY: Indicates to delete the mirror from the mirrored file.
1592  * @MF_COMP_ID: specified component id instead of mirror id
1593  *
1594  * Flags for extending a mirrored file.
1595  */
1596 enum mirror_flags {
1597         MF_NO_VERIFY    = 0x1,
1598         MF_DESTROY      = 0x2,
1599         MF_COMP_ID      = 0x4,
1600         MF_COMP_POOL    = 0x8,
1601 };
1602
1603 /**
1604  * mirror_create_sanity_check() - Check mirror list.
1605  * @list:  A linked list that stores the mirror arguments.
1606  *
1607  * This function does a sanity check on @list for creating
1608  * a mirrored file.
1609  *
1610  * Return: 0 on success or a negative error code on failure.
1611  */
1612 static int mirror_create_sanity_check(const char *fname,
1613                                       struct mirror_args *list,
1614                                       bool check_fname)
1615 {
1616         int rc = 0;
1617         bool has_m_file = false;
1618         bool has_m_layout = false;
1619
1620         if (!list)
1621                 return -EINVAL;
1622
1623         if (fname && check_fname) {
1624                 struct llapi_layout *layout;
1625
1626                 layout = llapi_layout_get_by_path(fname, 0);
1627                 if (!layout) {
1628                         fprintf(stderr,
1629                                 "error: %s: file '%s' couldn't get layout\n",
1630                                 progname, fname);
1631                         return -ENODATA;
1632                 }
1633
1634                 rc = llapi_layout_sanity(layout, fname, false, true);
1635
1636                 llapi_layout_free(layout);
1637
1638                 if (rc) {
1639                         llapi_layout_sanity_perror(rc);
1640                         return rc;
1641                 }
1642         }
1643
1644         while (list) {
1645                 if (list->m_file) {
1646                         has_m_file = true;
1647                         llapi_layout_free(list->m_layout);
1648
1649                         list->m_layout =
1650                                 llapi_layout_get_by_path(list->m_file, 0);
1651                         if (!list->m_layout) {
1652                                 fprintf(stderr,
1653                                         "error: %s: file '%s' has no layout\n",
1654                                         progname, list->m_file);
1655                                 return -ENODATA;
1656                         }
1657                 } else {
1658                         has_m_layout = true;
1659                         if (!list->m_layout) {
1660                                 fprintf(stderr, "error: %s: no mirror layout\n",
1661                                         progname);
1662                                 return -EINVAL;
1663                         }
1664                 }
1665
1666                 rc = llapi_layout_sanity(list->m_layout, fname, false, true);
1667                 if (rc) {
1668                         llapi_layout_sanity_perror(rc);
1669                         return rc;
1670                 }
1671
1672                 list = list->m_next;
1673         }
1674
1675         if (has_m_file && has_m_layout) {
1676                 fprintf(stderr,
1677                         "error: %s: -f <victim_file> option should not be specified with setstripe options\n",
1678                         progname);
1679                 return -EINVAL;
1680         }
1681
1682         return 0;
1683 }
1684
1685 static int mirror_set_flags(struct llapi_layout *layout, void *cbdata)
1686 {
1687         __u32 mirror_flags = *(__u32 *)cbdata;
1688         uint32_t flags;
1689         int rc;
1690
1691         rc = llapi_layout_comp_flags_get(layout, &flags);
1692         if (rc < 0)
1693                 return rc;
1694
1695         if (!flags) {
1696                 rc = llapi_layout_comp_flags_set(layout, mirror_flags);
1697                 if (rc)
1698                         return rc;
1699         }
1700
1701         return LLAPI_LAYOUT_ITER_CONT;
1702 }
1703
1704 /**
1705  * mirror_create() - Create a mirrored file.
1706  * @fname:        The file to be created.
1707  * @mirror_list:  A linked list that stores the mirror arguments.
1708  *
1709  * This function creates a mirrored file @fname with the mirror(s)
1710  * from @mirror_list.
1711  *
1712  * Return: 0 on success or a negative error code on failure.
1713  */
1714 static int mirror_create(char *fname, struct mirror_args *mirror_list)
1715 {
1716         struct llapi_layout *layout = NULL;
1717         struct mirror_args *cur_mirror = NULL;
1718         uint16_t mirror_count = 0;
1719         int i = 0;
1720         int rc = 0;
1721
1722         rc = mirror_create_sanity_check(fname, mirror_list, false);
1723         if (rc)
1724                 return rc;
1725
1726         cur_mirror = mirror_list;
1727         while (cur_mirror) {
1728                 rc = llapi_layout_comp_iterate(cur_mirror->m_layout,
1729                                                mirror_set_flags,
1730                                                &cur_mirror->m_flags);
1731                 if (rc) {
1732                         rc = -errno;
1733                         fprintf(stderr, "%s: failed to set mirror flags\n",
1734                                 progname);
1735                         goto error;
1736                 }
1737
1738                 for (i = 0; i < cur_mirror->m_count; i++) {
1739                         rc = llapi_layout_merge(&layout, cur_mirror->m_layout);
1740                         if (rc) {
1741                                 rc = -errno;
1742                                 fprintf(stderr,
1743                                         "error: %s: merge layout failed: %s\n",
1744                                         progname, strerror(errno));
1745                                 goto error;
1746                         }
1747                 }
1748                 mirror_count += cur_mirror->m_count;
1749                 cur_mirror = cur_mirror->m_next;
1750         }
1751
1752         if (!layout) {
1753                 fprintf(stderr, "error: %s: layout is NULL\n", progname);
1754                 return -EINVAL;
1755         }
1756
1757         rc = llapi_layout_mirror_count_set(layout, mirror_count);
1758         if (rc) {
1759                 rc = -errno;
1760                 fprintf(stderr, "error: %s: set mirror count failed: %s\n",
1761                         progname, strerror(errno));
1762                 goto error;
1763         }
1764
1765         rc = lfs_component_create(fname, O_CREAT | O_WRONLY, 0666,
1766                                   layout);
1767         if (rc >= 0) {
1768                 close(rc);
1769                 rc = 0;
1770         }
1771
1772 error:
1773         llapi_layout_free(layout);
1774         return rc;
1775 }
1776
1777 /**
1778  * Compare files and check lease on @fd.
1779  *
1780  * \retval bytes number of bytes are the same
1781  */
1782 static ssize_t mirror_file_compare(int fd, int fdv)
1783 {
1784         const size_t buflen = 4 * 1024 * 1024; /* 4M */
1785         void *buf;
1786         ssize_t bytes_done = 0;
1787         ssize_t bytes_read = 0;
1788
1789         buf = malloc(buflen * 2);
1790         if (!buf)
1791                 return -ENOMEM;
1792
1793         while (1) {
1794                 if (!llapi_lease_check(fd)) {
1795                         bytes_done = -EBUSY;
1796                         break;
1797                 }
1798
1799                 bytes_read = read(fd, buf, buflen);
1800                 if (bytes_read <= 0)
1801                         break;
1802
1803                 if (bytes_read != read(fdv, buf + buflen, buflen))
1804                         break;
1805
1806                 /*
1807                  * XXX: should compute the checksum on each buffer and then
1808                  * compare checksum to avoid cache collision
1809                  */
1810                 if (memcmp(buf, buf + buflen, bytes_read))
1811                         break;
1812
1813                 bytes_done += bytes_read;
1814         }
1815
1816         free(buf);
1817
1818         return bytes_done;
1819 }
1820
1821 static int mirror_extend_file(const char *fname, const char *victim_file,
1822                               enum mirror_flags mirror_flags)
1823 {
1824         int fd = -1;
1825         int fdv = -1;
1826         struct stat stbuf;
1827         struct stat stbuf_v;
1828         struct ll_ioc_lease *data = NULL;
1829         int rc;
1830
1831         fd = open(fname, O_RDWR);
1832         if (fd < 0) {
1833                 error_loc = "open source file";
1834                 rc = -errno;
1835                 goto out;
1836         }
1837
1838         fdv = open(victim_file, O_RDWR);
1839         if (fdv < 0) {
1840                 error_loc = "open target file";
1841                 rc = -errno;
1842                 goto out;
1843         }
1844
1845         if (fstat(fd, &stbuf) || fstat(fdv, &stbuf_v)) {
1846                 error_loc = "stat source or target file";
1847                 rc = -errno;
1848                 goto out;
1849         }
1850
1851         if (stbuf.st_dev != stbuf_v.st_dev) {
1852                 error_loc = "stat source and target file";
1853                 rc = -EXDEV;
1854                 goto out;
1855         }
1856
1857         /* mirrors should be of the same size */
1858         if (stbuf.st_size != stbuf_v.st_size) {
1859                 error_loc = "file sizes don't match";
1860                 rc = -EINVAL;
1861                 goto out;
1862         }
1863
1864         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1865         if (rc < 0) {
1866                 error_loc = "cannot get lease";
1867                 goto out;
1868         }
1869
1870         if (!(mirror_flags & MF_NO_VERIFY)) {
1871                 ssize_t ret;
1872                 /* mirrors should have the same contents */
1873                 ret = mirror_file_compare(fd, fdv);
1874                 if (ret != stbuf.st_size) {
1875                         error_loc = "file busy or contents don't match";
1876                         rc = ret < 0 ? ret : -EINVAL;
1877                         goto out;
1878                 }
1879         }
1880
1881         /* Get rid of caching pages from clients */
1882         rc = llapi_file_flush(fd);
1883         if (rc < 0) {
1884                 error_loc = "cannot get data version";
1885                 goto out;
1886         }
1887
1888         rc = llapi_file_flush(fdv);
1889         if (rc < 0) {
1890                 error_loc = "cannot get data version";
1891                 goto out;
1892         }
1893
1894         /* Make sure we keep original atime/mtime values */
1895         rc = migrate_copy_timestamps(fd, fdv);
1896         if (rc < 0) {
1897                 error_loc = "cannot copy timestamp";
1898                 goto out;
1899         }
1900
1901         /* Atomically put lease, merge layouts and close. */
1902         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1903         if (!data) {
1904                 error_loc = "memory allocation";
1905                 goto out;
1906         }
1907         data->lil_mode = LL_LEASE_UNLCK;
1908         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1909         data->lil_count = 1;
1910         data->lil_ids[0] = fdv;
1911         rc = llapi_lease_set(fd, data);
1912         if (rc < 0) {
1913                 error_loc = "cannot merge layout";
1914                 goto out;
1915         } else if (rc == 0) {
1916                 rc = -EBUSY;
1917                 error_loc = "lost lease lock";
1918                 goto out;
1919         }
1920         rc = 0;
1921
1922 out:
1923         if (data)
1924                 free(data);
1925         if (fd >= 0)
1926                 close(fd);
1927         if (fdv >= 0)
1928                 close(fdv);
1929         if (!rc)
1930                 (void) unlink(victim_file);
1931         if (rc < 0)
1932                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1933                         progname, fname, error_loc, strerror(-rc));
1934         return rc;
1935 }
1936
1937 static int mirror_extend_layout(char *name, struct llapi_layout *m_layout,
1938                                 bool inherit, uint32_t flags)
1939 {
1940         struct llapi_layout *f_layout = NULL;
1941         struct ll_ioc_lease *data = NULL;
1942         int fd = -1;
1943         int fdv = -1;
1944         int rc = 0;
1945
1946         if (inherit) {
1947                 f_layout = llapi_layout_get_by_path(name, 0);
1948                 if (!f_layout) {
1949                         fprintf(stderr, "%s: cannot get layout\n", progname);
1950                         goto out;
1951                 }
1952                 rc = llapi_layout_get_last_init_comp(f_layout);
1953                 if (rc) {
1954                         fprintf(stderr, "%s: cannot get the last init comp\n",
1955                                 progname);
1956                         goto out;
1957                 }
1958                 rc = llapi_layout_mirror_inherit(f_layout, m_layout);
1959                 if (rc) {
1960                         fprintf(stderr,
1961                                 "%s: cannot inherit from the last init comp\n",
1962                                 progname);
1963                         goto out;
1964                 }
1965         }
1966         llapi_layout_comp_flags_set(m_layout, flags);
1967         rc = migrate_open_files(name, MIGRATION_NONDIRECT, NULL, m_layout, &fd,
1968                                 &fdv);
1969         if (rc < 0)
1970                 goto out;
1971
1972         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1973         if (rc < 0) {
1974                 error_loc = "cannot get lease";
1975                 goto out;
1976         }
1977
1978         rc = migrate_nonblock(fd, fdv);
1979         if (rc < 0) {
1980                 llapi_lease_release(fd);
1981                 goto out;
1982         }
1983
1984         /* Atomically put lease, merge layouts and close. */
1985         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1986         if (!data) {
1987                 error_loc = "memory allocation";
1988                 goto out;
1989         }
1990         data->lil_mode = LL_LEASE_UNLCK;
1991         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1992         data->lil_count = 1;
1993         data->lil_ids[0] = fdv;
1994         rc = llapi_lease_set(fd, data);
1995         if (rc < 0) {
1996                 error_loc = "cannot merge layout";
1997                 goto out;
1998         } else if (rc == 0) {
1999                 rc = -EBUSY;
2000                 error_loc = "lost lease lock";
2001                 goto out;
2002         }
2003         rc = 0;
2004
2005 out:
2006         if (data)
2007                 free(data);
2008         if (fd >= 0)
2009                 close(fd);
2010         if (fdv >= 0)
2011                 close(fdv);
2012         if (rc < 0)
2013                 fprintf(stderr, "error: %s: %s: %s: %s\n",
2014                         progname, name, error_loc, strerror(-rc));
2015         return rc;
2016 }
2017
2018 static int mirror_extend(char *fname, struct mirror_args *mirror_list,
2019                          enum mirror_flags mirror_flags)
2020 {
2021         int rc;
2022
2023         rc = mirror_create_sanity_check(fname, mirror_list, true);
2024         if (rc)
2025                 return rc;
2026
2027         while (mirror_list) {
2028                 if (mirror_list->m_file) {
2029                         rc = mirror_extend_file(fname, mirror_list->m_file,
2030                                                 mirror_flags);
2031                 } else {
2032                         __u32 mirror_count = mirror_list->m_count;
2033
2034                         while (mirror_count > 0) {
2035                                 rc = mirror_extend_layout(fname,
2036                                                         mirror_list->m_layout,
2037                                                         mirror_list->m_inherit,
2038                                                         mirror_list->m_flags);
2039                                 if (rc)
2040                                         break;
2041
2042                                 --mirror_count;
2043                         }
2044                 }
2045                 if (rc)
2046                         break;
2047
2048                 mirror_list = mirror_list->m_next;
2049         }
2050
2051         return rc;
2052 }
2053
2054 static int find_mirror_id(struct llapi_layout *layout, void *cbdata)
2055 {
2056         uint32_t id;
2057         int rc;
2058
2059         rc = llapi_layout_mirror_id_get(layout, &id);
2060         if (rc < 0)
2061                 return rc;
2062
2063         if ((__u16)id == *(__u16 *)cbdata)
2064                 return LLAPI_LAYOUT_ITER_STOP;
2065
2066         return LLAPI_LAYOUT_ITER_CONT;
2067 }
2068
2069 static int find_comp_id(struct llapi_layout *layout, void *cbdata)
2070 {
2071         uint32_t id;
2072         int rc;
2073
2074         rc = llapi_layout_comp_id_get(layout, &id);
2075         if (rc < 0)
2076                 return rc;
2077
2078         if (id == *(__u32 *)cbdata)
2079                 return LLAPI_LAYOUT_ITER_STOP;
2080
2081         return LLAPI_LAYOUT_ITER_CONT;
2082 }
2083
2084 static int find_mirror_id_by_pool(struct llapi_layout *layout, void *cbdata)
2085 {
2086         char buf[LOV_MAXPOOLNAME + 1];
2087         struct pool_to_id_cbdata *d = (void *)cbdata;
2088         uint32_t id;
2089         int rc;
2090
2091         rc = llapi_layout_pool_name_get(layout, buf, sizeof(buf));
2092         if (rc < 0)
2093                 return rc;
2094         if (strcmp(d->pool, buf))
2095                 return LLAPI_LAYOUT_ITER_CONT;
2096
2097         rc = llapi_layout_mirror_id_get(layout, &id);
2098         if (rc < 0)
2099                 return rc;
2100         d->id = id;
2101
2102         return LLAPI_LAYOUT_ITER_STOP;
2103 }
2104
2105 static int find_comp_id_by_pool(struct llapi_layout *layout, void *cbdata)
2106 {
2107         char buf[LOV_MAXPOOLNAME + 1];
2108         struct pool_to_id_cbdata *d = (void *)cbdata;
2109         uint32_t id;
2110         int rc;
2111
2112         rc = llapi_layout_pool_name_get(layout, buf, sizeof(buf));
2113         if (rc < 0)
2114                 return rc;
2115         if (strcmp(d->pool, buf))
2116                 return LLAPI_LAYOUT_ITER_CONT;
2117
2118         rc = llapi_layout_comp_id_get(layout, &id);
2119         if (rc < 0)
2120                 return rc;
2121         d->id = id;
2122
2123         return LLAPI_LAYOUT_ITER_STOP;
2124 }
2125
2126 struct collect_ids_data {
2127         __u16   *cid_ids;
2128         int     cid_count;
2129         __u16   cid_exclude;
2130 };
2131
2132 static int collect_mirror_id(struct llapi_layout *layout, void *cbdata)
2133 {
2134         struct collect_ids_data *cid = cbdata;
2135         uint32_t id;
2136         int rc;
2137
2138         rc = llapi_layout_mirror_id_get(layout, &id);
2139         if (rc < 0)
2140                 return rc;
2141
2142         if ((__u16)id != cid->cid_exclude) {
2143                 int i;
2144
2145                 for (i = 0; i < cid->cid_count; i++) {
2146                         /* already collected the mirror id */
2147                         if (id == cid->cid_ids[i])
2148                                 return LLAPI_LAYOUT_ITER_CONT;
2149                 }
2150                 cid->cid_ids[cid->cid_count] = id;
2151                 cid->cid_count++;
2152         }
2153
2154         return LLAPI_LAYOUT_ITER_CONT;
2155 }
2156
2157 /**
2158  * last_non_stale_mirror() - Check if a mirror is the last non-stale mirror.
2159  * @mirror_id: Mirror id to be checked.
2160  * @layout:    Mirror component list.
2161  *
2162  * This function checks if a mirror with specified @mirror_id is the last
2163  * non-stale mirror of a layout @layout.
2164  *
2165  * Return: true or false.
2166  */
2167 static inline
2168 bool last_non_stale_mirror(__u16 mirror_id, struct llapi_layout *layout)
2169 {
2170         __u16 mirror_ids[128] = { 0 };
2171         struct collect_ids_data cid = { .cid_ids = mirror_ids,
2172                                         .cid_count = 0,
2173                                         .cid_exclude = mirror_id, };
2174         int i;
2175
2176         llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
2177
2178         for (i = 0; i < cid.cid_count; i++) {
2179                 struct llapi_resync_comp comp_array[1024] = { { 0 } };
2180                 int comp_size = 0;
2181
2182                 comp_size = llapi_mirror_find_stale(layout, comp_array,
2183                                                     ARRAY_SIZE(comp_array),
2184                                                     &mirror_ids[i], 1);
2185                 if (comp_size == 0)
2186                         return false;
2187         }
2188
2189         return true;
2190 }
2191
2192 static int mirror_split(const char *fname, __u32 id, const char *pool,
2193                         enum mirror_flags mflags, const char *victim_file)
2194 {
2195         struct llapi_layout *layout;
2196         char parent[PATH_MAX];
2197         char victim[PATH_MAX];
2198         int flags = O_CREAT | O_EXCL | O_LOV_DELAY_CREATE | O_NOFOLLOW;
2199         char *ptr;
2200         struct ll_ioc_lease *data;
2201         uint16_t mirror_count;
2202         __u32 mirror_id;
2203         int mdt_index;
2204         int fd, fdv;
2205         bool purge = true; /* delete mirror by setting fdv=fd */
2206         bool is_encrypted;
2207         int rc;
2208
2209         if (victim_file && (strcmp(fname, victim_file) == 0)) {
2210                 fprintf(stderr,
2211                         "error %s: the source file '%s' and -f file are the same\n",
2212                         progname, fname);
2213                 return -EINVAL;
2214         }
2215
2216         /* check fname contains mirror with mirror_id/comp_id */
2217         layout = llapi_layout_get_by_path(fname, 0);
2218         if (!layout) {
2219                 fprintf(stderr,
2220                         "error %s: file '%s' couldn't get layout\n",
2221                         progname, fname);
2222                 return -EINVAL;
2223         }
2224
2225         rc = llapi_layout_sanity(layout, fname, false, true);
2226         if (rc) {
2227                 llapi_layout_sanity_perror(rc);
2228                 goto free_layout;
2229         }
2230
2231         rc = llapi_layout_mirror_count_get(layout, &mirror_count);
2232         if (rc) {
2233                 fprintf(stderr,
2234                         "error %s: file '%s' couldn't get mirror count\n",
2235                         progname, fname);
2236                 goto free_layout;
2237         }
2238         if (mirror_count < 2) {
2239                 fprintf(stderr,
2240                         "error %s: file '%s' has %d component, cannot split\n",
2241                         progname, fname, mirror_count);
2242                 goto free_layout;
2243         }
2244
2245         if (mflags & MF_COMP_POOL) {
2246                 struct pool_to_id_cbdata data = { .pool = pool };
2247
2248                 rc = llapi_layout_comp_iterate(layout, find_mirror_id_by_pool,
2249                                                &data);
2250                 mirror_id = data.id;
2251         } else if (mflags & MF_COMP_ID) {
2252                 rc = llapi_layout_comp_iterate(layout, find_comp_id, &id);
2253                 mirror_id = mirror_id_of(id);
2254         } else {
2255                 rc = llapi_layout_comp_iterate(layout, find_mirror_id, &id);
2256                 mirror_id = id;
2257         }
2258         if (rc < 0) {
2259                 fprintf(stderr, "error %s: failed to iterate layout of '%s'\n",
2260                         progname, fname);
2261                 goto free_layout;
2262         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
2263                 if (mflags & MF_COMP_POOL) {
2264                         fprintf(stderr,
2265                                 "error %s: file '%s' does not contain mirror with pool '%s'\n",
2266                                 progname, fname, pool);
2267                         goto free_layout;
2268                 } else if (mflags & MF_COMP_ID) {
2269                         fprintf(stderr,
2270                                 "error %s: file '%s' does not contain mirror with comp-id %u\n",
2271                                 progname, fname, id);
2272                         goto free_layout;
2273                 } else {
2274                         fprintf(stderr,
2275                                 "error %s: file '%s' does not contain mirror with id %u\n",
2276                                 progname, fname, id);
2277                         goto free_layout;
2278                 }
2279         }
2280
2281         fd = open(fname, O_RDWR);
2282         if (fd < 0) {
2283                 fprintf(stderr,
2284                         "error %s: open file '%s' failed: %s\n",
2285                         progname, fname, strerror(errno));
2286                 goto free_layout;
2287         }
2288
2289         /* get victim file directory pathname */
2290         if (strlen(fname) > sizeof(parent) - 1) {
2291                 fprintf(stderr, "error %s: file name of '%s' too long\n",
2292                         progname, fname);
2293                 rc = -ERANGE;
2294                 goto close_fd;
2295         }
2296         strncpy(parent, fname, sizeof(parent));
2297         ptr = strrchr(parent, '/');
2298         if (!ptr) {
2299                 if (!getcwd(parent, sizeof(parent))) {
2300                         fprintf(stderr, "error %s: getcwd failed: %s\n",
2301                                 progname, strerror(errno));
2302                         rc = -errno;
2303                         goto close_fd;
2304                 }
2305         } else {
2306                 if (ptr == parent)
2307                         ptr = parent + 1;
2308                 *ptr = '\0';
2309         }
2310
2311         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
2312         if (rc < 0) {
2313                 fprintf(stderr, "%s: cannot get MDT index of '%s'\n",
2314                         progname, fname);
2315                 goto close_fd;
2316         }
2317
2318         rc = llapi_file_is_encrypted(fd);
2319         if (rc < 0) {
2320                 fprintf(stderr, "%s: cannot get flags of '%s': %d\n",
2321                         progname, fname, rc);
2322                 goto close_fd;
2323         }
2324         is_encrypted = rc;
2325
2326 again:
2327         if (!victim_file) {
2328                 /* use a temp file to store the splitted layout */
2329                 if (mflags & MF_DESTROY) {
2330                         char file_path[PATH_MAX];
2331                         unsigned int rnumber;
2332                         int open_flags;
2333
2334                         if (last_non_stale_mirror(mirror_id, layout)) {
2335                                 rc = -EUCLEAN;
2336                                 fprintf(stderr,
2337                                         "%s: cannot destroy the last non-stale mirror of file '%s'\n",
2338                                         progname, fname);
2339                                 goto close_fd;
2340                         }
2341
2342                         if (purge) {
2343                                 /* don't use volatile file for mirror destroy */
2344                                 fdv = fd;
2345                         } else {
2346                                 /**
2347                                  * try the old way to delete mirror using
2348                                  * volatile file.
2349                                  */
2350                                 do {
2351                                         rnumber = random();
2352                                         rc = snprintf(file_path,
2353                                                       sizeof(file_path),
2354                                                       "%s/" LUSTRE_VOLATILE_HDR ":%.4X:%.4X:fd=%.2d",
2355                                                       parent, mdt_index,
2356                                                       rnumber, fd);
2357                                         if (rc < 0 ||
2358                                             rc >= sizeof(file_path)) {
2359                                                 fdv = -ENAMETOOLONG;
2360                                                 break;
2361                                         }
2362
2363                                         open_flags = O_RDWR |
2364                                              (O_LOV_DELAY_CREATE & ~O_ACCMODE) |
2365                                              O_CREAT | O_EXCL | O_NOFOLLOW;
2366                                         fdv = open(file_path, open_flags,
2367                                                    S_IRUSR | S_IWUSR);
2368                                         if (fdv < 0)
2369                                                 rc = -errno;
2370                                 } while (fdv < 0 && rc == -EEXIST);
2371                         }
2372                 } else {
2373                         if (is_encrypted) {
2374                                 rc = -1;
2375                                 fprintf(stderr,
2376                                         "error %s: not permitted on encrypted file '%s': %d\n",
2377                                         progname, fname, rc);
2378                                 goto close_fd;
2379                         }
2380
2381                         snprintf(victim, sizeof(victim), "%s.mirror~%u",
2382                                  fname, mirror_id);
2383                         fdv = open(victim, flags, S_IRUSR | S_IWUSR);
2384                 }
2385         } else {
2386                 /* user specified victim file */
2387                 if (is_encrypted) {
2388                         rc = -1;
2389                         fprintf(stderr,
2390                                 "error %s: not permitted on encrypted file '%s': %d\n",
2391                                 progname, fname, rc);
2392                         goto close_fd;
2393                 }
2394                 fdv = open(victim_file, flags, S_IRUSR | S_IWUSR);
2395         }
2396
2397         if (fdv < 0) {
2398                 fprintf(stderr,
2399                         "error %s: create victim file failed: %s\n",
2400                         progname, strerror(errno));
2401                 goto close_fd;
2402         }
2403
2404         /* get lease lock of fname */
2405         rc = llapi_lease_acquire(fd, LL_LEASE_WRLCK);
2406         if (rc < 0) {
2407                 fprintf(stderr,
2408                         "error %s: cannot get lease of file '%s': %d\n",
2409                         progname, fname, rc);
2410                 goto close_victim;
2411         }
2412
2413         /* Atomatically put lease, split layouts and close. */
2414         data = malloc(offsetof(typeof(*data), lil_ids[2]));
2415         if (!data) {
2416                 rc = -ENOMEM;
2417                 goto close_victim;
2418         }
2419
2420         data->lil_mode = LL_LEASE_UNLCK;
2421         data->lil_flags = LL_LEASE_LAYOUT_SPLIT;
2422         data->lil_count = 2;
2423         data->lil_ids[0] = fdv;
2424         data->lil_ids[1] = mirror_id;
2425         rc = llapi_lease_set(fd, data);
2426         if (rc <= 0) {
2427                 if (rc == -EINVAL && purge) {
2428                         /* could be old MDS which prohibit fd==fdv */
2429                         purge = false;
2430                         goto again;
2431
2432                 }
2433                 if (rc == 0) /* lost lease lock */
2434                         rc = -EBUSY;
2435                 fprintf(stderr,
2436                         "error %s: cannot split '%s': %s\n",
2437                         progname, fname, strerror(-rc));
2438         } else {
2439                 rc = 0;
2440         }
2441         free(data);
2442
2443 close_victim:
2444         if (!purge)
2445                 close(fdv);
2446 close_fd:
2447         close(fd);
2448 free_layout:
2449         llapi_layout_free(layout);
2450         return rc;
2451 }
2452
2453 static inline
2454 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
2455                            __u16 *mirror_ids, int ids_nr);
2456
2457 static int lfs_migrate_to_dom(int fd, int fdv, char *name,
2458                               __u64 migration_flags,
2459                               struct llapi_stripe_param *param,
2460                               struct llapi_layout *layout)
2461 {
2462         struct ll_ioc_lease *data = NULL;
2463         int rc;
2464
2465         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
2466         if (rc < 0) {
2467                 error_loc = "cannot get lease";
2468                 goto out_close;
2469         }
2470
2471         /* Atomically put lease, merge layouts, resync and close. */
2472         data = calloc(1, offsetof(typeof(*data), lil_ids[1024]));
2473         if (!data) {
2474                 error_loc = "memory allocation";
2475                 goto out_close;
2476         }
2477         data->lil_mode = LL_LEASE_UNLCK;
2478         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
2479         data->lil_count = 1;
2480         data->lil_ids[0] = fdv;
2481         rc = llapi_lease_set(fd, data);
2482         if (rc < 0) {
2483                 error_loc = "cannot merge layout";
2484                 goto out_close;
2485         } else if (rc == 0) {
2486                 rc = -EBUSY;
2487                 error_loc = "lost lease lock";
2488                 goto out_close;
2489         }
2490         close(fd);
2491         close(fdv);
2492
2493         rc = lfs_mirror_resync_file(name, data, NULL, 0);
2494         if (rc) {
2495                 error_loc = "cannot resync file";
2496                 goto out;
2497         }
2498
2499         /* delete first mirror now */
2500         rc = mirror_split(name, 1, NULL, MF_DESTROY, NULL);
2501         if (rc < 0)
2502                 error_loc = "cannot delete old layout";
2503         goto out;
2504
2505 out_close:
2506         close(fd);
2507         close(fdv);
2508 out:
2509         if (rc < 0)
2510                 fprintf(stderr, "error: %s: %s: %s: %s\n",
2511                         progname, name, error_loc, strerror(-rc));
2512         else if (migration_flags & MIGRATION_VERBOSE)
2513                 printf("%s\n", name);
2514         if (data)
2515                 free(data);
2516         return rc;
2517 }
2518
2519 /**
2520  * Parse a string containing an target index list into an array of integers.
2521  *
2522  * The input string contains a comma delimited list of individual
2523  * indices and ranges, for example "1,2-4,7". Add the indices into the
2524  * \a tgts array and remove duplicates.
2525  *
2526  * \param[out] tgts             array to store indices in
2527  * \param[in] size              size of \a tgts array
2528  * \param[in] offset            starting index in \a tgts
2529  * \param[in] arg               string containing OST index list
2530  * \param[in/out] overstriping  index list may contain duplicates
2531  *
2532  * \retval positive    number of indices in \a tgts
2533  * \retval -EINVAL     unable to parse \a arg
2534  */
2535 static int parse_targets(__u32 *tgts, int size, int offset, char *arg,
2536                          unsigned long long *pattern)
2537 {
2538         int rc;
2539         int nr = offset;
2540         int slots = size - offset;
2541         char *ptr = NULL;
2542         bool overstriped = false;
2543         bool end_of_loop;
2544
2545         if (!arg)
2546                 return -EINVAL;
2547
2548         end_of_loop = false;
2549         while (!end_of_loop) {
2550                 int start_index = 0;
2551                 int end_index = 0;
2552                 int i;
2553                 char *endptr = NULL;
2554
2555                 rc = -EINVAL;
2556
2557                 ptr = strchrnul(arg, ',');
2558
2559                 end_of_loop = *ptr == '\0';
2560                 *ptr = '\0';
2561
2562                 errno = 0;
2563                 start_index = strtol(arg, &endptr, 0);
2564                 if (endptr == arg) /* no data at all */
2565                         break;
2566                 if (errno != 0 || start_index < -1 ||
2567                     (*endptr != '-' && *endptr != '\0'))
2568                         break;
2569
2570                 end_index = start_index;
2571                 if (*endptr == '-') {
2572                         errno = 0;
2573                         end_index = strtol(endptr + 1, &endptr, 0);
2574                         if (errno != 0 || *endptr != '\0' || end_index < -1)
2575                                 break;
2576                         if (end_index < start_index)
2577                                 break;
2578                 }
2579
2580                 for (i = start_index; i <= end_index && slots > 0; i++) {
2581                         int j;
2582
2583                         /* remove duplicate */
2584                         for (j = 0; j < offset; j++) {
2585                                 if (tgts[j] == i && pattern &&
2586                                     *pattern == LLAPI_LAYOUT_OVERSTRIPING)
2587                                         overstriped = true;
2588                                 else if (tgts[j] == i)
2589                                         return -EINVAL;
2590                         }
2591
2592                         j = offset;
2593
2594                         if (j == offset) { /* check complete */
2595                                 tgts[nr++] = i;
2596                                 --slots;
2597                         }
2598                 }
2599
2600                 if (slots == 0 && i < end_index)
2601                         break;
2602
2603                 *ptr = ',';
2604                 arg = ++ptr;
2605                 offset = nr;
2606                 rc = 0;
2607         }
2608         if (!end_of_loop && ptr)
2609                 *ptr = ',';
2610
2611         if (!overstriped && pattern)
2612                 *pattern = LLAPI_LAYOUT_DEFAULT;
2613
2614         return rc < 0 ? rc : nr;
2615 }
2616
2617 struct lfs_setstripe_args {
2618         unsigned long long       lsa_comp_end;
2619         unsigned long long       lsa_stripe_size;
2620         unsigned long long       lsa_extension_size;
2621         long long                lsa_stripe_count;
2622         long long                lsa_stripe_off;
2623         __u32                    lsa_comp_flags;
2624         __u32                    lsa_comp_neg_flags;
2625         unsigned long long       lsa_pattern;
2626         unsigned int             lsa_mirror_count;
2627         int                      lsa_nr_tgts;
2628         bool                     lsa_first_comp;
2629         bool                     lsa_extension_comp;
2630         __u32                   *lsa_tgts;
2631         char                    *lsa_pool_name;
2632 };
2633
2634 static inline void setstripe_args_init(struct lfs_setstripe_args *lsa)
2635 {
2636         unsigned int mirror_count = lsa->lsa_mirror_count;
2637         bool first_comp = lsa->lsa_first_comp;
2638
2639         memset(lsa, 0, sizeof(*lsa));
2640
2641         lsa->lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
2642         lsa->lsa_stripe_count = LLAPI_LAYOUT_DEFAULT;
2643         lsa->lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2644         lsa->lsa_pattern = LLAPI_LAYOUT_RAID0;
2645         lsa->lsa_pool_name = NULL;
2646
2647         lsa->lsa_mirror_count = mirror_count;
2648         lsa->lsa_first_comp = first_comp;
2649 }
2650
2651 /**
2652  * setstripe_args_init_inherit() - Initialize and inherit stripe options.
2653  * @lsa: Stripe options to be initialized and inherited.
2654  *
2655  * This function initializes stripe options in @lsa and inherit
2656  * stripe_size, stripe_count and OST pool_name options.
2657  *
2658  * Return: void.
2659  */
2660 static inline void setstripe_args_init_inherit(struct lfs_setstripe_args *lsa)
2661 {
2662         unsigned long long stripe_size;
2663         long long stripe_count;
2664         char *pool_name = NULL;
2665
2666         stripe_size = lsa->lsa_stripe_size;
2667         stripe_count = lsa->lsa_stripe_count;
2668         pool_name = lsa->lsa_pool_name;
2669
2670         setstripe_args_init(lsa);
2671
2672         lsa->lsa_stripe_size = stripe_size;
2673         lsa->lsa_stripe_count = stripe_count;
2674         lsa->lsa_pool_name = pool_name;
2675 }
2676
2677 static inline bool setstripe_args_specified(struct lfs_setstripe_args *lsa)
2678 {
2679         return (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT ||
2680                 lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ||
2681                 lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
2682                 lsa->lsa_pattern != LLAPI_LAYOUT_RAID0 ||
2683                 lsa->lsa_comp_end != 0);
2684 }
2685
2686 static int lsa_args_stripe_count_check(struct lfs_setstripe_args *lsa)
2687 {
2688         if (lsa->lsa_nr_tgts) {
2689                 if (lsa->lsa_nr_tgts < 0 ||
2690                     lsa->lsa_nr_tgts >= LOV_MAX_STRIPE_COUNT) {
2691                         fprintf(stderr, "Invalid nr_tgts(%d)\n",
2692                                 lsa->lsa_nr_tgts);
2693                         errno = EINVAL;
2694                         return -1;
2695                 }
2696
2697                 if (lsa->lsa_stripe_count > 0 &&
2698                     lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
2699                     lsa->lsa_stripe_count != LLAPI_LAYOUT_WIDE &&
2700                     lsa->lsa_nr_tgts != lsa->lsa_stripe_count) {
2701                         fprintf(stderr, "stripe_count(%lld) != nr_tgts(%d)\n",
2702                                 lsa->lsa_stripe_count,
2703                                 lsa->lsa_nr_tgts);
2704                         errno = EINVAL;
2705                         return -1;
2706                 }
2707         }
2708
2709         return 0;
2710
2711 }
2712
2713 /**
2714  * comp_args_to_layout() - Create or extend a composite layout.
2715  * @composite:       Pointer to the composite layout.
2716  * @lsa:             Stripe options for the new component.
2717  *
2718  * This function creates or extends a composite layout by adding a new
2719  * component with stripe options from @lsa.
2720  *
2721  * When modified, adjust llapi_stripe_param_verify() if needed as well.
2722  *
2723  * Return: 0 on success or an error code on failure.
2724  */
2725 static int comp_args_to_layout(struct llapi_layout **composite,
2726                                struct lfs_setstripe_args *lsa,
2727                                bool set_extent)
2728 {
2729         struct llapi_layout *layout = *composite;
2730         uint64_t prev_end = 0;
2731         uint64_t size;
2732         int i = 0, rc;
2733
2734 new_comp:
2735         if (!layout) {
2736                 layout = llapi_layout_alloc();
2737                 if (!layout) {
2738                         fprintf(stderr, "Alloc llapi_layout failed. %s\n",
2739                                 strerror(errno));
2740                         errno = ENOMEM;
2741                         return -1;
2742                 }
2743                 *composite = layout;
2744                 lsa->lsa_first_comp = true;
2745         } else {
2746                 uint64_t start;
2747
2748                 /*
2749                  * Get current component extent, current component
2750                  * must be the tail component.
2751                  */
2752                 rc = llapi_layout_comp_extent_get(layout, &start, &prev_end);
2753                 if (rc) {
2754                         fprintf(stderr, "Get comp extent failed. %s\n",
2755                                 strerror(errno));
2756                         return rc;
2757                 }
2758
2759                 if (lsa->lsa_first_comp) {
2760                         prev_end = 0;
2761                         rc = llapi_layout_add_first_comp(layout);
2762                 } else {
2763                         rc = llapi_layout_comp_add(layout);
2764                 }
2765                 if (rc) {
2766                         fprintf(stderr, "Add component failed. %s\n",
2767                                 strerror(errno));
2768                         return rc;
2769                 }
2770         }
2771
2772         rc = llapi_layout_comp_flags_set(layout, lsa->lsa_comp_flags);
2773         if (rc) {
2774                 fprintf(stderr, "Set flags 0x%x failed: %s\n",
2775                         lsa->lsa_comp_flags, strerror(errno));
2776                 return rc;
2777         }
2778
2779         if (set_extent) {
2780                 uint64_t comp_end = lsa->lsa_comp_end;
2781
2782                 /*
2783                  * The extendable component is 0-length, so it can be removed
2784                  * if there is insufficient space to extend it.
2785                  */
2786                 if (lsa->lsa_extension_comp)
2787                         comp_end = prev_end;
2788
2789                 rc = llapi_layout_comp_extent_set(layout, prev_end,
2790                                                   comp_end);
2791                 if (rc) {
2792                         fprintf(stderr, "Set extent [%lu, %lu) failed. %s\n",
2793                                 prev_end, comp_end, strerror(errno));
2794                         return rc;
2795                 }
2796         }
2797         /* reset lsa_first_comp */
2798         lsa->lsa_first_comp = false;
2799
2800         /* Data-on-MDT component setting */
2801         if (lsa->lsa_pattern == LLAPI_LAYOUT_MDT) {
2802                 /*
2803                  * In case of Data-on-MDT patterns the only extra option
2804                  * applicable is stripe size option.
2805                  */
2806                 if (lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
2807                         fprintf(stderr,
2808                                 "Option 'stripe-count' can't be specified with Data-on-MDT component: %lld\n",
2809                                 lsa->lsa_stripe_count);
2810                         errno = EINVAL;
2811                         return -1;
2812                 }
2813                 if (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT) {
2814                         fprintf(stderr,
2815                                 "Option 'stripe-size' can't be specified with Data-on-MDT component: %llu\n",
2816                                 lsa->lsa_stripe_size);
2817                         errno = EINVAL;
2818                         return -1;
2819                 }
2820                 if (lsa->lsa_nr_tgts != 0) {
2821                         fprintf(stderr,
2822                                 "Option 'ost-list' can't be specified with Data-on-MDT component: '%i'\n",
2823                                 lsa->lsa_nr_tgts);
2824                         errno = EINVAL;
2825                         return -1;
2826                 }
2827                 if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT) {
2828                         fprintf(stderr,
2829                                 "Option 'stripe-offset' can't be specified with Data-on-MDT component: %lld\n",
2830                                 lsa->lsa_stripe_off);
2831                         errno = EINVAL;
2832                         return -1;
2833                 }
2834                 if (lsa->lsa_pool_name != 0) {
2835                         fprintf(stderr,
2836                                 "Option 'pool' can't be specified with Data-on-MDT component: '%s'\n",
2837                                 lsa->lsa_pool_name);
2838                         errno = EINVAL;
2839                         return -1;
2840                 }
2841
2842                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2843                 if (rc) {
2844                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2845                                 lsa->lsa_pattern,
2846                                 strerror(errno));
2847                         return rc;
2848                 }
2849                 /* Data-on-MDT component has always single stripe up to end */
2850                 lsa->lsa_stripe_size = lsa->lsa_comp_end;
2851         } else if (lsa->lsa_pattern == LLAPI_LAYOUT_OVERSTRIPING) {
2852                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2853                 if (rc) {
2854                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2855                                 lsa->lsa_pattern,
2856                                 strerror(errno));
2857                         return rc;
2858                 }
2859         }
2860
2861         size = lsa->lsa_comp_flags & LCME_FL_EXTENSION ?
2862                 lsa->lsa_extension_size : lsa->lsa_stripe_size;
2863
2864         if (lsa->lsa_comp_flags & LCME_FL_EXTENSION)
2865                 rc = llapi_layout_extension_size_set(layout, size);
2866         else
2867                 rc = llapi_layout_stripe_size_set(layout, size);
2868
2869         if (rc) {
2870                 fprintf(stderr, "Set stripe size %lu failed: %s\n",
2871                         size, strerror(errno));
2872                 return rc;
2873         }
2874
2875         rc = llapi_layout_stripe_count_set(layout, lsa->lsa_stripe_count);
2876         if (rc) {
2877                 fprintf(stderr, "Set stripe count %lld failed: %s\n",
2878                         lsa->lsa_stripe_count, strerror(errno));
2879                 return rc;
2880         }
2881
2882         if (lsa->lsa_pool_name) {
2883                 rc = llapi_layout_pool_name_set(layout, lsa->lsa_pool_name);
2884                 if (rc) {
2885                         fprintf(stderr, "Set pool name: %s failed. %s\n",
2886                                 lsa->lsa_pool_name, strerror(errno));
2887                         return rc;
2888                 }
2889         } else {
2890                 rc = llapi_layout_pool_name_set(layout, "");
2891                 if (rc) {
2892                         fprintf(stderr, "Clear pool name failed: %s\n",
2893                                 strerror(errno));
2894                         return rc;
2895                 }
2896         }
2897
2898         rc = lsa_args_stripe_count_check(lsa);
2899         if (rc)
2900                 return rc;
2901
2902         if (lsa->lsa_nr_tgts > 0) {
2903                 bool found = false;
2904
2905                 for (i = 0; i < lsa->lsa_nr_tgts; i++) {
2906                         rc = llapi_layout_ost_index_set(layout, i,
2907                                                         lsa->lsa_tgts[i]);
2908                         if (rc)
2909                                 break;
2910
2911                         /* Make sure stripe offset is in OST list. */
2912                         if (lsa->lsa_tgts[i] == lsa->lsa_stripe_off)
2913                                 found = true;
2914                 }
2915                 if (!found) {
2916                         fprintf(stderr, "Invalid stripe offset '%lld', not in the target list",
2917                                 lsa->lsa_stripe_off);
2918                         errno = EINVAL;
2919                         return -1;
2920                 }
2921         } else if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT &&
2922                    lsa->lsa_stripe_off != -1) {
2923                 rc = llapi_layout_ost_index_set(layout, 0, lsa->lsa_stripe_off);
2924         }
2925         if (rc) {
2926                 fprintf(stderr, "Set ost index %d failed. %s\n",
2927                         i, strerror(errno));
2928                 return rc;
2929         }
2930
2931         /* Create the second, virtual component of extension space */
2932         if (lsa->lsa_extension_comp) {
2933                 lsa->lsa_comp_flags |= LCME_FL_EXTENSION;
2934                 lsa->lsa_extension_comp = false;
2935                 goto new_comp;
2936         }
2937
2938         return rc;
2939 }
2940
2941 static int build_component(struct llapi_layout **layout,
2942                            struct lfs_setstripe_args *lsa, bool set_extent)
2943 {
2944         int rc;
2945
2946         rc = comp_args_to_layout(layout, lsa, set_extent);
2947         if (rc)
2948                 return rc;
2949
2950         if (lsa->lsa_mirror_count > 0) {
2951                 rc = llapi_layout_mirror_count_set(*layout,
2952                                                    lsa->lsa_mirror_count);
2953                 if (rc)
2954                         return rc;
2955
2956                 rc = llapi_layout_flags_set(*layout, LCM_FL_RDONLY);
2957                 if (rc)
2958                         return rc;
2959                 lsa->lsa_mirror_count = 0;
2960         }
2961
2962         return rc;
2963 }
2964
2965 static int build_prev_component(struct llapi_layout **layout,
2966                                 struct lfs_setstripe_args *prev,
2967                                 struct lfs_setstripe_args *lsa,
2968                                 bool set_extent)
2969 {
2970         int extension = lsa->lsa_comp_flags & LCME_FL_EXTENSION;
2971         int rc;
2972
2973         if (prev->lsa_stripe_size) {
2974                 if (extension) {
2975                         prev->lsa_comp_end = lsa->lsa_comp_end;
2976                         prev->lsa_extension_size = lsa->lsa_extension_size;
2977                         prev->lsa_extension_comp = true;
2978                 }
2979
2980                 rc = build_component(layout, prev, true);
2981                 if (rc)
2982                         return rc;
2983         }
2984
2985         /*
2986          * Copy lsa to previous lsa;
2987          * if this is an extension component, make the previous invalid;
2988          */
2989         if (extension)
2990                 prev->lsa_stripe_size = 0;
2991         else
2992                 *prev = *lsa;
2993
2994         return 0;
2995 }
2996
2997 static int build_layout_from_yaml_node(struct cYAML *node,
2998                                        struct llapi_layout **layout,
2999                                        struct lfs_setstripe_args *lsa,
3000                                        struct lfs_setstripe_args *prevp)
3001 {
3002         struct lfs_setstripe_args prev = { 0 };
3003         __u32 *osts = lsa->lsa_tgts;
3004         char *string;
3005         int rc = 0;
3006
3007         if (!prevp)
3008                 prevp = &prev;
3009
3010         while (node) {
3011                 string = node->cy_string;
3012
3013                 if (node->cy_type == CYAML_TYPE_OBJECT) {
3014                         /* go deep to sub blocks */
3015                         if (string && !strncmp(string, "component", 9) &&
3016                             strncmp(string, "component0", 10) &&
3017                             strncmp(string, "components", 10)) {
3018                                 rc = build_prev_component(layout, prevp, lsa,
3019                                                           true);
3020                                 if (rc)
3021                                         return rc;
3022
3023                                 /* initialize lsa. */
3024                                 setstripe_args_init(lsa);
3025                                 lsa->lsa_first_comp = false;
3026                                 lsa->lsa_tgts = osts;
3027                         }
3028
3029                         rc = build_layout_from_yaml_node(node->cy_child, layout,
3030                                                          lsa, prevp);
3031                         if (rc)
3032                                 return rc;
3033                 } else {
3034                         if (!node->cy_string)
3035                                 return -EINVAL;
3036
3037                         /* skip leading lmm_ if present, to simplify parsing */
3038                         if (strncmp(string, "lmm_", 4) == 0)
3039                                 string += 4;
3040
3041                         if (node->cy_type == CYAML_TYPE_STRING) {
3042                                 if (!strcmp(string, "lcme_extent.e_end")) {
3043                                         if (!strcmp(node->cy_valuestring, "EOF") ||
3044                                             !strcmp(node->cy_valuestring, "eof"))
3045                                                 lsa->lsa_comp_end = LUSTRE_EOF;
3046                                 } else if (!strcmp(string, "pool")) {
3047                                         lsa->lsa_pool_name = node->cy_valuestring;
3048                                 } else if (!strcmp(string, "pattern")) {
3049                                         if (!strcmp(node->cy_valuestring, "mdt"))
3050                                                 lsa->lsa_pattern = LLAPI_LAYOUT_MDT;
3051                                         if (!strcmp(node->cy_valuestring,
3052                                                     "raid0,overstriped"))
3053                                                 lsa->lsa_pattern =
3054                                                         LLAPI_LAYOUT_OVERSTRIPING;
3055                                 } else if (!strcmp(string, "lcme_flags")) {
3056                                         rc = comp_str2flags(node->cy_valuestring,
3057                                                             &lsa->lsa_comp_flags,
3058                                                             &lsa->lsa_comp_neg_flags);
3059                                         if (rc)
3060                                                 return rc;
3061                                         /*
3062                                          * Only template flags have meaning in
3063                                          * the layout for a new file
3064                                          */
3065                                         lsa->lsa_comp_flags &= LCME_TEMPLATE_FLAGS;
3066                                 }
3067                         } else if (node->cy_type == CYAML_TYPE_NUMBER) {
3068                                 if (!strcmp(string, "lcm_mirror_count")) {
3069                                         lsa->lsa_mirror_count = node->cy_valueint;
3070                                 } else if (!strcmp(string, "lcme_extent.e_start")) {
3071                                         if (node->cy_valueint == 0)
3072                                                 lsa->lsa_first_comp = true;
3073                                 } else if (!strcmp(string, "lcme_extent.e_end")) {
3074                                         if (node->cy_valueint == -1)
3075                                                 lsa->lsa_comp_end = LUSTRE_EOF;
3076                                         else
3077                                                 lsa->lsa_comp_end = node->cy_valueint;
3078                                 } else if (!strcmp(string, "stripe_count")) {
3079                                         lsa->lsa_stripe_count = node->cy_valueint;
3080                                 } else if (!strcmp(string, "stripe_size")) {
3081                                         lsa->lsa_stripe_size = node->cy_valueint;
3082                                 } else if (!strcmp(string, "extension_size")) {
3083                                         lsa->lsa_extension_size = node->cy_valueint;
3084                                         lsa->lsa_extension_comp = true;
3085                                 } else if (!strcmp(string, "stripe_offset")) {
3086                                         lsa->lsa_stripe_off = node->cy_valueint;
3087                                 } else if (!strcmp(string, "l_ost_idx")) {
3088                                         osts[lsa->lsa_nr_tgts] = node->cy_valueint;
3089                                         lsa->lsa_nr_tgts++;
3090                                 }
3091                         }
3092                 }
3093                 node = node->cy_next;
3094         }
3095
3096         if (prevp == &prev) {
3097                 rc = build_prev_component(layout, prevp, lsa, true);
3098                 if (rc)
3099                         return rc;
3100
3101                 if (!(lsa->lsa_comp_flags & LCME_FL_EXTENSION))
3102                         rc = build_component(layout, lsa, *layout != NULL);
3103         }
3104
3105         return rc;
3106 }
3107
3108 static int lfs_comp_create_from_yaml(char *template,
3109                                      struct llapi_layout **layout,
3110                                      struct lfs_setstripe_args *lsa,
3111                                      __u32 *osts)
3112 {
3113         struct cYAML *tree = NULL, *err_rc = NULL;
3114         int rc = 0;
3115
3116         tree = cYAML_build_tree(template, NULL, 0, &err_rc, false);
3117         if (!tree) {
3118                 fprintf(stderr, "%s: cannot parse YAML file %s\n",
3119                         progname, template);
3120                 cYAML_build_error(-EINVAL, -1, "yaml", "from comp yaml",
3121                                   "can't parse", &err_rc);
3122                 cYAML_print_tree2file(stderr, err_rc);
3123                 cYAML_free_tree(err_rc);
3124                 rc = -EINVAL;
3125                 goto err;
3126         }
3127
3128         /* initialize lsa for plain file */
3129         setstripe_args_init(lsa);
3130         lsa->lsa_tgts = osts;
3131
3132         rc = build_layout_from_yaml_node(tree, layout, lsa, NULL);
3133         if (rc) {
3134                 fprintf(stderr, "%s: cannot build layout from YAML file %s.\n",
3135                         progname, template);
3136                 goto err;
3137         }
3138         /* clean clean lsa */
3139         setstripe_args_init(lsa);
3140
3141 err:
3142         if (tree)
3143                 cYAML_free_tree(tree);
3144         return rc;
3145 }
3146
3147 /**
3148  * Get the extension size from the next (SEL) component and extend the
3149  * current component on it. The start of the next component is to be
3150  * adjusted as well.
3151  *
3152  * \param[in] layout    the current layout
3153  * \param[in] start     the start of the current component
3154  * \param[in,out] end   the end of the current component
3155  * \param[in] offset    the offset to adjust the end position to instead of
3156  *                      extension size
3157  *
3158  * \retval 0            - extended successfully
3159  * \retval < 0          - error
3160  */
3161 static int layout_extend_comp(struct llapi_layout *layout,
3162                               uint64_t start, uint64_t *end,
3163                               uint64_t offset)
3164 {
3165         uint64_t size, next_start, next_end;
3166         int rc;
3167
3168         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_NEXT);
3169         if (rc < 0) {
3170                 fprintf(stderr,
3171                         "%s setstripe: cannot move component cursor: %s\n",
3172                         progname, strerror(errno));
3173                 return rc;
3174         }
3175
3176         /*
3177          * Even if the @size will not be used below, this will fail if
3178          * this is not a SEL component - a good confirmation we are
3179          * working on right components.
3180          */
3181         rc = llapi_layout_extension_size_get(layout, &size);
3182         if (rc < 0) {
3183                 fprintf(stderr,
3184                         "%s setstripe: cannot get component ext size: %s\n",
3185                         progname, strerror(errno));
3186                 return rc;
3187         }
3188
3189         rc = llapi_layout_comp_extent_get(layout, &next_start, &next_end);
3190         if (rc) {
3191                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
3192                         progname, strerror(errno));
3193                 return rc;
3194         }
3195
3196         next_start += offset ?: size;
3197         rc = llapi_layout_comp_extent_set(layout, next_start, next_end);
3198         if (rc) {
3199                 fprintf(stderr, "%s setstripe: cannot set extent: %s\n",
3200                         progname, strerror(errno));
3201                 return rc;
3202         }
3203
3204         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_PREV);
3205         if (rc < 0) {
3206                 fprintf(stderr,
3207                         "%s setstripe: cannot move component cursor: %s\n",
3208                         progname, strerror(errno));
3209                 return rc;
3210         }
3211
3212         *end += offset ?: size;
3213         rc = llapi_layout_comp_extent_set(layout, start, *end);
3214         if (rc) {
3215                 fprintf(stderr, "%s setstripe: cannot set extent: %s\n",
3216                         progname, strerror(errno));
3217                 return rc;
3218         }
3219
3220         return 0;
3221 }
3222
3223 /**
3224  * In 'lfs setstripe --component-add' mode, we need to fetch the extent
3225  * end of the last component in the existing file, and adjust the
3226  * first extent start of the components to be added accordingly.
3227  *
3228  * In the create mode, we need to check if the first component is an extendable
3229  * SEL component and extend its length to the extension size (first component
3230  * of the PFL file is initialised at the create time, cannot be 0-lenght.
3231  */
3232 static int layout_adjust_first_extent(char *fname, struct llapi_layout *layout,
3233                                       bool comp_add)
3234 {
3235         struct llapi_layout *head;
3236         uint64_t start = 0, prev_end = 0;
3237         uint64_t end;
3238         int rc, ret = 0;
3239
3240         if (!layout || !(comp_add || llapi_layout_is_composite(layout)))
3241                 return 0;
3242
3243         errno = 0;
3244         while (comp_add) {
3245                 head = llapi_layout_get_by_path(fname, 0);
3246                 if (!head) {
3247                         fprintf(stderr,
3248                                 "%s setstripe: cannot read layout from '%s': %s\n",
3249                                 progname, fname, strerror(errno));
3250                         return -EINVAL;
3251                 } else if (errno == ENODATA) {
3252                         /*
3253                          * file without LOVEA, this component-add will be turned
3254                          * into a component-create.
3255                          */
3256                         llapi_layout_free(head);
3257                         ret = -ENODATA;
3258
3259                         /*
3260                          * the new layout will be added to an empty one, it
3261                          * still needs to be adjusted below
3262                          */
3263                         comp_add = 0;
3264                         break;
3265                 } else if (!llapi_layout_is_composite(head)) {
3266                         fprintf(stderr,
3267                                 "%s setstripe: '%s' not a composite file\n",
3268                                 progname, fname);
3269                         llapi_layout_free(head);
3270                         return -EINVAL;
3271                 }
3272
3273                 rc = llapi_layout_comp_extent_get(head, &start, &prev_end);
3274                 if (rc) {
3275                         fprintf(stderr,
3276                                 "%s setstripe: cannot get prev extent: %s\n",
3277                                 progname, strerror(errno));
3278                         llapi_layout_free(head);
3279                         return rc;
3280                 }
3281
3282                 llapi_layout_free(head);
3283                 break;
3284         }
3285
3286         /* Make sure we use the first component of the layout to be added. */
3287         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
3288         if (rc < 0) {
3289                 fprintf(stderr,
3290                         "%s setstripe: cannot move component cursor: %s\n",
3291                         progname, strerror(errno));
3292                 return rc;
3293         }
3294
3295         rc = llapi_layout_comp_extent_get(layout, &start, &end);
3296         if (rc) {
3297                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
3298                         progname, strerror(errno));
3299                 return rc;
3300         }
3301
3302         if (start == 0 && end == 0) {
3303                 rc = layout_extend_comp(layout, start, &end,
3304                                         comp_add ? prev_end : 0);
3305                 if (rc)
3306                         return rc;
3307         }
3308
3309         if (start > prev_end || end < prev_end) {
3310                 fprintf(stderr,
3311                         "%s setstripe: first extent [%lu, %lu) not adjacent with extent end %lu\n",
3312                         progname, start, end, prev_end);
3313                 return -EINVAL;
3314         }
3315
3316         rc = llapi_layout_comp_extent_set(layout, prev_end, end);
3317         if (rc) {
3318                 fprintf(stderr,
3319                         "%s setstripe: cannot set component extent [%lu, %lu): %s\n",
3320                         progname, prev_end, end, strerror(errno));
3321                 return rc;
3322         }
3323
3324         return ret;
3325 }
3326
3327 static int mirror_adjust_first_extents(struct mirror_args *list)
3328 {
3329         int rc = 0;
3330
3331         if (!list)
3332                 return 0;
3333
3334         while (list) {
3335                 rc = layout_adjust_first_extent(NULL, list->m_layout, false);
3336                 if (rc)
3337                         break;
3338                 list = list->m_next;
3339         }
3340
3341         return rc;
3342 }
3343
3344 static inline bool arg_is_eof(char *arg)
3345 {
3346         return !strncmp(arg, "-1", strlen("-1")) ||
3347                !strncmp(arg, "EOF", strlen("EOF")) ||
3348                !strncmp(arg, "eof", strlen("eof"));
3349 }
3350
3351 /**
3352  * lfs_mirror_alloc() - Allocate a mirror argument structure.
3353  *
3354  * Return: Valid mirror_args pointer on success and
3355  *         NULL if memory allocation fails.
3356  */
3357 static struct mirror_args *lfs_mirror_alloc(void)
3358 {
3359         struct mirror_args *mirror = NULL;
3360
3361         while (1) {
3362                 mirror = calloc(1, sizeof(*mirror));
3363                 if (mirror) {
3364                         mirror->m_inherit = false;
3365                         break;
3366                 }
3367
3368                 sleep(1);
3369         }
3370
3371         return mirror;
3372 }
3373
3374 /**
3375  * lfs_mirror_free() - Free memory allocated for a mirror argument
3376  *                     structure.
3377  * @mirror: Previously allocated mirror argument structure by
3378  *          lfs_mirror_alloc().
3379  *
3380  * Free memory allocated for @mirror.
3381  *
3382  * Return: void.
3383  */
3384 static void lfs_mirror_free(struct mirror_args *mirror)
3385 {
3386         if (mirror->m_layout)
3387                 llapi_layout_free(mirror->m_layout);
3388         free(mirror);
3389 }
3390
3391 /**
3392  * lfs_mirror_list_free() - Free memory allocated for a mirror list.
3393  * @mirror_list: Previously allocated mirror list.
3394  *
3395  * Free memory allocated for @mirror_list.
3396  *
3397  * Return: void.
3398  */
3399 static void lfs_mirror_list_free(struct mirror_args *mirror_list)
3400 {
3401         struct mirror_args *next_mirror = NULL;
3402
3403         while (mirror_list) {
3404                 next_mirror = mirror_list->m_next;
3405                 lfs_mirror_free(mirror_list);
3406                 mirror_list = next_mirror;
3407         }
3408 }
3409
3410 enum {
3411         LFS_POOL_OPT = 3,
3412         LFS_COMP_COUNT_OPT,
3413         LFS_COMP_START_OPT,
3414         LFS_COMP_FLAGS_OPT,
3415         LFS_COMP_DEL_OPT,
3416         LFS_COMP_SET_OPT,
3417         LFS_COMP_ADD_OPT,
3418         LFS_COMP_NO_VERIFY_OPT,
3419         LFS_PROJID_OPT,
3420         LFS_LAYOUT_FLAGS_OPT, /* used for mirror and foreign flags */
3421         LFS_MIRROR_ID_OPT,
3422         LFS_MIRROR_STATE_OPT,
3423         LFS_LAYOUT_COPY,
3424         LFS_MIRROR_INDEX_OPT,
3425         LFS_LAYOUT_FOREIGN_OPT,
3426         LFS_MODE_OPT,
3427         LFS_NEWERXY_OPT,
3428         LFS_INHERIT_RR_OPT,
3429         LFS_FIND_PERM,
3430 };
3431
3432 /* functions */
3433 static int lfs_setstripe_internal(int argc, char **argv,
3434                                   enum setstripe_origin opc)
3435 {
3436         struct lfs_setstripe_args        lsa = { 0 };
3437         struct llapi_stripe_param       *param = NULL;
3438         struct find_param                migrate_mdt_param = {
3439                 .fp_max_depth = -1,
3440                 .fp_mdt_index = -1,
3441         };
3442         char                            *fname;
3443         int                              result = 0;
3444         int                              result2 = 0;
3445         char                            *end;
3446         int                              c;
3447         int                              delete = 0;
3448         unsigned long long               size_units = 1;
3449         bool                             migrate_mode = false;
3450         bool                             migrate_mdt_mode = false;
3451         bool                             setstripe_mode = false;
3452         bool                             migration_block = false;
3453         __u64                            migration_flags = 0;
3454         __u32                            tgts[LOV_MAX_STRIPE_COUNT] = { 0 };
3455         int                              comp_del = 0, comp_set = 0;
3456         int                              comp_add = 0;
3457         __u32                            comp_id = 0;
3458         struct llapi_layout             *layout = NULL;
3459         struct llapi_layout             **lpp = &layout;
3460         bool                             mirror_mode = false;
3461         bool                             has_m_file = false;
3462         __u32                            mirror_count = 0;
3463         enum mirror_flags                mirror_flags = 0;
3464         struct mirror_args              *mirror_list = NULL;
3465         struct mirror_args              *new_mirror = NULL;
3466         struct mirror_args              *last_mirror = NULL;
3467         __u16                            mirror_id = 0;
3468         char                             cmd[PATH_MAX];
3469         bool from_yaml = false;
3470         bool from_copy = false;
3471         char *template = NULL;
3472         bool foreign_mode = false;
3473         char *xattr = NULL;
3474         uint32_t type = LU_FOREIGN_TYPE_NONE, flags = 0;
3475         char *mode_opt = NULL;
3476         mode_t previous_umask = 0;
3477         mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
3478
3479         struct option long_opts[] = {
3480 /* find { .val = '0',   .name = "null",         .has_arg = no_argument }, */
3481 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
3482         /* --block is only valid in migrate mode */
3483         { .val = 'b',   .name = "block",        .has_arg = no_argument },
3484 /* find { .val = 'B',   .name = "btime",        .has_arg = required_argument }*/
3485         { .val = LFS_COMP_ADD_OPT,
3486                         .name = "comp-add",     .has_arg = no_argument },
3487         { .val = LFS_COMP_ADD_OPT,
3488                         .name = "component-add", .has_arg = no_argument },
3489         { .val = LFS_COMP_DEL_OPT,
3490                         .name = "comp-del",     .has_arg = no_argument },
3491         { .val = LFS_COMP_DEL_OPT,
3492                         .name = "component-del", .has_arg = no_argument },
3493         { .val = LFS_COMP_FLAGS_OPT,
3494                         .name = "comp-flags",   .has_arg = required_argument },
3495         { .val = LFS_COMP_FLAGS_OPT,
3496                         .name = "component-flags",
3497                                                 .has_arg = required_argument },
3498         { .val = LFS_COMP_SET_OPT,
3499                         .name = "comp-set",     .has_arg = no_argument },
3500         { .val = LFS_COMP_SET_OPT,
3501                         .name = "component-set",
3502                                                 .has_arg = no_argument},
3503         { .val = LFS_COMP_NO_VERIFY_OPT,
3504                         .name = "no-verify",    .has_arg = no_argument},
3505         { .val = LFS_LAYOUT_FLAGS_OPT,
3506                         .name = "flags",        .has_arg = required_argument},
3507         { .val = LFS_LAYOUT_FOREIGN_OPT,
3508                         .name = "foreign",      .has_arg = optional_argument},
3509         { .val = LFS_MIRROR_ID_OPT,
3510                         .name = "mirror-id",    .has_arg = required_argument},
3511         { .val = LFS_MODE_OPT,
3512                         .name = "mode",         .has_arg = required_argument},
3513         { .val = LFS_LAYOUT_COPY,
3514                         .name = "copy",         .has_arg = required_argument},
3515         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument},
3516         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument},
3517         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument},
3518         { .val = 'C',   .name = "overstripe-count",
3519                                                 .has_arg = required_argument},
3520         { .val = 'd',   .name = "delete",       .has_arg = no_argument},
3521         { .val = 'd',   .name = "destroy",      .has_arg = no_argument},
3522         /* --non-direct is only valid in migrate mode */
3523         { .val = 'D',   .name = "non-direct",   .has_arg = no_argument },
3524         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument},
3525         { .val = 'E',   .name = "component-end",
3526                                                 .has_arg = required_argument},
3527         { .val = 'f',   .name = "file",         .has_arg = required_argument },
3528 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
3529 /* find { .val = 'g',   .name = "gid",          .has_arg = no_argument }, */
3530 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
3531         { .val = 'h',   .name = "help",         .has_arg = no_argument },
3532         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument},
3533         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument},
3534         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument},
3535         { .val = 'I',   .name = "comp-id",      .has_arg = required_argument},
3536         { .val = 'I',   .name = "component-id", .has_arg = required_argument},
3537 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
3538         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
3539         { .val = 'm',   .name = "mdt",          .has_arg = required_argument},
3540         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument},
3541         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument},
3542         /* --non-block is only valid in migrate mode */
3543         { .val = 'n',   .name = "non-block",    .has_arg = no_argument },
3544         { .val = 'N',   .name = "mirror-count", .has_arg = optional_argument},
3545         { .val = 'o',   .name = "ost",          .has_arg = required_argument },
3546 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
3547         { .val = 'o',   .name = "ost-list",     .has_arg = required_argument },
3548         { .val = 'o',   .name = "ost_list",     .has_arg = required_argument },
3549 #endif
3550         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
3551 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
3552 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
3553 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
3554 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
3555         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
3556         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
3557 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
3558 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
3559 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
3560 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
3561         /* --verbose is only valid in migrate mode */
3562         { .val = 'v',   .name = "verbose",      .has_arg = no_argument},
3563         { .val = 'x',   .name = "xattr",        .has_arg = required_argument },
3564 /* dirstripe { .val = 'X',.name = "max-inherit",.has_arg = required_argument }*/
3565         { .val = 'y',   .name = "yaml",         .has_arg = required_argument },
3566         { .val = 'z',   .name = "ext-size",     .has_arg = required_argument},
3567         { .val = 'z',   .name = "extension-size", .has_arg = required_argument},
3568         { .name = NULL } };
3569
3570         setstripe_args_init(&lsa);
3571
3572         migrate_mode = (opc == SO_MIGRATE);
3573         mirror_mode = (opc == SO_MIRROR_CREATE || opc == SO_MIRROR_EXTEND);
3574         setstripe_mode = (opc == SO_SETSTRIPE);
3575         if (opc == SO_MIRROR_DELETE) {
3576                 delete = 1;
3577                 mirror_flags = MF_DESTROY;
3578         }
3579
3580         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
3581         progname = cmd;
3582         while ((c = getopt_long(argc, argv,
3583                                 "bc:C:dDE:f:hH:i:I:m:N::no:p:L:s:S:vx:y:z:",
3584                                 long_opts, NULL)) >= 0) {
3585                 size_units = 1;
3586                 switch (c) {
3587                 case 0:
3588                         /* Long options. */
3589                         break;
3590                 case LFS_COMP_ADD_OPT:
3591                         comp_add = 1;
3592                         break;
3593                 case LFS_COMP_DEL_OPT:
3594                         comp_del = 1;
3595                         break;
3596                 case LFS_COMP_FLAGS_OPT:
3597                         result = comp_str2flags(optarg, &lsa.lsa_comp_flags,
3598                                                 &lsa.lsa_comp_neg_flags);
3599                         if (result != 0)
3600                                 goto usage_error;
3601                         if (mirror_mode && lsa.lsa_comp_neg_flags) {
3602                                 fprintf(stderr,
3603                                         "%s: inverted flags are not supported\n",
3604                                         progname);
3605                                 goto usage_error;
3606                         }
3607                         break;
3608                 case LFS_COMP_SET_OPT:
3609                         comp_set = 1;
3610                         break;
3611                 case LFS_COMP_NO_VERIFY_OPT:
3612                         mirror_flags |= MF_NO_VERIFY;
3613                         break;
3614                 case LFS_MIRROR_ID_OPT: {
3615                         unsigned long int id;
3616
3617                         errno = 0;
3618                         id = strtoul(optarg, &end, 0);
3619                         if (errno != 0 || *end != '\0' || id == 0 ||
3620                             id > UINT16_MAX) {
3621                                 fprintf(stderr,
3622                                         "%s %s: invalid mirror ID '%s'\n",
3623                                         progname, argv[0], optarg);
3624                                 goto usage_error;
3625                         }
3626
3627                         mirror_id = (__u16)id;
3628                         break;
3629                 }
3630                 case LFS_LAYOUT_FLAGS_OPT: {
3631                         uint32_t neg_flags;
3632
3633                         /* check for numeric flags (foreign and mirror cases) */
3634                         if (setstripe_mode && !mirror_mode && !last_mirror) {
3635                                 errno = 0;
3636                                 flags = strtoul(optarg, &end, 16);
3637                                 if (errno != 0 || *end != '\0' ||
3638                                     flags >= UINT32_MAX) {
3639                                         fprintf(stderr,
3640                                                 "%s %s: invalid hex flags '%s'\n",
3641                                                 progname, argv[0], optarg);
3642                                         return CMD_HELP;
3643                                 }
3644                                 if (!foreign_mode) {
3645                                         fprintf(stderr,
3646                                                 "%s %s: hex flags must be specified with --foreign option\n",
3647                                                 progname, argv[0]);
3648                                         return CMD_HELP;
3649                                 }
3650                                 break;
3651                         }
3652
3653                         if (!mirror_mode || !last_mirror) {
3654                                 fprintf(stderr,
3655                                         "error: %s: --flags must be specified with --mirror-count|-N option\n",
3656                                         progname);
3657                                 goto usage_error;
3658                         }
3659
3660                         result = comp_str2flags(optarg, &last_mirror->m_flags,
3661                                                 &neg_flags);
3662                         if (result != 0)
3663                                 goto usage_error;
3664
3665                         if (neg_flags) {
3666                                 fprintf(stderr,
3667                                         "%s: inverted flags are not supported\n",
3668                                         progname);
3669                                 result = -EINVAL;
3670                                 goto usage_error;
3671                         }
3672                         if (last_mirror->m_flags & ~LCME_USER_MIRROR_FLAGS) {
3673                                 fprintf(stderr,
3674                                         "%s: unsupported mirror flags: %s\n",
3675                                         progname, optarg);
3676                                 result = -EINVAL;
3677                                 goto error;
3678                         }
3679                         break;
3680                 }
3681                 case LFS_LAYOUT_FOREIGN_OPT:
3682                         if (optarg) {
3683                                 /* check pure numeric */
3684                                 type = strtoul(optarg, &end, 0);
3685                                 if (*end) {
3686                                         /* check name */
3687                                         type = check_foreign_type_name(optarg);
3688                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
3689                                                 fprintf(stderr,
3690                                                         "%s %s: unrecognized foreign type '%s'\n",
3691                                                         progname, argv[0],
3692                                                         optarg);
3693                                                 return CMD_HELP;
3694                                         }
3695                                 } else if (type >= UINT32_MAX) {
3696                                         fprintf(stderr,
3697                                                 "%s %s: invalid foreign type '%s'\n",
3698                                                 progname, argv[0], optarg);
3699                                         return CMD_HELP;
3700                                 }
3701                         }
3702                         foreign_mode = true;
3703                         break;
3704                 case LFS_MODE_OPT:
3705                         mode_opt = optarg;
3706                         if (mode_opt) {
3707                                 mode = strtoul(mode_opt, &end, 8);
3708                                 if (*end != '\0') {
3709                                         fprintf(stderr,
3710                                                 "%s %s: bad mode '%s'\n",
3711                                                 progname, argv[0], mode_opt);
3712                                         return CMD_HELP;
3713                                 }
3714                                 previous_umask = umask(0);
3715                         }
3716                         break;
3717                 case LFS_LAYOUT_COPY:
3718                         from_copy = true;
3719                         template = optarg;
3720                         break;
3721                 case 'b':
3722                         if (!migrate_mode) {
3723                                 fprintf(stderr,
3724                                         "%s %s: -b|--block valid only for migrate command\n",
3725                                         progname, argv[0]);
3726                                 goto usage_error;
3727                         }
3728                         migration_block = true;
3729                         break;
3730                 case 'C':
3731                         if (lsa.lsa_pattern == LLAPI_LAYOUT_MDT) {
3732                                 fprintf(stderr,
3733                                         "%s %s: -C|--overstripe-count incompatible with DoM layout\n",
3734                                         progname, argv[0]);
3735                                 goto usage_error;
3736                         }
3737                         lsa.lsa_pattern = LLAPI_LAYOUT_OVERSTRIPING;
3738                         /* fall through */
3739                 case 'c':
3740                         errno = 0;
3741                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
3742                         if (errno != 0 || *end != '\0'||
3743                             lsa.lsa_stripe_count < -1 ||
3744                             lsa.lsa_stripe_count > LOV_MAX_STRIPE_COUNT) {
3745                                 fprintf(stderr,
3746                                         "%s %s: invalid stripe count '%s'\n",
3747                                         progname, argv[0], optarg);
3748                                 goto usage_error;
3749                         }
3750
3751                         if (lsa.lsa_stripe_count == -1)
3752                                 lsa.lsa_stripe_count = LLAPI_LAYOUT_WIDE;
3753                         break;
3754                 case 'd':
3755                         /* delete the default striping pattern */
3756                         delete = 1;
3757                         if (opc == SO_MIRROR_SPLIT) {
3758                                 if (has_m_file) {
3759                                         fprintf(stderr,
3760                                               "%s %s: -d cannot used with -f\n",
3761                                                 progname, argv[0]);
3762                                         goto usage_error;
3763                                 }
3764                                 mirror_flags |= MF_DESTROY;
3765                         }
3766                         break;
3767                 case 'D':
3768                         if (!migrate_mode) {
3769                                 fprintf(stderr,
3770                                         "%s %s: -D|--non-direct is valid only for migrate command\n",
3771                                         progname, argv[0]);
3772                                 goto usage_error;
3773                         }
3774                         migration_flags |= MIGRATION_NONDIRECT;
3775                         break;
3776                 case 'E':
3777                         if (lsa.lsa_comp_end != 0) {
3778                                 result = comp_args_to_layout(lpp, &lsa, true);
3779                                 if (result) {
3780                                         fprintf(stderr, "%s: invalid layout\n",
3781                                                 progname);
3782                                         goto usage_error;
3783                                 }
3784
3785                                 setstripe_args_init_inherit(&lsa);
3786                         }
3787
3788                         if (arg_is_eof(optarg)) {
3789                                 lsa.lsa_comp_end = LUSTRE_EOF;
3790                         } else {
3791                                 result = llapi_parse_size(optarg,
3792                                                           &lsa.lsa_comp_end,
3793                                                           &size_units, 0);
3794                                 /* assume units of KB if too small */
3795                                 if (lsa.lsa_comp_end < 4096)
3796                                         lsa.lsa_comp_end *= 1024;
3797                                 if (result ||
3798                                     lsa.lsa_comp_end & (LOV_MIN_STRIPE_SIZE - 1)) {
3799                                         fprintf(stderr,
3800                                                 "%s %s: invalid component end '%s'\n",
3801                                                 progname, argv[0], optarg);
3802                                         goto usage_error;
3803                                 }
3804                         }
3805                         break;
3806                 case 'H':
3807                         if (!migrate_mode) {
3808                                 fprintf(stderr,
3809                                         "--mdt-hash is valid only for migrate command\n");
3810                                 return CMD_HELP;
3811                         }
3812
3813                         lsa.lsa_pattern = check_hashtype(optarg);
3814                         if (lsa.lsa_pattern == 0) {
3815                                 fprintf(stderr,
3816                                         "%s %s: bad stripe hash type '%s'\n",
3817                                         progname, argv[0], optarg);
3818                                 return CMD_HELP;
3819                         }
3820                         break;
3821                 case 'i':
3822                         errno = 0;
3823                         lsa.lsa_stripe_off = strtol(optarg, &end, 0);
3824                         if (errno != 0 || *end != '\0' ||
3825                             lsa.lsa_stripe_off < -1 ||
3826                             lsa.lsa_stripe_off > LOV_V1_INSANE_STRIPE_COUNT) {
3827                                 fprintf(stderr,
3828                                         "%s %s: invalid stripe offset '%s'\n",
3829                                         progname, argv[0], optarg);
3830                                 goto usage_error;
3831                         }
3832                         if (lsa.lsa_stripe_off == -1)
3833                                 lsa.lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
3834                         break;
3835                 case 'I':
3836                         comp_id = strtoul(optarg, &end, 0);
3837                         if (*end != '\0' || comp_id == 0 ||
3838                             comp_id > LCME_ID_MAX) {
3839                                 fprintf(stderr,
3840                                         "%s %s: invalid component ID '%s'\n",
3841                                         progname, argv[0], optarg);
3842                                 goto usage_error;
3843                         }
3844                         break;
3845                 case 'f':
3846                         if (opc != SO_MIRROR_EXTEND && opc != SO_MIRROR_SPLIT) {
3847                                 fprintf(stderr,
3848                                         "error: %s: invalid option: %s\n",
3849                                         progname, argv[optopt + 1]);
3850                                 goto usage_error;
3851                         }
3852                         if (opc == SO_MIRROR_EXTEND) {
3853                                 if (!last_mirror) {
3854                                         fprintf(stderr,
3855                                 "error: %s: '-N' must exist in front of '%s'\n",
3856                                                 progname, argv[optopt + 1]);
3857                                         goto usage_error;
3858                                 }
3859                                 last_mirror->m_file = optarg;
3860                                 last_mirror->m_count = 1;
3861                         } else {
3862                                 /* mirror split */
3863                                 if (!mirror_list)
3864                                         mirror_list = lfs_mirror_alloc();
3865                                 mirror_list->m_file = optarg;
3866                         }
3867                         has_m_file = true;
3868                         break;
3869                 case 'L':
3870                         if (strcmp(argv[optind - 1], "mdt") == 0) {
3871                                 /* Can be only the first component */
3872                                 if (layout) {
3873                                         result = -EINVAL;
3874                                         fprintf(stderr,
3875                                                 "error: 'mdt' layout can be only the first one\n");
3876                                         goto error;
3877                                 }
3878                                 if (lsa.lsa_comp_end > (1ULL << 30)) { /* 1Gb */
3879                                         result = -EFBIG;
3880                                         fprintf(stderr,
3881                                                 "error: 'mdt' layout size is too big\n");
3882                                         goto error;
3883                                 }
3884                                 lsa.lsa_pattern = LLAPI_LAYOUT_MDT;
3885                         } else if (strcmp(argv[optind - 1], "raid0") != 0) {
3886                                 result = -EINVAL;
3887                                 fprintf(stderr,
3888                                         "error: layout '%s' is unknown, supported layouts are: 'mdt', 'raid0'\n",
3889                                         argv[optind]);
3890                                 goto error;
3891                         }
3892                         break;
3893                 case 'm':
3894                         if (!migrate_mode) {
3895                                 fprintf(stderr,
3896                                         "%s %s: -m|--mdt-index is valid only for migrate command\n",
3897                                         progname, argv[0]);
3898                                 goto usage_error;
3899                         }
3900                         migrate_mdt_mode = true;
3901                         lsa.lsa_nr_tgts = parse_targets(tgts,
3902                                                 sizeof(tgts) / sizeof(__u32),
3903                                                 lsa.lsa_nr_tgts, optarg, NULL);
3904                         if (lsa.lsa_nr_tgts < 0) {
3905                                 fprintf(stderr,
3906                                         "%s: invalid MDT target(s) '%s'\n",
3907                                         progname, optarg);
3908                                 goto usage_error;
3909                         }
3910
3911                         lsa.lsa_tgts = tgts;
3912                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
3913                                 lsa.lsa_stripe_off = tgts[0];
3914                         break;
3915                 case 'n':
3916                         if (!migrate_mode) {
3917                                 fprintf(stderr,
3918                                         "%s %s: -n|--non-block valid only for migrate command\n",
3919                                         progname, argv[0]);
3920                                 goto usage_error;
3921                         }
3922                         migration_flags |= MIGRATION_NONBLOCK;
3923                         break;
3924                 case 'N':
3925                         if (opc == SO_SETSTRIPE) {
3926                                 opc = SO_MIRROR_CREATE;
3927                                 mirror_mode = true;
3928                         }
3929                         mirror_count = 1;
3930                         if (optarg) {
3931                                 errno = 0;
3932                                 mirror_count = strtoul(optarg, &end, 0);
3933                                 if (errno != 0 || *end != '\0' ||
3934                                     mirror_count == 0 ||
3935                                     mirror_count > LUSTRE_MIRROR_COUNT_MAX) {
3936                                         fprintf(stderr,
3937                                                 "error: %s: bad mirror count: %s\n",
3938                                                 progname, optarg);
3939                                         result = -EINVAL;
3940                                         goto error;
3941                                 }
3942                         }
3943
3944                         new_mirror = lfs_mirror_alloc();
3945                         new_mirror->m_count = mirror_count;
3946
3947                         if (!mirror_list)
3948                                 mirror_list = new_mirror;
3949
3950                         if (last_mirror) {
3951                                 /* wrap up last mirror */
3952                                 if (!setstripe_args_specified(&lsa))
3953                                         last_mirror->m_inherit = true;
3954                                 if (lsa.lsa_comp_end == 0)
3955                                         lsa.lsa_comp_end = LUSTRE_EOF;
3956
3957                                 result = comp_args_to_layout(lpp, &lsa, true);
3958                                 if (result) {
3959                                         lfs_mirror_free(new_mirror);
3960                                         goto error;
3961                                 }
3962
3963                                 setstripe_args_init_inherit(&lsa);
3964
3965                                 last_mirror->m_next = new_mirror;
3966                         }
3967
3968                         last_mirror = new_mirror;
3969                         lpp = &last_mirror->m_layout;
3970                         break;
3971                 case 'o':
3972 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
3973                         if (strcmp(argv[optind - 1], "--ost-list") == 0)
3974                                 fprintf(stderr,
3975                                         "warning: '--ost-list' is deprecated, use '--ost' instead\n");
3976 #endif
3977                         if (lsa.lsa_pattern == LLAPI_LAYOUT_MDT) {
3978                                 fprintf(stderr,
3979                                         "%s %s: -o|--ost incompatible with DoM layout\n",
3980                                         progname, argv[0]);
3981                                 goto usage_error;
3982                         }
3983                         /*
3984                          * -o allows overstriping, and must note it because
3985                          * parse_targets is shared with MDT striping, which
3986                          * does not allow duplicates
3987                          */
3988                         lsa.lsa_pattern = LLAPI_LAYOUT_OVERSTRIPING;
3989                         lsa.lsa_nr_tgts = parse_targets(tgts,
3990                                                 sizeof(tgts) / sizeof(__u32),
3991                                                 lsa.lsa_nr_tgts, optarg,
3992                                                 &lsa.lsa_pattern);
3993                         if (lsa.lsa_nr_tgts < 0) {
3994                                 fprintf(stderr,
3995                                         "%s %s: invalid OST target(s) '%s'\n",
3996                                         progname, argv[0], optarg);
3997                                 goto usage_error;
3998                         }
3999
4000                         lsa.lsa_tgts = tgts;
4001                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
4002                                 lsa.lsa_stripe_off = tgts[0];
4003                         break;
4004                 case 'p':
4005                         if (!optarg)
4006                                 goto usage_error;
4007                         lsa.lsa_pool_name = optarg;
4008
4009                         if (strlen(lsa.lsa_pool_name) == 0 ||
4010                             strncmp(lsa.lsa_pool_name, "none",
4011                                     LOV_MAXPOOLNAME) == 0)
4012                                 lsa.lsa_pool_name = NULL;
4013                         break;
4014                 case 'S':
4015                         result = llapi_parse_size(optarg, &lsa.lsa_stripe_size,
4016                                                   &size_units, 0);
4017                         /* assume units of KB if too small to be valid */
4018                         if (lsa.lsa_stripe_size < 4096)
4019                                 lsa.lsa_stripe_size *= 1024;
4020                         if (result ||
4021                             lsa.lsa_stripe_size & (LOV_MIN_STRIPE_SIZE - 1)) {
4022                                 fprintf(stderr,
4023                                         "%s %s: invalid stripe size '%s'\n",
4024                                         progname, argv[0], optarg);
4025                                 goto usage_error;
4026                         }
4027                         break;
4028                 case 'v':
4029                         if (!migrate_mode) {
4030                                 fprintf(stderr,
4031                                         "%s %s: -v|--verbose valid only for migrate command\n",
4032                                         progname, argv[0]);
4033                                 goto usage_error;
4034                         }
4035                         migrate_mdt_param.fp_verbose = VERBOSE_DETAIL;
4036                         migration_flags = MIGRATION_VERBOSE;
4037                         break;
4038                 case 'x':
4039                         xattr = optarg;
4040                         break;
4041                 case 'y':
4042                         from_yaml = true;
4043                         template = optarg;
4044                         break;
4045                 case 'z':
4046                         result = llapi_parse_size(optarg,
4047                                                   &lsa.lsa_extension_size,
4048                                                   &size_units, 0);
4049                         if (result) {
4050                                 fprintf(stderr,
4051                                         "%s %s: invalid extension size '%s'\n",
4052                                         progname, argv[0], optarg);
4053                                 goto usage_error;
4054                         }
4055
4056                         lsa.lsa_extension_comp = true;
4057                         break;
4058                 default:
4059                         fprintf(stderr, "%s: unrecognized option '%s'\n",
4060                                 progname, argv[optind - 1]);
4061                 case 'h':
4062                         goto usage_error;
4063                 }
4064         }
4065
4066         fname = argv[optind];
4067
4068         if (optind == argc) {
4069                 fprintf(stderr, "%s %s: FILE must be specified\n",
4070                         progname, argv[0]);
4071                 goto usage_error;
4072         }
4073
4074         /* lfs migrate $filename should keep the file's layout by default */
4075         if (migrate_mode && !setstripe_args_specified(&lsa) && !layout &&
4076             !from_yaml)
4077                 from_copy = true;
4078
4079         if (xattr && !foreign_mode) {
4080                 /*
4081                  * only print a warning as this is harmless and will be ignored
4082                  */
4083                 fprintf(stderr,
4084                         "%s %s: xattr has been specified for non-foreign layout\n",
4085                         progname, argv[0]);
4086         } else if (foreign_mode && !xattr) {
4087                 fprintf(stderr,
4088                         "%s %s: xattr must be provided in foreign mode\n",
4089                         progname, argv[0]);
4090                 goto usage_error;
4091         }
4092
4093         if (foreign_mode && (!setstripe_mode || comp_add | comp_del ||
4094             comp_set || comp_id || delete || from_copy ||
4095             setstripe_args_specified(&lsa) || lsa.lsa_nr_tgts ||
4096             lsa.lsa_tgts)) {
4097                 fprintf(stderr,
4098                         "%s %s: only --xattr/--flags/--mode options are valid with --foreign\n",
4099                         progname, argv[0]);
4100                 return CMD_HELP;
4101         }
4102
4103         if (mirror_mode && mirror_count == 0) {
4104                 fprintf(stderr,
4105                         "error: %s: --mirror-count|-N option is required\n",
4106                         progname);
4107                 result = -EINVAL;
4108                 goto error;
4109         }
4110
4111         if (mirror_mode) {
4112                 if (!setstripe_args_specified(&lsa))
4113                         last_mirror->m_inherit = true;
4114                 if (lsa.lsa_comp_end == 0)
4115                         lsa.lsa_comp_end = LUSTRE_EOF;
4116         }
4117
4118         if (lsa.lsa_comp_end != 0) {
4119                 result = comp_args_to_layout(lpp, &lsa, true);
4120                 if (result) {
4121                         fprintf(stderr, "error: %s: invalid layout\n",
4122                                 progname);
4123                         result = -EINVAL;
4124                         goto error;
4125                 }
4126         }
4127
4128         if (mirror_flags & MF_NO_VERIFY) {
4129                 if (opc != SO_MIRROR_EXTEND) {
4130                         fprintf(stderr,
4131                                 "error: %s: --no-verify is valid only for lfs mirror extend command\n",
4132                                 progname);
4133                         result = -EINVAL;
4134                         goto error;
4135                 } else if (!has_m_file) {
4136                         fprintf(stderr,
4137                                 "error: %s: --no-verify must be specified with -f <victim_file> option\n",
4138                                 progname);
4139                         result = -EINVAL;
4140                         goto error;
4141                 }
4142         }
4143
4144         if (comp_set && !comp_id && !lsa.lsa_pool_name) {
4145                 fprintf(stderr,
4146                         "%s %s: --component-set doesn't have component-id set\n",
4147                         progname, argv[0]);
4148                 goto usage_error;
4149         }
4150
4151         if ((delete + comp_set + comp_del + comp_add) > 1) {
4152                 fprintf(stderr,
4153                         "%s %s: options --component-set, --component-del, --component-add and -d are mutually exclusive\n",
4154                         progname, argv[0]);
4155                 goto usage_error;
4156         }
4157
4158         if (delete && (setstripe_args_specified(&lsa) || comp_id != 0 ||
4159                        lsa.lsa_comp_flags != 0 || layout != NULL)) {
4160                 fprintf(stderr,
4161                         "%s %s: option -d is mutually exclusive with -s, -c, -o, -p, -I, -F and -E options\n",
4162                         progname, argv[0]);
4163                 goto usage_error;
4164         }
4165
4166         if ((comp_set || comp_del) &&
4167             (setstripe_args_specified(&lsa) || layout != NULL)) {
4168                 fprintf(stderr,
4169                         "%s %s: options --component-del and --component-set are mutually exclusive when used with -c, -E, -o, -p, or -s\n",
4170                         progname, argv[0]);
4171                 goto usage_error;
4172         }
4173
4174         if (comp_del && comp_id != 0 && lsa.lsa_comp_flags != 0) {
4175                 fprintf(stderr,
4176                         "%s %s: options -I and -F are mutually exclusive when used with --component-del\n",
4177                         progname, argv[0]);
4178                 goto usage_error;
4179         }
4180
4181         if (comp_add || comp_del) {
4182                 struct stat st;
4183
4184                 result = lstat(fname, &st);
4185                 if (result == 0 && S_ISDIR(st.st_mode)) {
4186                         fprintf(stderr,
4187                                 "%s setstripe: cannot use --component-add or --component-del for directory\n",
4188                                 progname);
4189                         goto usage_error;
4190                 }
4191
4192                 if (mirror_mode) {
4193                         fprintf(stderr,
4194                                 "error: %s: can't use --component-add or --component-del for mirror operation\n",
4195                                 progname);
4196                         goto usage_error;
4197                 }
4198         }
4199
4200         if (comp_add) {
4201                 if (!layout) {
4202                         fprintf(stderr,
4203                                 "%s %s: option -E must be specified with --component-add\n",
4204                                 progname, argv[0]);
4205                         goto usage_error;
4206                 }
4207         }
4208
4209         if (from_yaml && from_copy) {
4210                 fprintf(stderr,
4211                         "%s: can't specify --yaml and --copy together\n",
4212                         progname);
4213                 goto error;
4214         }
4215
4216         if ((from_yaml || from_copy) &&
4217             (setstripe_args_specified(&lsa) || layout != NULL)) {
4218                 fprintf(stderr,
4219                         "error: %s: can't specify --yaml or --copy with -c, -S, -i, -o, -p or -E options.\n",
4220                         argv[0]);
4221                 goto error;
4222         }
4223
4224         if ((migration_flags & MIGRATION_NONBLOCK) && migration_block) {
4225                 fprintf(stderr,
4226                         "%s %s: options --non-block and --block are mutually exclusive\n",
4227                         progname, argv[0]);
4228                 goto usage_error;
4229         }
4230
4231         if (!comp_del && !comp_set && opc != SO_MIRROR_SPLIT &&
4232             opc != SO_MIRROR_DELETE && comp_id != 0) {
4233                 fprintf(stderr,
4234                         "%s: option -I can only be used with --component-del or --component-set or lfs mirror split\n",
4235                         progname);
4236                 goto usage_error;
4237         }
4238
4239         if (migrate_mdt_mode) {
4240                 struct lmv_user_md *lmu;
4241
4242                 /* initialize migrate mdt parameters */
4243                 lmu = calloc(1, lmv_user_md_size(lsa.lsa_nr_tgts,
4244                                                  LMV_USER_MAGIC_SPECIFIC));
4245                 if (!lmu) {
4246                         fprintf(stderr,
4247                                 "%s %s: cannot allocate memory for lmv_user_md: %s\n",
4248                                 progname, argv[0], strerror(ENOMEM));
4249                         result = -ENOMEM;
4250                         goto error;
4251                 }
4252                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
4253                         lmu->lum_stripe_count = lsa.lsa_stripe_count;
4254                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT) {
4255                         fprintf(stderr,
4256                                 "%s %s: migrate should specify MDT index\n",
4257                                 progname, argv[0]);
4258                         free(lmu);
4259                         goto usage_error;
4260                 }
4261                 lmu->lum_stripe_offset = lsa.lsa_stripe_off;
4262                 if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
4263                         lmu->lum_hash_type = lsa.lsa_pattern;
4264                 else
4265                         lmu->lum_hash_type = LMV_HASH_TYPE_UNKNOWN;
4266                 if (lsa.lsa_pool_name) {
4267                         strncpy(lmu->lum_pool_name, lsa.lsa_pool_name,
4268                                 sizeof(lmu->lum_pool_name) - 1);
4269                         lmu->lum_pool_name[sizeof(lmu->lum_pool_name) - 1] = 0;
4270                 }
4271                 if (lsa.lsa_nr_tgts > 1) {
4272                         int i;
4273
4274                         if (lsa.lsa_stripe_count > 0 &&
4275                             lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
4276                             lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
4277                                 fprintf(stderr,
4278                                         "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
4279                                         progname, lsa.lsa_stripe_count,
4280                                         lsa.lsa_nr_tgts);
4281                                 free(lmu);
4282                                 goto usage_error;
4283                         }
4284
4285                         lmu->lum_magic = LMV_USER_MAGIC_SPECIFIC;
4286                         lmu->lum_stripe_count = lsa.lsa_nr_tgts;
4287                         for (i = 0; i < lsa.lsa_nr_tgts; i++)
4288                                 lmu->lum_objects[i].lum_mds = lsa.lsa_tgts[i];
4289                 } else {
4290                         lmu->lum_magic = LMV_USER_MAGIC;
4291                 }
4292
4293                 migrate_mdt_param.fp_lmv_md = lmu;
4294                 migrate_mdt_param.fp_migrate = 1;
4295         } else if (!layout) {
4296                 if (lsa_args_stripe_count_check(&lsa))
4297                         goto usage_error;
4298
4299                 /* initialize stripe parameters */
4300                 param = calloc(1, offsetof(typeof(*param),
4301                                lsp_osts[lsa.lsa_nr_tgts]));
4302                 if (!param) {
4303                         fprintf(stderr,
4304                                 "%s %s: cannot allocate memory for parameters: %s\n",
4305                                 progname, argv[0], strerror(ENOMEM));
4306                         result = -ENOMEM;
4307                         goto error;
4308                 }
4309
4310                 if (lsa.lsa_stripe_size != LLAPI_LAYOUT_DEFAULT)
4311                         param->lsp_stripe_size = lsa.lsa_stripe_size;
4312                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
4313                         if (lsa.lsa_stripe_count == LLAPI_LAYOUT_WIDE)
4314                                 param->lsp_stripe_count = -1;
4315                         else
4316                                 param->lsp_stripe_count = lsa.lsa_stripe_count;
4317                 }
4318                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
4319                         param->lsp_stripe_offset = -1;
4320                 else
4321                         param->lsp_stripe_offset = lsa.lsa_stripe_off;
4322                 param->lsp_stripe_pattern =
4323                                 llapi_pattern_to_lov(lsa.lsa_pattern);
4324                 if (param->lsp_stripe_pattern == EINVAL) {
4325                         fprintf(stderr, "error: %s: invalid stripe pattern\n",
4326                                 argv[0]);
4327                         free(param);
4328                         goto usage_error;
4329                 }
4330                 param->lsp_pool = lsa.lsa_pool_name;
4331                 param->lsp_is_specific = false;
4332
4333                 if (lsa.lsa_nr_tgts > 0) {
4334                         param->lsp_is_specific = true;
4335                         param->lsp_stripe_count = lsa.lsa_nr_tgts;
4336                         memcpy(param->lsp_osts, tgts,
4337                                sizeof(*tgts) * lsa.lsa_nr_tgts);
4338                 }
4339         }
4340
4341         if (from_yaml) {
4342                 /* generate a layout from a YAML template */
4343                 result = lfs_comp_create_from_yaml(template, &layout,
4344                                                    &lsa, tgts);
4345                 if (result) {
4346                         fprintf(stderr,
4347                                 "error: %s: can't create composite layout from template file %s\n",
4348                                 argv[0], template);
4349                         goto error;
4350                 }
4351         }
4352
4353         if (layout != NULL || mirror_list != NULL) {
4354                 if (mirror_list)
4355                         result = mirror_adjust_first_extents(mirror_list);
4356                 else
4357                         result = layout_adjust_first_extent(fname, layout,
4358                                                             comp_add);
4359                 if (result == -ENODATA)
4360                         comp_add = 0;
4361                 else if (result != 0) {
4362                         fprintf(stderr, "error: %s: invalid layout\n",
4363                                 progname);
4364                         goto error;
4365                 }
4366         }
4367
4368         for (fname = argv[optind]; fname != NULL; fname = argv[++optind]) {
4369                 if (from_copy) {
4370                         layout = llapi_layout_get_by_path(template ?: fname, 0);
4371                         if (!layout) {
4372                                 fprintf(stderr,
4373                                         "%s: can't create composite layout from file %s: %s\n",
4374                                         progname, template ?: fname,
4375                                         strerror(errno));
4376                                 result = -errno;
4377                                 goto error;
4378                         }
4379                 }
4380
4381                 if (migrate_mdt_mode) {
4382                         result = llapi_migrate_mdt(fname, &migrate_mdt_param);
4383                 } else if (migrate_mode) {
4384                         result = lfs_migrate(fname, migration_flags, param,
4385                                              layout);
4386                 } else if (comp_set != 0) {
4387                         result = lfs_component_set(fname, comp_id,
4388                                                    lsa.lsa_pool_name,
4389                                                    lsa.lsa_comp_flags,
4390                                                    lsa.lsa_comp_neg_flags);
4391                 } else if (comp_del != 0) {
4392                         result = lfs_component_del(fname, comp_id,
4393                                                    lsa.lsa_comp_flags,
4394                                                    lsa.lsa_comp_neg_flags);
4395                 } else if (comp_add != 0) {
4396                         result = lfs_component_add(fname, layout);
4397                 } else if (opc == SO_MIRROR_CREATE) {
4398                         result = mirror_create(fname, mirror_list);
4399                 } else if (opc == SO_MIRROR_EXTEND) {
4400                         result = mirror_extend(fname, mirror_list,
4401                                                mirror_flags);
4402                 } else if (opc == SO_MIRROR_SPLIT || opc == SO_MIRROR_DELETE) {
4403                         if (!mirror_id && !comp_id && !lsa.lsa_pool_name) {
4404                                 fprintf(stderr,
4405                                         "%s: no mirror id, component id, or pool name specified to delete from '%s'\n",
4406                                         progname, fname);
4407                                 goto usage_error;
4408                         }
4409                         if (lsa.lsa_pool_name)
4410                                 mirror_flags |= MF_COMP_POOL;
4411                         else if (mirror_id != 0)
4412                                 comp_id = mirror_id;
4413                         else
4414                                 mirror_flags |= MF_COMP_ID;
4415                         if (has_m_file && !strcmp(fname, mirror_list->m_file)) {
4416                                 fprintf(stderr,
4417                                         "%s: the file specified by -f cannot be same as the source file '%s'\n",
4418                                         progname, fname);
4419                                 goto usage_error;
4420                         }
4421                         result = mirror_split(fname, comp_id, lsa.lsa_pool_name,
4422                                               mirror_flags,
4423                                               has_m_file ? mirror_list->m_file :
4424                                               NULL);
4425                 } else if (layout) {
4426                         result = lfs_component_create(fname, O_CREAT | O_WRONLY,
4427                                                       mode, layout);
4428                         if (result >= 0) {
4429                                 close(result);
4430                                 result = 0;
4431                         }
4432                 } else if (foreign_mode) {
4433                         result = llapi_file_create_foreign(fname, mode, type,
4434                                                            flags, xattr);
4435                         if (result >= 0) {
4436                                 close(result);
4437                                 result = 0;
4438                         }
4439                 } else {
4440                         result = llapi_file_open_param(fname,
4441                                                        O_CREAT | O_WRONLY,
4442                                                        mode, param);
4443                         if (result >= 0) {
4444                                 close(result);
4445                                 result = 0;
4446                         }
4447                 }
4448                 if (result) {
4449                         /* Save the first error encountered. */
4450                         if (result2 == 0)
4451                                 result2 = result;
4452                         continue;
4453                 }
4454         }
4455
4456         if (mode_opt)
4457                 umask(previous_umask);
4458
4459         free(param);
4460         free(migrate_mdt_param.fp_lmv_md);
4461         llapi_layout_free(layout);
4462         lfs_mirror_list_free(mirror_list);
4463         return result2;
4464 usage_error:
4465         result = CMD_HELP;
4466 error:
4467         llapi_layout_free(layout);
4468         lfs_mirror_list_free(mirror_list);
4469         return result;
4470 }
4471
4472 static int lfs_poollist(int argc, char **argv)
4473 {
4474         if (argc != 2)
4475                 return CMD_HELP;
4476
4477         return llapi_poollist(argv[1]);
4478 }
4479
4480 #define FP_DEFAULT_TIME_MARGIN (24 * 60 * 60)
4481 static time_t set_time(struct find_param *param, time_t *time, time_t *set,
4482                        char *str)
4483 {
4484         long long t = 0;
4485         int sign = 0;
4486         char *endptr = "AD";
4487         char *timebuf;
4488
4489         if (str[0] == '+')
4490                 sign = 1;
4491         else if (str[0] == '-')
4492                 sign = -1;
4493
4494         if (sign)
4495                 str++;
4496
4497         for (timebuf = str; *endptr && *(endptr + 1); timebuf = endptr + 1) {
4498                 long long val = strtoll(timebuf, &endptr, 0);
4499                 int unit = 1;
4500
4501                 switch (*endptr) {
4502                 case  'y':
4503                         unit *= 52; /* 52 weeks + 1 day below */
4504                 case  'w':      /* fallthrough */
4505                         unit *= 7;
4506                         if (param->fp_time_margin == FP_DEFAULT_TIME_MARGIN)
4507                                 param->fp_time_margin *= (1 + unit / 52);
4508                         unit += (*endptr == 'y'); /* +1 day for 365 days/year */
4509                 case '\0': /* days are default unit if none used */
4510                 case  'd':      /* fallthrough */
4511                         unit *= 24;
4512                 case  'h':      /* fallthrough */
4513                         unit *= 60;
4514                 case  'm':      /* fallthrough */
4515                         unit *= 60;
4516                 case  's':      /* fallthrough */
4517                         break;
4518                         /* don't need to multiply by 1 for seconds */
4519                 default:
4520                         fprintf(stderr,
4521                                 "%s find: bad time string '%s': %s\n",
4522                                 progname, timebuf, strerror(EINVAL));
4523                         return LONG_MAX;
4524                 }
4525
4526                 if (param->fp_time_margin == 0 ||
4527                     (*endptr && unit < param->fp_time_margin))
4528                         param->fp_time_margin = unit;
4529
4530                 t += val * unit;
4531         }
4532         if (*time < t) {
4533                 if (sign != 0)
4534                         str--;
4535                 fprintf(stderr, "%s find: bad time '%s': too large\n",
4536                         progname, str);
4537                 return LONG_MAX;
4538         }
4539
4540         *set = *time - t;
4541
4542         return sign;
4543 }
4544
4545 static int str2quotaid(__u32 *id, const char *arg)
4546 {
4547         unsigned long int projid_tmp = 0;
4548         char *endptr = NULL;
4549
4550         projid_tmp = strtoul(arg, &endptr, 10);
4551         if (*endptr != '\0')
4552                 return -EINVAL;
4553         if (projid_tmp >= UINT32_MAX)
4554                 return -ERANGE;
4555
4556         *id = projid_tmp;
4557         return 0;
4558 }
4559
4560 static int name2uid(unsigned int *id, const char *name)
4561 {
4562         struct passwd *passwd;
4563
4564         passwd = getpwnam(name);
4565         if (!passwd)
4566                 return -ENOENT;
4567         *id = passwd->pw_uid;
4568
4569         return 0;
4570 }
4571
4572 static int name2gid(unsigned int *id, const char *name)
4573 {
4574         struct group *group;
4575
4576         group = getgrnam(name);
4577         if (!group)
4578                 return -ENOENT;
4579         *id = group->gr_gid;
4580
4581         return 0;
4582 }
4583
4584 static inline int name2projid(unsigned int *id, const char *name)
4585 {
4586         return -ENOTSUP;
4587 }
4588
4589 static int uid2name(char **name, unsigned int id)
4590 {
4591         struct passwd *passwd;
4592
4593         passwd = getpwuid(id);
4594         if (!passwd)
4595                 return -ENOENT;
4596         *name = passwd->pw_name;
4597
4598         return 0;
4599 }
4600
4601 static inline int gid2name(char **name, unsigned int id)
4602 {
4603         struct group *group;
4604
4605         group = getgrgid(id);
4606         if (!group)
4607                 return -ENOENT;
4608         *name = group->gr_name;
4609
4610         return 0;
4611 }
4612
4613 static int name2layout(__u32 *layout, char *name)
4614 {
4615         char *ptr, *layout_name;
4616
4617         *layout = 0;
4618         for (ptr = name; ; ptr = NULL) {
4619                 layout_name = strtok(ptr, ",");
4620                 if (!layout_name)
4621                         break;
4622                 if (strcmp(layout_name, "released") == 0)
4623                         *layout |= LOV_PATTERN_F_RELEASED;
4624                 else if (strcmp(layout_name, "raid0") == 0)
4625                         *layout |= LOV_PATTERN_RAID0;
4626                 else if (strcmp(layout_name, "mdt") == 0)
4627                         *layout |= LOV_PATTERN_MDT;
4628                 else if (strcmp(layout_name, "overstriping") == 0)
4629                         *layout |= LOV_PATTERN_OVERSTRIPING;
4630                 else
4631                         return -1;
4632         }
4633         return 0;
4634 }
4635
4636 static int parse_symbolic(const char *input, mode_t *outmode, const char **end)
4637 {
4638         int loop;
4639         int user, group, other;
4640         int who, all;
4641         char c, op;
4642         mode_t perm;
4643         mode_t usermask;
4644         mode_t previous_flags;
4645
4646         user = group = other = 0;
4647         all = 0;
4648         loop = 1;
4649         perm = 0;
4650         previous_flags = 0;
4651         *end = input;
4652         usermask = 0;
4653
4654         while (loop) {
4655                 switch (*input) {
4656                 case 'u':
4657                         user = 1;
4658                         break;
4659                 case 'g':
4660                         group = 1;
4661                         break;
4662                 case 'o':
4663                         other = 1;
4664                         break;
4665                 case 'a':
4666                         user = group = other = 1;
4667                         all = 1;
4668                         break;
4669                 default:
4670                         loop = 0;
4671                 }
4672
4673                 if (loop)
4674                         input++;
4675         }
4676
4677         who = user || group || other;
4678         if (!who) {
4679                 /* get the umask */
4680                 usermask = umask(0022);
4681                 umask(usermask);
4682                 usermask &= 07777;
4683         }
4684
4685         if (*input == '-' || *input == '+' || *input == '=')
4686                 op = *input++;
4687         else
4688                 /* operation is required */
4689                 return -1;
4690
4691         /* get the flags in *outmode */
4692         switch (*input) {
4693         case 'u':
4694                 previous_flags = (*outmode & 0700);
4695                 perm |= user  ? previous_flags : 0;
4696                 perm |= group ? (previous_flags >> 3) : 0;
4697                 perm |= other ? (previous_flags >> 6) : 0;
4698                 input++;
4699                 goto write_perm;
4700         case 'g':
4701                 previous_flags = (*outmode & 0070);
4702                 perm |= user  ? (previous_flags << 3) : 0;
4703                 perm |= group ? previous_flags : 0;
4704                 perm |= other ? (previous_flags >> 3) : 0;
4705                 input++;
4706                 goto write_perm;
4707         case 'o':
4708                 previous_flags = (*outmode & 0007);
4709                 perm |= user  ? (previous_flags << 6) : 0;
4710                 perm |= group ? (previous_flags << 3) : 0;
4711                 perm |= other ? previous_flags : 0;
4712                 input++;
4713                 goto write_perm;
4714         default:
4715                 break;
4716         }
4717
4718         /* this part is optional,
4719          * if empty perm = 0 and *outmode is not modified
4720          */
4721         loop = 1;
4722         while (loop) {
4723                 c = *input;
4724                 switch (c) {
4725                 case 'r':
4726                         perm |= user  ? 0400 : 0;
4727                         perm |= group ? 0040 : 0;
4728                         perm |= other ? 0004 : 0;
4729                         /* set read permission for uog except for umask's
4730                          * permissions
4731                          */
4732                         perm |= who   ? 0 : (0444 & ~usermask);
4733                         break;
4734                 case 'w':
4735                         perm |= user  ? 0200 : 0;
4736                         perm |= group ? 0020 : 0;
4737                         perm |= other ? 0002 : 0;
4738                         /* set write permission for uog except for umask'
4739                          * permissions
4740                          */
4741                         perm |= who   ? 0 : (0222 & ~usermask);
4742                         break;
4743                 case 'x':
4744                         perm |= user  ? 0100 : 0;
4745                         perm |= group ? 0010 : 0;
4746                         perm |= other ? 0001 : 0;
4747                         /* set execute permission for uog except for umask'
4748                          * permissions
4749                          */
4750                         perm |= who   ? 0 : (0111 & ~usermask);
4751                         break;
4752                 case 'X':
4753                         /*
4754                          * Adds execute permission to 'u', 'g' and/or 'g' if
4755                          * specified and either 'u', 'g' or 'o' already has
4756                          * execute permissions.
4757                          */
4758                         if ((*outmode & 0111) != 0) {
4759                                 perm |= user  ? 0100 : 0;
4760                                 perm |= group ? 0010 : 0;
4761                                 perm |= other ? 0001 : 0;
4762                                 perm |= !who  ? 0111 : 0;
4763                         }
4764                         break;
4765                 case 's':
4766                         /* s is ignored if o is given, but it's not an error */
4767                         if (other && !group && !user)
4768                                 break;
4769                         perm |= user  ? S_ISUID : 0;
4770                         perm |= group ? S_ISGID : 0;
4771                         break;
4772                 case 't':
4773                         /* 't' should be used when 'a' is given
4774                          * or who is empty
4775                          */
4776                         perm |= (!who || all) ? S_ISVTX : 0;
4777                         /* using ugo with t is not an error */
4778                         break;
4779                 default:
4780                         loop = 0;
4781                         break;
4782                 }
4783                 if (loop)
4784                         input++;
4785         }
4786
4787 write_perm:
4788         /* uog flags should be only one character long */
4789         if (previous_flags && (*input != '\0' && *input != ','))
4790                 return -1;
4791
4792         switch (op) {
4793         case '-':
4794                 /* remove the flags from outmode */
4795                 *outmode &= ~perm;
4796                 break;
4797         case '+':
4798                 /* add the flags to outmode */
4799                 *outmode |= perm;
4800                 break;
4801         case '=':
4802                 /* set the flags of outmode to perm */
4803                 if (perm != 0)
4804                         *outmode = perm;
4805                 break;
4806         }
4807
4808         *end = input;
4809         return 0;
4810 }
4811
4812 static int str2mode_t(const char *input, mode_t *outmode)
4813 {
4814         int ret;
4815         const char *iter;
4816
4817         ret = 0;
4818
4819         if (*input >= '0' && *input <= '7') {
4820                 /* parse octal representation */
4821                 char *end;
4822
4823                 iter = input;
4824
4825                 /* look for invalid digits in octal representation */
4826                 while (isdigit(*iter))
4827                         if (*iter++ > '7')
4828                                 return -1;
4829
4830                 errno = 0;
4831                 *outmode = strtoul(input, &end, 8);
4832
4833                 if (errno != 0 || *outmode > 07777) {
4834                         *outmode = 0;
4835                         ret = -1;
4836                 }
4837
4838         } else if (*input == '8' || *input == '9') {
4839                 /* error: invalid octal number */
4840                 ret = -1;
4841         } else {
4842                 /* parse coma seperated list of symbolic representation */
4843                 int rc;
4844                 const char *end;
4845
4846                 *outmode = 0;
4847                 rc = 0;
4848                 end = NULL;
4849
4850                 do {
4851                         rc = parse_symbolic(input, outmode, &end);
4852                         if (rc)
4853                                 return -1;
4854
4855                         input = end+1;
4856                 } while (*end == ',');
4857
4858                 if (*end != '\0')
4859                         ret = -1;
4860         }
4861         return ret;
4862 }
4863
4864 static int lfs_find(int argc, char **argv)
4865 {
4866         int c, rc;
4867         int ret = 0;
4868         time_t t;
4869         struct find_param param = {
4870                 .fp_max_depth = -1,
4871                 .fp_quiet = 1,
4872                 .fp_time_margin = FP_DEFAULT_TIME_MARGIN,
4873         };
4874         struct option long_opts[] = {
4875         { .val = 'A',   .name = "atime",        .has_arg = required_argument },
4876         { .val = 'b',   .name = "blocks",       .has_arg = required_argument },
4877         { .val = 'B',   .name = "btime",        .has_arg = required_argument },
4878         { .val = 'B',   .name = "Btime",        .has_arg = required_argument },
4879         { .val = LFS_COMP_COUNT_OPT,
4880                         .name = "comp-count",   .has_arg = required_argument },
4881         { .val = LFS_COMP_COUNT_OPT,
4882                         .name = "component-count",
4883                                                 .has_arg = required_argument },
4884         { .val = LFS_COMP_FLAGS_OPT,
4885                         .name = "comp-flags",   .has_arg = required_argument },
4886         { .val = LFS_COMP_FLAGS_OPT,
4887                         .name = "component-flags",
4888                                                 .has_arg = required_argument },
4889         { .val = LFS_COMP_START_OPT,
4890                         .name = "comp-start",   .has_arg = required_argument },
4891         { .val = LFS_COMP_START_OPT,
4892                         .name = "component-start",
4893                                                 .has_arg = required_argument },
4894         { .val = LFS_MIRROR_STATE_OPT,
4895                         .name = "mirror-state", .has_arg = required_argument },
4896         { .val = LFS_NEWERXY_OPT,
4897                         .name = "newer",        .has_arg = required_argument},
4898         { .val = LFS_NEWERXY_OPT,
4899                         .name = "neweraa",      .has_arg = required_argument},
4900         { .val = LFS_NEWERXY_OPT,
4901                         .name = "neweram",      .has_arg = required_argument},
4902         { .val = LFS_NEWERXY_OPT,
4903                         .name = "newerac",      .has_arg = required_argument},
4904         { .val = LFS_NEWERXY_OPT,
4905                         .name = "newerab",      .has_arg = required_argument},
4906         { .val = LFS_NEWERXY_OPT,
4907                         .name = "newerma",      .has_arg = required_argument},
4908         { .val = LFS_NEWERXY_OPT,
4909                         .name = "newermm",      .has_arg = required_argument},
4910         { .val = LFS_NEWERXY_OPT,
4911                         .name = "newermc",      .has_arg = required_argument},
4912         { .val = LFS_NEWERXY_OPT,
4913                         .name = "newermb",      .has_arg = required_argument},
4914         { .val = LFS_NEWERXY_OPT,
4915                         .name = "newerca",      .has_arg = required_argument},
4916         { .val = LFS_NEWERXY_OPT,
4917                         .name = "newercm",      .has_arg = required_argument},
4918         { .val = LFS_NEWERXY_OPT,
4919                         .name = "newercc",      .has_arg = required_argument},
4920         { .val = LFS_NEWERXY_OPT,
4921                         .name = "newercb",      .has_arg = required_argument},
4922         { .val = LFS_NEWERXY_OPT,
4923                         .name = "newerba",      .has_arg = required_argument},
4924         { .val = LFS_NEWERXY_OPT,
4925                         .name = "newerbm",      .has_arg = required_argument},
4926         { .val = LFS_NEWERXY_OPT,
4927                         .name = "newerbc",      .has_arg = required_argument},
4928         { .val = LFS_NEWERXY_OPT,
4929                         .name = "newerbb",      .has_arg = required_argument},
4930         { .val = LFS_NEWERXY_OPT,
4931                         .name = "newerBa",      .has_arg = required_argument},
4932         { .val = LFS_NEWERXY_OPT,
4933                         .name = "newerBm",      .has_arg = required_argument},
4934         { .val = LFS_NEWERXY_OPT,
4935                         .name = "newerBc",      .has_arg = required_argument},
4936         { .val = LFS_NEWERXY_OPT,
4937                         .name = "newerBB",      .has_arg = required_argument},
4938         { .val = LFS_NEWERXY_OPT,
4939                         .name = "newerat",      .has_arg = required_argument},
4940         { .val = LFS_NEWERXY_OPT,
4941                         .name = "newermt",      .has_arg = required_argument},
4942         { .val = LFS_NEWERXY_OPT,
4943                         .name = "newerct",      .has_arg = required_argument},
4944         { .val = LFS_NEWERXY_OPT,
4945                         .name = "newerbt",      .has_arg = required_argument},
4946         { .val = LFS_NEWERXY_OPT,
4947                         .name = "newerBt",      .has_arg = required_argument},
4948         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument },
4949         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument },
4950         { .val = 'C',   .name = "ctime",        .has_arg = required_argument },
4951 /* getstripe { .val = 'd', .name = "directory", .has_arg = no_argument }, */
4952         { .val = 'D',   .name = "maxdepth",     .has_arg = required_argument },
4953         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument },
4954         { .val = 'E',   .name = "component-end",
4955                                                 .has_arg = required_argument },
4956 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
4957         { .val = LFS_LAYOUT_FOREIGN_OPT,
4958                         .name = "foreign",      .has_arg = optional_argument},
4959         { .val = 'g',   .name = "gid",          .has_arg = required_argument },
4960         { .val = 'G',   .name = "group",        .has_arg = required_argument },
4961         { .val = 'h',   .name = "help",         .has_arg = no_argument },
4962         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
4963         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument },
4964         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument },
4965 /* getstripe { .val = 'I', .name = "comp-id",   .has_arg = required_argument }*/
4966         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
4967         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
4968         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
4969         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
4970         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument },
4971         { .val = 'M',   .name = "mtime",        .has_arg = required_argument },
4972         { .val = 'n',   .name = "name",         .has_arg = required_argument },
4973         { .val = 'N',   .name = "mirror-count", .has_arg = required_argument },
4974 /* find { .val = 'o'    .name = "or", .has_arg = no_argument }, like find(1) */
4975         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
4976         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
4977         /* no short option for pool yet, can be 'p' after 2.18 */
4978         { .val = LFS_POOL_OPT,
4979                         .name = "pool",         .has_arg = required_argument },
4980         { .val = '0',   .name = "print0",       .has_arg = no_argument },
4981         { .val = 'P',   .name = "print",        .has_arg = no_argument },
4982         { .val = LFS_PROJID_OPT,
4983                         .name = "projid",       .has_arg = required_argument },
4984 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
4985 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
4986 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
4987         { .val = 's',   .name = "size",         .has_arg = required_argument },
4988         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
4989         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
4990         { .val = 't',   .name = "type",         .has_arg = required_argument },
4991         { .val = LFS_FIND_PERM,
4992                         .name = "perm",         .has_arg = required_argument },
4993         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
4994         { .val = 'u',   .name = "uid",          .has_arg = required_argument },
4995         { .val = 'U',   .name = "user",         .has_arg = required_argument },
4996         { .val = 'z',   .name = "extension-size",
4997                                                 .has_arg = required_argument },
4998         { .val = 'z',   .name = "ext-size",     .has_arg = required_argument },
4999 /* getstripe { .val = 'v', .name = "verbose",   .has_arg = no_argument }, */
5000 /* getstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
5001         { .name = NULL } };
5002         int optidx = 0;
5003         int pathstart = -1;
5004         int pathend = -1;
5005         int pathbad = -1;
5006         int neg_opt = 0;
5007         time_t *xtime;
5008         int *xsign;
5009         int isoption;
5010         char *endptr;
5011
5012         time(&t);
5013
5014         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
5015         while ((c = getopt_long_only(argc, argv,
5016                 "-0A:b:B:c:C:D:E:g:G:hH:i:L:m:M:n:N:O:Ppqrs:S:t:T:u:U:vz:",
5017                 long_opts, &optidx)) >= 0) {
5018                 xtime = NULL;
5019                 xsign = NULL;
5020                 if (neg_opt)
5021                         --neg_opt;
5022                 /* '!' is part of option */
5023                 /*
5024                  * when getopt_long_only() finds a string which is not
5025                  * an option nor a known option argument it returns 1
5026                  * in that case if we already have found pathstart and pathend
5027                  * (i.e. we have the list of pathnames),
5028                  * the only supported value is "!"
5029                  */
5030                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
5031                 if (!isoption && pathend != -1) {
5032                         fprintf(stderr,
5033                                 "err: %s: filename|dirname must either precede options or follow options\n",
5034                                 argv[0]);
5035                         ret = CMD_HELP;
5036                         goto err;
5037                 }
5038                 if (!isoption && pathstart == -1)
5039                         pathstart = optind - 1;
5040                 if (isoption && pathstart != -1 && pathend == -1)
5041                         pathend = optind - 2;
5042                 switch (c) {
5043                 case 0:
5044                         /* Long options. */
5045                         break;
5046                 case 1:
5047                         /*
5048                          * unknown; opt is "!" or path component,
5049                          * checking done above.
5050                          */
5051                         if (strcmp(optarg, "!") == 0)
5052                                 neg_opt = 2;
5053                         break;
5054                 case 'A':
5055                         xtime = &param.fp_atime;
5056                         xsign = &param.fp_asign;
5057                         param.fp_exclude_atime = !!neg_opt;
5058                         /* no break, this falls through to 'B' for btime */
5059                 case 'B':
5060                         if (c == 'B') {
5061                                 xtime = &param.fp_btime;
5062                                 xsign = &param.fp_bsign;
5063                                 param.fp_exclude_btime = !!neg_opt;
5064                         }
5065                         /* no break, this falls through to 'C' for ctime */
5066                 case 'C':
5067                         if (c == 'C') {
5068                                 xtime = &param.fp_ctime;
5069                                 xsign = &param.fp_csign;
5070                                 param.fp_exclude_ctime = !!neg_opt;
5071                         }
5072                         /* no break, this falls through to 'M' for mtime */
5073                 case 'M':
5074                         if (c == 'M') {
5075                                 xtime = &param.fp_mtime;
5076                                 xsign = &param.fp_msign;
5077                                 param.fp_exclude_mtime = !!neg_opt;
5078                         }
5079                         rc = set_time(&param, &t, xtime, optarg);
5080                         if (rc == LONG_MAX) {
5081                                 ret = -1;
5082                                 goto err;
5083                         }
5084                         if (rc)
5085                                 *xsign = rc;
5086                         break;
5087                 case 'b':
5088                         if (optarg[0] == '+') {
5089                                 param.fp_blocks_sign = -1;
5090                                 optarg++;
5091                         } else if (optarg[0] == '-') {
5092                                 param.fp_blocks_sign =  1;
5093                                 optarg++;
5094                         }
5095
5096                         param.fp_blocks_units = 1024;
5097                         ret = llapi_parse_size(optarg, &param.fp_blocks,
5098                                                &param.fp_blocks_units, 0);
5099                         if (ret) {
5100                                 fprintf(stderr, "error: bad blocks '%s'\n",
5101                                         optarg);
5102                                 goto err;
5103                         }
5104                         param.fp_check_blocks = 1;
5105                         param.fp_exclude_blocks = !!neg_opt;
5106                         break;
5107                 case LFS_COMP_COUNT_OPT:
5108                         if (optarg[0] == '+') {
5109                                 param.fp_comp_count_sign = -1;
5110                                 optarg++;
5111                         } else if (optarg[0] == '-') {
5112                                 param.fp_comp_count_sign =  1;
5113                                 optarg++;
5114                         }
5115
5116                         errno = 0;
5117                         param.fp_comp_count = strtoul(optarg, &endptr, 0);
5118                         if (errno != 0 || *endptr != '\0' ||
5119                             param.fp_comp_count > UINT32_MAX) {
5120                                 fprintf(stderr,
5121                                         "error: bad component count '%s'\n",
5122                                         optarg);
5123                                 goto err;
5124                         }
5125                         param.fp_check_comp_count = 1;
5126                         param.fp_exclude_comp_count = !!neg_opt;
5127                         break;
5128                 case LFS_COMP_FLAGS_OPT:
5129                         rc = comp_str2flags(optarg, &param.fp_comp_flags,
5130                                             &param.fp_comp_neg_flags);
5131                         if (rc) {
5132                                 fprintf(stderr,
5133                                         "error: bad component flags '%s'\n",
5134                                         optarg);
5135                                 goto err;
5136                         }
5137                         param.fp_check_comp_flags = 1;
5138                         if (neg_opt) {
5139                                 __u32 flags = param.fp_comp_neg_flags;
5140
5141                                 param.fp_comp_neg_flags = param.fp_comp_flags;
5142                                 param.fp_comp_flags = flags;
5143                         }
5144                         break;
5145                 case LFS_COMP_START_OPT:
5146                         if (optarg[0] == '+') {
5147                                 param.fp_comp_start_sign = -1;
5148                                 optarg++;
5149                         } else if (optarg[0] == '-') {
5150                                 param.fp_comp_start_sign =  1;
5151                                 optarg++;
5152                         }
5153
5154                         rc = llapi_parse_size(optarg, &param.fp_comp_start,
5155                                               &param.fp_comp_start_units, 0);
5156                         if (rc) {
5157                                 fprintf(stderr,
5158                                         "error: bad component start '%s'\n",
5159                                         optarg);
5160                                 goto err;
5161                         }
5162                         param.fp_check_comp_start = 1;
5163                         param.fp_exclude_comp_start = !!neg_opt;
5164                         break;
5165                 case LFS_MIRROR_STATE_OPT:
5166                         rc = mirror_str2state(optarg, &param.fp_mirror_state,
5167                                               &param.fp_mirror_neg_state);
5168                         if (rc) {
5169                                 fprintf(stderr,
5170                                         "error: bad mirrored file state '%s'\n",
5171                                         optarg);
5172                                 goto err;
5173                         }
5174                         param.fp_check_mirror_state = 1;
5175                         if (neg_opt) {
5176                                 __u16 state = param.fp_mirror_neg_state;
5177
5178                                 param.fp_mirror_neg_state =
5179                                         param.fp_mirror_state;
5180                                 param.fp_mirror_state = state;
5181                         }
5182                         break;
5183                 case 'c':
5184                         if (optarg[0] == '+') {
5185                                 param.fp_stripe_count_sign = -1;
5186                                 optarg++;
5187                         } else if (optarg[0] == '-') {
5188                                 param.fp_stripe_count_sign =  1;
5189                                 optarg++;
5190                         }
5191
5192                         errno = 0;
5193                         param.fp_stripe_count = strtoul(optarg, &endptr, 0);
5194                         if (errno != 0 || *endptr != '\0' ||
5195                             param.fp_stripe_count > LOV_MAX_STRIPE_COUNT) {
5196                                 fprintf(stderr,
5197                                         "error: bad stripe_count '%s'\n",
5198                                         optarg);
5199                                 ret = -1;
5200                                 goto err;
5201                         }
5202                         param.fp_check_stripe_count = 1;
5203                         param.fp_exclude_stripe_count = !!neg_opt;
5204                         break;
5205                 case 'D':
5206                         errno = 0;
5207                         param.fp_max_depth = strtol(optarg, 0, 0);
5208                         if (errno != 0 || param.fp_max_depth < 0) {
5209                                 fprintf(stderr,
5210                                         "error: bad maxdepth '%s'\n",
5211                                         optarg);
5212                                 ret = -1;
5213                                 goto err;
5214                         }
5215                         break;
5216                 case 'E':
5217                         if (optarg[0] == '+') {
5218                                 param.fp_comp_end_sign = -1;
5219                                 optarg++;
5220                         } else if (optarg[0] == '-') {
5221                                 param.fp_comp_end_sign =  1;
5222                                 optarg++;
5223                         }
5224
5225                         if (arg_is_eof(optarg)) {
5226                                 param.fp_comp_end = LUSTRE_EOF;
5227                                 param.fp_comp_end_units = 1;
5228                                 rc = 0;
5229                         } else {
5230                                 rc = llapi_parse_size(optarg,
5231                                                 &param.fp_comp_end,
5232                                                 &param.fp_comp_end_units, 0);
5233                                 /* assume units of KB if too small */
5234                                 if (param.fp_comp_end < 4096)
5235                                         param.fp_comp_end *= 1024;
5236                         }
5237                         if (rc) {
5238                                 fprintf(stderr,
5239                                         "error: bad component end '%s'\n",
5240                                         optarg);
5241                                 goto err;
5242                         }
5243                         param.fp_check_comp_end = 1;
5244                         param.fp_exclude_comp_end = !!neg_opt;
5245                         break;
5246                 case LFS_LAYOUT_FOREIGN_OPT: {
5247                         /* all types by default */
5248                         uint32_t type = LU_FOREIGN_TYPE_UNKNOWN;
5249
5250                         if (optarg) {
5251                                 /* check pure numeric */
5252                                 type = strtoul(optarg, &endptr, 0);
5253                                 if (*endptr) {
5254                                         /* check name */
5255                                         type = check_foreign_type_name(optarg);
5256                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
5257                                                 fprintf(stderr,
5258                                                         "%s %s: unknown foreign type '%s'\n",
5259                                                         progname, argv[0],
5260                                                         optarg);
5261                                                 return CMD_HELP;
5262                                         }
5263                                 } else if (type >= UINT32_MAX) {
5264                                         fprintf(stderr,
5265                                                 "%s %s: invalid foreign type '%s'\n",
5266                                                 progname, argv[0], optarg);
5267                                         return CMD_HELP;
5268                                 }
5269                         }
5270                         param.fp_foreign_type = type;
5271                         param.fp_check_foreign = 1;
5272                         param.fp_exclude_foreign = !!neg_opt;
5273                         break;
5274                 }
5275                 case LFS_NEWERXY_OPT: {
5276                         char x = 'm';
5277                         char y = 'm';
5278                         int xidx;
5279                         int negidx;
5280                         time_t *newery;
5281                         time_t ref = time(NULL);
5282
5283                         /* no need to check bad options, they won't get here */
5284                         if (strlen(long_opts[optidx].name) == 7) {
5285                                 x = long_opts[optidx].name[5];
5286                                 y = long_opts[optidx].name[6];
5287                         }
5288
5289                         if (y == 't') {
5290                                 static const char *const fmts[] = {
5291                                         "%Y-%m-%d %H:%M:%S",
5292                                         "%Y-%m-%d %H:%M",
5293                                         "%Y-%m-%d",
5294                                         "%H:%M:%S", /* sometime today */
5295                                         "%H:%M",
5296                                         "@%s",
5297                                         "%s",
5298                                         NULL };
5299                                 struct tm tm;
5300                                 bool found = false;
5301                                 int i;
5302
5303                                 for (i = 0; fmts[i] != NULL; i++) {
5304                                         char *ptr;
5305
5306                                         /* Init for times relative to today */
5307                                         if (strncmp(fmts[i], "%H", 2) == 0)
5308                                                 localtime_r(&ref, &tm);
5309                                         else
5310                                                 memset(&tm, 0, sizeof(tm));
5311                                         ptr = strptime(optarg, fmts[i], &tm);
5312                                         /* Skip spaces */
5313                                         while (ptr && isspace(*ptr))
5314                                                 ptr++;
5315                                         if (ptr == optarg + strlen(optarg)) {
5316                                                 found = true;
5317                                                 break;
5318                                         }
5319                                 }
5320
5321                                 if (!found) {
5322                                         fprintf(stderr,
5323                                                 "%s: invalid time '%s'\n",
5324                                                 progname, optarg);
5325                                         fprintf(stderr,
5326                                                 "supported formats are:\n  ");
5327                                         for (i = 0; fmts[i] != NULL; i++)
5328                                                 fprintf(stderr, "'%s', ",
5329                                                         fmts[i]);
5330                                         fprintf(stderr, "\n");
5331                                         ret = -EINVAL;
5332                                         goto err;
5333                                 }
5334
5335                                 ref = mktime(&tm);
5336                         } else if (y == 'b' || y == 'B') {
5337                                 lstatx_t stx;
5338
5339                                 rc = llapi_get_lum_file(optarg, NULL, &stx,
5340                                                         NULL, 0);
5341                                 if (rc || !(stx.stx_mask & STATX_BTIME)) {
5342                                         if (!(stx.stx_mask & STATX_BTIME))
5343                                                 ret = -EOPNOTSUPP;
5344                                         else
5345                                                 ret = -errno;
5346                                         fprintf(stderr,
5347                                                 "%s: get btime failed '%s': %s\n",
5348                                                 progname, optarg,
5349                                                 strerror(-ret));
5350                                         goto err;
5351                                 }
5352
5353                                 ref = stx.stx_btime.tv_sec;
5354                         } else {
5355                                 struct stat statbuf;
5356
5357                                 if (stat(optarg, &statbuf) < 0) {
5358                                         fprintf(stderr,
5359                                                 "%s: cannot stat file '%s': %s\n",
5360                                                 progname, optarg,
5361                                                 strerror(errno));
5362                                         ret = -errno;
5363                                         goto err;
5364                                 }
5365
5366                                 switch (y) {
5367                                 case 'a':
5368                                         ref = statbuf.st_atime;
5369                                         break;
5370                                 case 'm':
5371                                         ref = statbuf.st_mtime;
5372                                         break;
5373                                 case 'c':
5374                                         ref = statbuf.st_ctime;
5375                                         break;
5376                                 default:
5377                                         fprintf(stderr,
5378                                                 "%s: invalid Y argument: '%c'\n",
5379                                                 progname, x);
5380                                         ret = -EINVAL;
5381                                         goto err;
5382                                 }
5383                         }
5384
5385                         switch (x) {
5386                         case 'a':
5387                                 xidx = NEWERXY_ATIME;
5388                                 break;
5389                         case 'm':
5390                                 xidx = NEWERXY_MTIME;
5391                                 break;
5392                         case 'c':
5393                                 xidx = NEWERXY_CTIME;
5394                                 break;
5395                         case 'b':
5396                         case 'B':
5397                                 xidx = NEWERXY_BTIME;
5398                                 break;
5399                         default:
5400                                 fprintf(stderr,
5401                                         "%s: invalid X argument: '%c'\n",
5402                                         progname, x);
5403                                 ret = -EINVAL;
5404                                 goto err;
5405                         }
5406
5407                         negidx = !!neg_opt;
5408                         newery = &param.fp_newery[xidx][negidx];
5409
5410                         if (*newery == 0) {
5411                                 *newery = ref;
5412                         } else {
5413                                 if (negidx)
5414                                         *newery = *newery > ref ? ref : *newery;
5415                                 else
5416                                         *newery = *newery > ref ? *newery : ref;
5417                         }
5418                         param.fp_newerxy = 1;
5419                         break;
5420                 }
5421                 case 'g':
5422                 case 'G':
5423                         rc = name2gid(&param.fp_gid, optarg);
5424                         if (rc) {
5425                                 if (str2quotaid(&param.fp_gid, optarg)) {
5426                                         fprintf(stderr,
5427                                                 "Group/GID: %s cannot be found.\n",
5428                                                 optarg);
5429                                         ret = -1;
5430                                         goto err;
5431                                 }
5432                         }
5433                         param.fp_exclude_gid = !!neg_opt;
5434                         param.fp_check_gid = 1;
5435                         break;
5436                 case 'H':
5437                         rc = mdthash_input(optarg, &param.fp_hash_inflags,
5438                                            &param.fp_hash_exflags,
5439                                            &param.fp_hash_type);
5440                         if (rc) {
5441                                 ret = -1;
5442                                 goto err;
5443                         }
5444                         if (param.fp_hash_inflags || param.fp_hash_exflags)
5445                                 param.fp_check_hash_flag = 1;
5446                         param.fp_exclude_hash_type = !!neg_opt;
5447                         break;
5448                 case 'l':
5449                         param.fp_lazy = 1;
5450                         break;
5451                 case 'L':
5452                         ret = name2layout(&param.fp_layout, optarg);
5453                         if (ret)
5454                                 goto err;
5455                         param.fp_exclude_layout = !!neg_opt;
5456                         param.fp_check_layout = 1;
5457                         break;
5458                 case 'u':
5459                 case 'U':
5460                         rc = name2uid(&param.fp_uid, optarg);
5461                         if (rc) {
5462                                 if (str2quotaid(&param.fp_uid, optarg)) {
5463                                         fprintf(stderr,
5464                                                 "User/UID: %s cannot be found.\n",
5465                                                 optarg);
5466                                         ret = -1;
5467                                         goto err;
5468                                 }
5469                         }
5470                         param.fp_exclude_uid = !!neg_opt;
5471                         param.fp_check_uid = 1;
5472                         break;
5473                 case 'n':
5474                         param.fp_pattern = (char *)optarg;
5475                         param.fp_exclude_pattern = !!neg_opt;
5476                         break;
5477                 case 'N':
5478                         if (optarg[0] == '+') {
5479                                 param.fp_mirror_count_sign = -1;
5480                                 optarg++;
5481                         } else if (optarg[0] == '-') {
5482                                 param.fp_mirror_count_sign =  1;
5483                                 optarg++;
5484                         }
5485
5486                         errno = 0;
5487                         param.fp_mirror_count = strtoul(optarg, &endptr, 0);
5488                         if (errno != 0 || *endptr != '\0' ||
5489                             param.fp_mirror_count > LUSTRE_MIRROR_COUNT_MAX) {
5490                                 fprintf(stderr,
5491                                         "error: bad mirror count '%s'\n",
5492                                         optarg);
5493                                 goto err;
5494                         }
5495                         param.fp_check_mirror_count = 1;
5496                         param.fp_exclude_mirror_count = !!neg_opt;
5497                         break;
5498                 case 'm':
5499                 case 'i':
5500                 case 'O': {
5501                         char *buf, *token, *next, *p;
5502                         int len = 1;
5503                         void *tmp;
5504
5505                         buf = strdup(optarg);
5506                         if (!buf) {
5507                                 ret = -ENOMEM;
5508                                 goto err;
5509                         }
5510
5511                         param.fp_exclude_obd = !!neg_opt;
5512
5513                         token = buf;
5514                         while (token && *token) {
5515                                 token = strchr(token, ',');
5516                                 if (token) {
5517                                         len++;
5518                                         token++;
5519                                 }
5520                         }
5521                         if (c == 'm') {
5522                                 param.fp_exclude_mdt = !!neg_opt;
5523                                 param.fp_num_alloc_mdts += len;
5524                                 tmp = realloc(param.fp_mdt_uuid,
5525                                               param.fp_num_alloc_mdts *
5526                                               sizeof(*param.fp_mdt_uuid));
5527                                 if (!tmp) {
5528                                         ret = -ENOMEM;
5529                                         goto err_free;
5530                                 }
5531
5532                                 param.fp_mdt_uuid = tmp;
5533                         } else {
5534                                 param.fp_exclude_obd = !!neg_opt;
5535                                 param.fp_num_alloc_obds += len;
5536                                 tmp = realloc(param.fp_obd_uuid,
5537                                               param.fp_num_alloc_obds *
5538                                               sizeof(*param.fp_obd_uuid));
5539                                 if (!tmp) {
5540                                         ret = -ENOMEM;
5541                                         goto err_free;
5542                                 }
5543
5544                                 param.fp_obd_uuid = tmp;
5545                         }
5546                         for (token = buf; token && *token; token = next) {
5547                                 struct obd_uuid *puuid;
5548
5549                                 if (c == 'm') {
5550                                         puuid =
5551                                         &param.fp_mdt_uuid[param.fp_num_mdts++];
5552                                 } else {
5553                                         puuid =
5554                                         &param.fp_obd_uuid[param.fp_num_obds++];
5555                                 }
5556                                 p = strchr(token, ',');
5557                                 next = 0;
5558                                 if (p) {
5559                                         *p = 0;
5560                                         next = p+1;
5561                                 }
5562
5563                                 if (strlen(token) > sizeof(puuid->uuid) - 1) {
5564                                         ret = -E2BIG;
5565                                         goto err_free;
5566                                 }
5567
5568                                 strncpy(puuid->uuid, token,
5569                                         sizeof(puuid->uuid));
5570                         }
5571 err_free:
5572                         if (buf)
5573                                 free(buf);
5574                         break;
5575                 }
5576 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 18, 53, 0)
5577                 case 'p':
5578 #endif
5579                 case LFS_POOL_OPT:
5580                         if (strlen(optarg) > LOV_MAXPOOLNAME) {
5581                                 fprintf(stderr,
5582                                         "Pool name %s is too long (max %d)\n",
5583                                         optarg, LOV_MAXPOOLNAME);
5584                                 ret = -1;
5585                                 goto err;
5586                         }
5587                         /*
5588                          * We do check for empty pool because empty pool
5589                          * is used to find V1 LOV attributes
5590                          */
5591                         strncpy(param.fp_poolname, optarg, LOV_MAXPOOLNAME);
5592                         param.fp_poolname[LOV_MAXPOOLNAME] = '\0';
5593                         param.fp_exclude_pool = !!neg_opt;
5594                         param.fp_check_pool = 1;
5595                         break;
5596 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 14, 53, 0)
5597                 case 'p': /* want this for --pool, to match getstripe/find */
5598                         fprintf(stderr,
5599                                 "warning: -p deprecated, use --print0 or -0\n");
5600 #endif
5601                 case '0':
5602                         param.fp_zero_end = 1;
5603                         break;
5604                 case 'P': /* we always print, this option is a no-op */
5605                         break;
5606                 case LFS_PROJID_OPT:
5607                         rc = name2projid(&param.fp_projid, optarg);
5608                         if (rc) {
5609                                 if (str2quotaid(&param.fp_projid, optarg)) {
5610                                         fprintf(stderr,
5611                                                 "Invalid project ID: %s\n",
5612                                                 optarg);
5613                                         ret = -1;
5614                                         goto err;
5615                                 }
5616                         }
5617                         param.fp_exclude_projid = !!neg_opt;
5618                         param.fp_check_projid = 1;
5619                         break;
5620                 case 's':
5621                         if (optarg[0] == '+') {
5622                                 param.fp_size_sign = -1;
5623                                 optarg++;
5624                         } else if (optarg[0] == '-') {
5625                                 param.fp_size_sign =  1;
5626                                 optarg++;
5627                         }
5628
5629                         ret = llapi_parse_size(optarg, &param.fp_size,
5630                                                &param.fp_size_units, 0);
5631                         if (ret) {
5632                                 fprintf(stderr, "error: bad file size '%s'\n",
5633                                         optarg);
5634                                 goto err;
5635                         }
5636                         param.fp_check_size = 1;
5637                         param.fp_exclude_size = !!neg_opt;
5638                         break;
5639                 case 'S':
5640                         if (optarg[0] == '+') {
5641                                 param.fp_stripe_size_sign = -1;
5642                                 optarg++;
5643                         } else if (optarg[0] == '-') {
5644                                 param.fp_stripe_size_sign =  1;
5645                                 optarg++;
5646                         }
5647
5648                         ret = llapi_parse_size(optarg, &param.fp_stripe_size,
5649                                                &param.fp_stripe_size_units, 0);
5650                         /* assume units of KB if too small to be valid */
5651                         if (param.fp_stripe_size < 4096)
5652                                 param.fp_stripe_size *= 1024;
5653                         if (ret) {
5654                                 fprintf(stderr, "error: bad stripe_size '%s'\n",
5655                                         optarg);
5656                                 goto err;
5657                         }
5658                         param.fp_check_stripe_size = 1;
5659                         param.fp_exclude_stripe_size = !!neg_opt;
5660                         break;
5661                 case 't':
5662                         param.fp_exclude_type = !!neg_opt;
5663                         switch (optarg[0]) {
5664                         case 'b':
5665                                 param.fp_type = S_IFBLK;
5666                                 break;
5667                         case 'c':
5668                                 param.fp_type = S_IFCHR;
5669                                 break;
5670                         case 'd':
5671                                 param.fp_type = S_IFDIR;
5672                                 break;
5673                         case 'f':
5674                                 param.fp_type = S_IFREG;
5675                                 break;
5676                         case 'l':
5677                                 param.fp_type = S_IFLNK;
5678                                 break;
5679                         case 'p':
5680                                 param.fp_type = S_IFIFO;
5681                                 break;
5682                         case 's':
5683                                 param.fp_type = S_IFSOCK;
5684                                 break;
5685                         default:
5686                                 fprintf(stderr, "%s: bad type '%s'\n",
5687                                         progname, optarg);
5688                                 ret = CMD_HELP;
5689                                 goto err;
5690                         }
5691                         break;
5692                 case LFS_FIND_PERM:
5693                         param.fp_exclude_perm = !!neg_opt;
5694                         param.fp_perm_sign = LFS_FIND_PERM_EXACT;
5695                         if (*optarg == '/') {
5696                                 param.fp_perm_sign = LFS_FIND_PERM_ANY;
5697                                 optarg++;
5698                         } else if (*optarg == '-') {
5699                                 param.fp_perm_sign = LFS_FIND_PERM_ALL;
5700                                 optarg++;
5701                         }
5702
5703                         if (str2mode_t(optarg, &param.fp_perm)) {
5704                                 fprintf(stderr, "error: invalid mode '%s'\n",
5705                                         optarg);
5706                                 ret = -1;
5707                                 goto err;
5708                         }
5709                         break;
5710                 case 'T':
5711                         if (optarg[0] == '+') {
5712                                 param.fp_mdt_count_sign = -1;
5713                                 optarg++;
5714                         } else if (optarg[0] == '-') {
5715                                 param.fp_mdt_count_sign =  1;
5716                                 optarg++;
5717                         }
5718
5719                         errno = 0;
5720                         param.fp_mdt_count = strtoul(optarg, &endptr, 0);
5721                         if (errno != 0 || *endptr != '\0' ||
5722                             param.fp_mdt_count >= UINT32_MAX) {
5723                                 fprintf(stderr, "error: bad mdt_count '%s'\n",
5724                                         optarg);
5725                                 ret = -1;
5726                                 goto err;
5727                         }
5728                         param.fp_check_mdt_count = 1;
5729                         param.fp_exclude_mdt_count = !!neg_opt;
5730                         break;
5731                 case 'z':
5732                         if (optarg[0] == '+') {
5733                                 param.fp_ext_size_sign = -1;
5734                                 optarg++;
5735                         } else if (optarg[0] == '-') {
5736                                 param.fp_ext_size_sign =  1;
5737                                 optarg++;
5738                         }
5739
5740                         ret = llapi_parse_size(optarg, &param.fp_ext_size,
5741                                                &param.fp_ext_size_units, 0);
5742                         if (ret) {
5743                                 fprintf(stderr, "error: bad ext-size '%s'\n",
5744                                         optarg);
5745                                 goto err;
5746                         }
5747                         param.fp_ext_size /= SEL_UNIT_SIZE;
5748                         param.fp_ext_size_units /= SEL_UNIT_SIZE;
5749                         param.fp_check_ext_size = 1;
5750                         param.fp_exclude_ext_size = !!neg_opt;
5751                         break;
5752                 default:
5753                         fprintf(stderr, "%s: unrecognized option '%s'\n",
5754                                 progname, argv[optind - 1]);
5755                 case 'h':
5756                         ret = CMD_HELP;
5757                         goto err;
5758                 }
5759         }
5760
5761         if (pathstart == -1) {
5762                 fprintf(stderr, "error: %s: no filename|pathname\n",
5763                         argv[0]);
5764                 ret = CMD_HELP;
5765                 goto err;
5766         } else if (pathend == -1) {
5767                 /* no options */
5768                 pathend = argc;
5769         }
5770
5771         do {
5772                 rc = llapi_find(argv[pathstart], &param);
5773                 if (rc && !ret) {
5774                         ret = rc;
5775                         pathbad = pathstart;
5776                 }
5777         } while (++pathstart < pathend);
5778
5779         if (ret)
5780                 fprintf(stderr, "%s: failed for '%s': %s\n",
5781                         progname, argv[pathbad], strerror(-rc));
5782
5783 err:
5784         if (param.fp_obd_uuid && param.fp_num_alloc_obds)
5785                 free(param.fp_obd_uuid);
5786
5787         if (param.fp_mdt_uuid && param.fp_num_alloc_mdts)
5788                 free(param.fp_mdt_uuid);
5789
5790         return ret;
5791 }
5792
5793 static int lfs_getstripe_internal(int argc, char **argv,
5794                                   struct find_param *param)
5795 {
5796         struct option long_opts[] = {
5797 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
5798 /* find { .val = 'b',   .name = "blocks",       .has_arg = required_argument }*/
5799 /* find { .val = 'B',   .name = "btime",        .has_arg = required_argument }*/
5800 /* find { .val = 'B',   .name = "Btime",        .has_arg = required_argument }*/
5801         { .val = LFS_COMP_COUNT_OPT,
5802                         .name = "comp-count",   .has_arg = no_argument },
5803         { .val = LFS_COMP_COUNT_OPT,
5804                 .name = "component-count",      .has_arg = no_argument },
5805         { .val = LFS_COMP_FLAGS_OPT,
5806                         .name = "comp-flags",   .has_arg = optional_argument },
5807         { .val = LFS_COMP_FLAGS_OPT,
5808                 .name = "component-flags",      .has_arg = optional_argument },
5809         { .val = LFS_COMP_START_OPT,
5810                         .name = "comp-start",   .has_arg = optional_argument },
5811         { .val = LFS_COMP_START_OPT,
5812                 .name = "component-start",      .has_arg = optional_argument },
5813         { .val = LFS_MIRROR_INDEX_OPT,
5814                 .name = "mirror-index",         .has_arg = required_argument },
5815         { .val = LFS_MIRROR_ID_OPT,
5816                 .name = "mirror-id",            .has_arg = required_argument },
5817         { .val = 'c',   .name = "stripe-count", .has_arg = no_argument },
5818         { .val = 'c',   .name = "stripe_count", .has_arg = no_argument },
5819 /* find { .val = 'C',   .name = "ctime",        .has_arg = required_argument }*/
5820         { .val = 'd',   .name = "directory",    .has_arg = no_argument },
5821         { .val = 'D',   .name = "default",      .has_arg = no_argument },
5822         { .val = 'E',   .name = "comp-end",     .has_arg = optional_argument },
5823         { .val = 'E',   .name = "component-end", .has_arg = optional_argument },
5824         { .val = 'F',   .name = "fid",          .has_arg = no_argument },
5825         { .val = 'g',   .name = "generation",   .has_arg = no_argument },
5826 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
5827         { .val = 'h',   .name = "help",         .has_arg = no_argument },
5828 /* dirstripe { .val = 'H', .name = "mdt-hash",  .has_arg = required_argument }*/
5829         { .val = 'i',   .name = "stripe-index", .has_arg = no_argument },
5830         { .val = 'i',   .name = "stripe_index", .has_arg = no_argument },
5831         { .val = 'I',   .name = "comp-id",      .has_arg = optional_argument },
5832         { .val = 'I',   .name = "component-id", .has_arg = optional_argument },
5833 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
5834         { .val = 'L',   .name = "layout",       .has_arg = no_argument },
5835         { .val = 'm',   .name = "mdt",          .has_arg = no_argument },
5836         { .val = 'm',   .name = "mdt-index",    .has_arg = no_argument },
5837         { .val = 'm',   .name = "mdt_index",    .has_arg = no_argument },
5838 /* find { .val = 'M',   .name = "mtime",        .has_arg = required_argument }*/
5839 /* find { .val = 'n',   .name = "name",         .has_arg = required_argument }*/
5840         { .val = 'N',   .name = "mirror-count", .has_arg = no_argument },
5841         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
5842         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
5843         { .val = 'p',   .name = "pool",         .has_arg = no_argument },
5844 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
5845         { .val = 'q',   .name = "quiet",        .has_arg = no_argument },
5846         { .val = 'r',   .name = "recursive",    .has_arg = no_argument },
5847         { .val = 'R',   .name = "raw",          .has_arg = no_argument },
5848         { .val = 'S',   .name = "stripe-size",  .has_arg = no_argument },
5849         { .val = 'S',   .name = "stripe_size",  .has_arg = no_argument },
5850 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
5851 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
5852 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
5853 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
5854         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
5855 /* dirstripe { .val = 'X',.name = "max-inherit",.has_arg = required_argument }*/
5856         { .val = 'y',   .name = "yaml",         .has_arg = no_argument },
5857         { .val = 'z',   .name = "extension-size", .has_arg = no_argument },
5858         { .val = 'z',   .name = "ext-size",     .has_arg = no_argument },
5859         { .name = NULL } };
5860         int c, rc;
5861         int neg_opt = 0;
5862         int pathstart = -1, pathend = -1;
5863         int isoption;
5864         char *end, *tmp;
5865
5866         while ((c = getopt_long(argc, argv,
5867                         "-cdDE::FghiI::LmMNoO:pqrRsSvyz",
5868                         long_opts, NULL)) != -1) {
5869                 if (neg_opt)
5870                         --neg_opt;
5871
5872                 /* '!' is part of option */
5873                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
5874                 if (!isoption && pathend != -1) {
5875                         fprintf(stderr,
5876                                 "error: %s: filename|dirname must either precede options or follow options\n",
5877                                 argv[0]);
5878                         return CMD_HELP;
5879                 }
5880                 if (!isoption && pathstart == -1)
5881                         pathstart = optind - 1;
5882                 if (isoption && pathstart != -1 && pathend == -1)
5883                         pathend = optind - 2;
5884
5885                 switch (c) {
5886                 case 1:
5887                         /* unknown: opt is "!" */
5888                         if (strcmp(optarg, "!") == 0)
5889                                 neg_opt = 2;
5890                         break;
5891                 case 'c':
5892                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
5893                                 param->fp_verbose |= VERBOSE_COUNT;
5894                                 param->fp_max_depth = 0;
5895                         }
5896                         break;
5897                 case LFS_COMP_COUNT_OPT:
5898                         param->fp_verbose |= VERBOSE_COMP_COUNT;
5899                         param->fp_max_depth = 0;
5900                         break;
5901                 case LFS_COMP_FLAGS_OPT:
5902                         if (optarg) {
5903                                 rc = comp_str2flags(optarg,
5904                                                     &param->fp_comp_flags,
5905                                                     &param->fp_comp_neg_flags);
5906                                 if (rc != 0) {
5907                                         fprintf(stderr,
5908                                                 "error: %s bad component flags '%s'.\n",
5909                                                 argv[0], optarg);
5910                                         return CMD_HELP;
5911                                 }
5912                                 param->fp_check_comp_flags = 1;
5913                         } else {
5914                                 param->fp_verbose |= VERBOSE_COMP_FLAGS;
5915                                 param->fp_max_depth = 0;
5916                         }
5917                         break;
5918                 case LFS_COMP_START_OPT:
5919                         if (optarg) {
5920                                 tmp = optarg;
5921                                 if (tmp[0] == '+') {
5922                                         param->fp_comp_start_sign = -1;
5923                                         tmp++;
5924                                 } else if (tmp[0] == '-') {
5925                                         param->fp_comp_start_sign = 1;
5926                                         tmp++;
5927                                 }
5928                                 rc = llapi_parse_size(tmp,
5929                                                 &param->fp_comp_start,
5930                                                 &param->fp_comp_start_units, 0);
5931                                 if (rc != 0) {
5932                                         fprintf(stderr,
5933                                                 "error: %s bad component start '%s'.\n",
5934                                                 argv[0], tmp);
5935                                         return CMD_HELP;
5936                                 }
5937                                 param->fp_check_comp_start = 1;
5938                         } else {
5939                                 param->fp_verbose |= VERBOSE_COMP_START;
5940                                 param->fp_max_depth = 0;
5941                         }
5942                         break;
5943                 case LFS_MIRROR_INDEX_OPT: {
5944                         unsigned long int mirror_index;
5945
5946                         if (optarg[0] == '+') {
5947                                 param->fp_mirror_index_sign = -1;
5948                                 optarg++;
5949                         } else if (optarg[0] == '-') {
5950                                 param->fp_mirror_index_sign = 1;
5951                                 optarg++;
5952                         }
5953
5954                         errno = 0;
5955                         mirror_index = strtoul(optarg, &end, 0);
5956                         if (errno != 0 || *end != '\0' ||
5957                             mirror_index > UINT16_MAX || (mirror_index == 0 &&
5958                             param->fp_mirror_index_sign == 0 && neg_opt == 0)) {
5959                                 fprintf(stderr,
5960                                         "%s %s: invalid mirror index '%s'\n",
5961                                         progname, argv[0], optarg);
5962                                 return CMD_HELP;
5963                         }
5964
5965                         param->fp_mirror_index = (__u16)mirror_index;
5966
5967                         if (param->fp_mirror_id != 0) {
5968                                 fprintf(stderr,
5969                                         "%s %s: can't specify both mirror index and mirror ID\n",
5970                                         progname, argv[0]);
5971                                 return CMD_HELP;
5972                         }
5973                         param->fp_check_mirror_index = 1;
5974                         param->fp_exclude_mirror_index = !!neg_opt;
5975                         break;
5976                 }
5977                 case LFS_MIRROR_ID_OPT: {
5978                         unsigned long int mirror_id;
5979
5980                         if (optarg[0] == '+') {
5981                                 param->fp_mirror_id_sign = -1;
5982                                 optarg++;
5983                         } else if (optarg[0] == '-') {
5984                                 param->fp_mirror_id_sign = 1;
5985                                 optarg++;
5986                         }
5987
5988                         errno = 0;
5989                         mirror_id = strtoul(optarg, &end, 0);
5990                         if (errno != 0 || *end != '\0' ||
5991                             mirror_id > UINT16_MAX || (mirror_id == 0 &&
5992                             param->fp_mirror_id_sign == 0 && neg_opt == 0)) {
5993                                 fprintf(stderr,
5994                                         "%s %s: invalid mirror ID '%s'\n",
5995                                         progname, argv[0], optarg);
5996                                 return CMD_HELP;
5997                         }
5998
5999                         param->fp_mirror_id = (__u16)mirror_id;
6000
6001                         if (param->fp_mirror_index != 0) {
6002                                 fprintf(stderr,
6003                                         "%s %s: can't specify both mirror index and mirror ID\n",
6004                                         progname, argv[0]);
6005                                 return CMD_HELP;
6006                         }
6007                         param->fp_check_mirror_id = 1;
6008                         param->fp_exclude_mirror_id = !!neg_opt;
6009                         break;
6010                 }
6011                 case 'd':
6012                         param->fp_max_depth = 0;
6013                         break;
6014                 case 'D':
6015                         param->fp_get_default_lmv = 1;
6016                         break;
6017                 case 'E':
6018                         if (optarg) {
6019                                 tmp = optarg;
6020                                 if (tmp[0] == '+') {
6021                                         param->fp_comp_end_sign = -1;
6022                                         tmp++;
6023                                 } else if (tmp[0] == '-') {
6024                                         param->fp_comp_end_sign = 1;
6025                                         tmp++;
6026                                 }
6027
6028                                 if (arg_is_eof(tmp)) {
6029                                         param->fp_comp_end = LUSTRE_EOF;
6030                                         param->fp_comp_end_units = 1;
6031                                         rc = 0;
6032                                 } else {
6033                                         rc = llapi_parse_size(tmp,
6034                                                 &param->fp_comp_end,
6035                                                 &param->fp_comp_end_units, 0);
6036                                         /* assume units of KB if too small */
6037                                         if (param->fp_comp_end < 4096)
6038                                                 param->fp_comp_end *= 1024;
6039                                 }
6040                                 if (rc != 0) {
6041                                         fprintf(stderr,
6042                                                 "error: %s bad component end '%s'.\n",
6043                                                 argv[0], tmp);
6044                                         return CMD_HELP;
6045                                 }
6046                                 param->fp_check_comp_end = 1;
6047                         } else {
6048                                 param->fp_verbose |= VERBOSE_COMP_END;
6049                                 param->fp_max_depth = 0;
6050                         }
6051                         break;
6052                 case 'F':
6053                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6054                                 param->fp_verbose |= VERBOSE_DFID;
6055                                 param->fp_max_depth = 0;
6056                         }
6057                         break;
6058                 case 'g':
6059                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6060                                 param->fp_verbose |= VERBOSE_GENERATION;
6061                                 param->fp_max_depth = 0;
6062                         }
6063                         break;
6064                 case 'i':
6065                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6066                                 param->fp_verbose |= VERBOSE_STRIPE_OFFSET;
6067                                 param->fp_max_depth = 0;
6068                         }
6069                         break;
6070                 case 'I':
6071                         if (optarg) {
6072                                 param->fp_comp_id = strtoul(optarg, &end, 0);
6073                                 if (*end != '\0' || param->fp_comp_id == 0 ||
6074                                     param->fp_comp_id > LCME_ID_MAX) {
6075                                         fprintf(stderr,
6076                                                 "error: %s bad component id '%s'\n",
6077                                                 argv[0], optarg);
6078                                         return CMD_HELP;
6079                                 }
6080                                 param->fp_check_comp_id = 1;
6081                         } else {
6082                                 param->fp_max_depth = 0;
6083                                 param->fp_verbose |= VERBOSE_COMP_ID;
6084                         }
6085                         break;
6086                 case 'L':
6087                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6088                                 param->fp_verbose |= VERBOSE_PATTERN;
6089                                 param->fp_max_depth = 0;
6090                         }
6091                         break;
6092 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6093                 case 'M':
6094                         fprintf(stderr,
6095                                 "warning: '-M' deprecated, use '--mdt-index' or '-m' instead\n");
6096 #endif
6097                 case 'm':
6098                         if (!(param->fp_verbose & VERBOSE_DETAIL))
6099                                 param->fp_max_depth = 0;
6100                         param->fp_verbose |= VERBOSE_MDTINDEX;
6101                         break;
6102                 case 'N':
6103                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6104                                 param->fp_verbose |= VERBOSE_MIRROR_COUNT;
6105                                 param->fp_max_depth = 0;
6106                         }
6107                         break;
6108                 case 'O':
6109                         if (param->fp_obd_uuid) {
6110                                 fprintf(stderr,
6111                                         "error: %s: only one obduuid allowed",
6112                                         argv[0]);
6113                                 return CMD_HELP;
6114                         }
6115                         param->fp_obd_uuid = (struct obd_uuid *)optarg;
6116                         break;
6117                 case 'p':
6118                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6119                                 param->fp_verbose |= VERBOSE_POOL;
6120                                 param->fp_max_depth = 0;
6121                         }
6122                         break;
6123                 case 'q':
6124                         param->fp_quiet++;
6125                         break;
6126                 case 'r':
6127                         param->fp_recursive = 1;
6128                         break;
6129                 case 'R':
6130                         param->fp_raw = 1;
6131                         break;
6132                 case 'S':
6133                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6134                                 param->fp_verbose |= VERBOSE_STRIPE_SIZE;
6135                                 param->fp_max_depth = 0;
6136                         }
6137                         break;
6138                 case 'v':
6139                         param->fp_verbose = VERBOSE_DEFAULT | VERBOSE_DETAIL;
6140                         break;
6141                 case 'y':
6142                         param->fp_yaml = 1;
6143                         break;
6144                 case 'z':
6145                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
6146                                 param->fp_verbose |= VERBOSE_EXT_SIZE;
6147                                 param->fp_max_depth = 0;
6148                         }
6149                         break;
6150                 default:
6151                         fprintf(stderr, "%s: unrecognized option '%s'\n",
6152                                 progname, argv[optind - 1]);
6153                 case 'h':
6154                         return CMD_HELP;
6155                 }
6156         }
6157
6158         if (pathstart == -1) {
6159                 fprintf(stderr, "error: %s: no filename|pathname\n",
6160                                 argv[0]);
6161                 return CMD_HELP;
6162         } else if (pathend == -1) {
6163                 /* no options */
6164                 pathend = argc;
6165         }
6166
6167         if (pathend > argc)
6168                 return CMD_HELP;
6169
6170         if (param->fp_recursive)
6171                 param->fp_max_depth = -1;
6172         else if (param->fp_verbose & VERBOSE_DETAIL)
6173                 param->fp_max_depth = 1;
6174
6175         if (!param->fp_verbose)
6176                 param->fp_verbose = VERBOSE_DEFAULT;
6177         if (param->fp_quiet)
6178                 param->fp_verbose = VERBOSE_OBJID;
6179
6180         do {
6181                 rc = llapi_getstripe(argv[pathstart], param);
6182         } while (++pathstart < pathend && !rc);
6183
6184         if (rc)
6185                 fprintf(stderr, "error: %s failed for %s.\n",
6186                         argv[0], argv[optind - 1]);
6187         return rc;
6188 }
6189
6190 static int lfs_tgts(int argc, char **argv)
6191 {
6192         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
6193         struct find_param param;
6194         int index = 0, rc = 0;
6195
6196         if (argc > 2)
6197                 return CMD_HELP;
6198
6199         if (argc == 2 && !realpath(argv[1], path)) {
6200                 rc = -errno;
6201                 fprintf(stderr, "error: invalid path '%s': %s\n",
6202                         argv[1], strerror(-rc));
6203                 return rc;
6204         }
6205
6206         while (!llapi_search_mounts(path, index++, mntdir, NULL)) {
6207                 /* Check if we have a mount point */
6208                 if (mntdir[0] == '\0')
6209                         continue;
6210
6211                 memset(&param, 0, sizeof(param));
6212                 if (!strcmp(argv[0], "mdts"))
6213                         param.fp_get_lmv = 1;
6214
6215                 rc = llapi_ostlist(mntdir, &param);
6216                 if (rc) {
6217                         fprintf(stderr, "error: %s: failed on %s\n",
6218                                 argv[0], mntdir);
6219                 }
6220                 if (path[0] != '\0')
6221                         break;
6222                 memset(mntdir, 0, PATH_MAX);
6223         }
6224
6225         return rc;
6226 }
6227
6228 static int lfs_getstripe(int argc, char **argv)
6229 {
6230         struct find_param param = { 0 };
6231
6232         param.fp_max_depth = 1;
6233         return lfs_getstripe_internal(argc, argv, &param);
6234 }
6235
6236 /* functions */
6237 static int lfs_getdirstripe(int argc, char **argv)
6238 {
6239         struct find_param param = { 0 };
6240         struct option long_opts[] = {
6241         { .val = 'c',   .name = "mdt-count",     .has_arg = no_argument },
6242         { .val = 'D',   .name = "default",       .has_arg = no_argument },
6243         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6244         { .val = 'H',   .name = "mdt-hash",      .has_arg = no_argument },
6245         { .val = 'i',   .name = "mdt-index",     .has_arg = no_argument },
6246         { .val = 'm',   .name = "mdt-index",     .has_arg = no_argument },
6247         { .val = 'O',   .name = "obd",           .has_arg = required_argument },
6248         { .val = 'r',   .name = "recursive",     .has_arg = no_argument },
6249         { .val = 'T',   .name = "mdt-count",     .has_arg = no_argument },
6250         { .val = 'v',   .name = "verbose",       .has_arg = no_argument },
6251         { .val = 'X',   .name = "max-inherit",   .has_arg = no_argument },
6252         { .val = 'y',   .name = "yaml",          .has_arg = no_argument },
6253         { .val = LFS_INHERIT_RR_OPT,
6254                         .name = "max-inherit-rr", .has_arg = no_argument },
6255         { .name = NULL } };
6256         int c, rc;
6257
6258         param.fp_get_lmv = 1;
6259
6260         while ((c = getopt_long(argc, argv,
6261                                 "cDhHimO:rtTvXy", long_opts, NULL)) != -1) {
6262                 switch (c) {
6263                 case 'c':
6264                 case 'T':
6265                         param.fp_verbose |= VERBOSE_COUNT;
6266                         break;
6267                 case 'D':
6268                         param.fp_get_default_lmv = 1;
6269                         break;
6270 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6271                 case 't':
6272                         fprintf(stderr,
6273                                 "warning: '-t' deprecated, use '--mdt-hash' or '-H' instead\n");
6274                         /* fallthrough */
6275 #endif
6276                 case 'H':
6277                         param.fp_verbose |= VERBOSE_HASH_TYPE;
6278                         break;
6279                 case 'i': /* fallthrough */
6280                 case 'm':
6281                         param.fp_verbose |= VERBOSE_STRIPE_OFFSET;
6282                         break;
6283                 case 'O':
6284                         if (param.fp_obd_uuid) {
6285                                 fprintf(stderr,
6286                                         "%s: only one obduuid allowed",
6287                                         progname);
6288                                 return CMD_HELP;
6289                         }
6290                         param.fp_obd_uuid = (struct obd_uuid *)optarg;
6291                         break;
6292                 case 'r':
6293                         param.fp_recursive = 1;
6294                         break;
6295                 case 'v':
6296                         param.fp_verbose |= VERBOSE_DETAIL;
6297                         break;
6298                 case 'X':
6299                         param.fp_verbose |= VERBOSE_INHERIT;
6300                         break;
6301                 case LFS_INHERIT_RR_OPT:
6302                         param.fp_verbose |= VERBOSE_INHERIT_RR;
6303                         break;
6304                 case 'y':
6305                         param.fp_yaml = 1;
6306                         break;
6307                 default:
6308                         fprintf(stderr, "%s: unrecognized option '%s'\n",
6309                                 progname, argv[optind - 1]);
6310                         /* fallthrough */
6311                 case 'h':
6312                         return CMD_HELP;
6313                 }
6314         }
6315
6316         if (optind >= argc)
6317                 return CMD_HELP;
6318
6319         if (param.fp_recursive)
6320                 param.fp_max_depth = -1;
6321
6322         if (!param.fp_verbose)
6323                 param.fp_verbose = VERBOSE_DEFAULT;
6324
6325         do {
6326                 rc = llapi_getstripe(argv[optind], &param);
6327         } while (++optind < argc && !rc);
6328
6329         if (rc)
6330                 fprintf(stderr, "error: %s failed for %s.\n",
6331                         argv[0], argv[optind - 1]);
6332         return rc;
6333 }
6334
6335 enum mntdf_flags {
6336         MNTDF_INODES    = 0x0001,
6337         MNTDF_COOKED    = 0x0002,
6338         MNTDF_LAZY      = 0x0004,
6339         MNTDF_VERBOSE   = 0x0008,
6340         MNTDF_SHOW      = 0x0010,
6341         MNTDF_DECIMAL   = 0x0020,
6342 };
6343
6344 #define COOK(value, base)                                       \
6345 ({                                                              \
6346         int radix = 0;                                          \
6347         while (value > base) {                                  \
6348                 value /= base;                                  \
6349                 radix++;                                        \
6350         }                                                       \
6351         radix;                                                  \
6352 })
6353 #define UUF     "%-20s"
6354 #define CSF     "%11s"
6355 #define CDF     "%11llu"
6356 #define HDF     "%8.1f%c"
6357 #define RSF     "%4s"
6358 #define RDF     "%3d%%"
6359
6360 static inline int obd_statfs_ratio(const struct obd_statfs *st, bool inodes)
6361 {
6362         double avail, used, ratio = 0;
6363
6364         if (inodes) {
6365                 avail = st->os_ffree;
6366                 used = st->os_files - st->os_ffree;
6367         } else {
6368                 avail = st->os_bavail;
6369                 used = st->os_blocks - st->os_bfree;
6370         }
6371         if (avail + used > 0)
6372                 ratio = used / (used + avail) * 100;
6373
6374         /* Round up to match df(1) usage percentage */
6375         return (ratio - (int)ratio) > 0 ? (int)(ratio + 1) : (int)ratio;
6376 }
6377
6378 /*
6379  * This is to identify various problem states for "lfs df" if .osn_err = true,
6380  * so only show flags reflecting those states by default. Informational states
6381  * are only shown with "-v" and use lower-case names to distinguish them.
6382  * UNUSED[12] were for "EROFS = 30" until 1.6 but are now available for use.
6383  */
6384 static struct obd_statfs_state_names {
6385         enum obd_statfs_state   osn_state;
6386         const char              osn_name;
6387         bool                    osn_err;
6388 } oss_names[] = {
6389         { .osn_state = OS_STATFS_DEGRADED,   .osn_name = 'D', .osn_err = true },
6390         { .osn_state = OS_STATFS_READONLY,   .osn_name = 'R', .osn_err = true },
6391         { .osn_state = OS_STATFS_NOPRECREATE,.osn_name = 'N', .osn_err = true },
6392         { .osn_state = OS_STATFS_UNUSED1,    .osn_name = '?', .osn_err = true },
6393         { .osn_state = OS_STATFS_UNUSED2,    .osn_name = '?', .osn_err = true },
6394         { .osn_state = OS_STATFS_ENOSPC,     .osn_name = 'S', .osn_err = true },
6395         { .osn_state = OS_STATFS_ENOINO,     .osn_name = 'I', .osn_err = true },
6396         { .osn_state = OS_STATFS_SUM,        .osn_name = 'a', /* aggregate */ },
6397         { .osn_state = OS_STATFS_NONROT,     .osn_name = 'f', /* flash */     },
6398 };
6399
6400 static int showdf(char *mntdir, struct obd_statfs *stat,
6401                   char *uuid, enum mntdf_flags flags,
6402                   char *type, int index, int rc)
6403 {
6404         long long avail, used, total;
6405         int ratio = 0;
6406         char *suffix = flags & MNTDF_DECIMAL ? "kMGTPEZY" : "KMGTPEZY";
6407         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
6408         char tbuf[3 * sizeof(__u64)];
6409         char ubuf[3 * sizeof(__u64)];
6410         char abuf[3 * sizeof(__u64)];
6411         char rbuf[3 * sizeof(__u64)];
6412
6413         if (!uuid || !stat)
6414                 return -EINVAL;
6415
6416         switch (rc) {
6417         case 0:
6418                 if (flags & MNTDF_INODES) {
6419                         avail = stat->os_ffree;
6420                         used = stat->os_files - stat->os_ffree;
6421                         total = stat->os_files;
6422                 } else {
6423                         int shift = flags & MNTDF_COOKED ? 0 : 10;
6424
6425                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
6426                         used  = ((stat->os_blocks - stat->os_bfree) *
6427                                  stat->os_bsize) >> shift;
6428                         total = (stat->os_blocks * stat->os_bsize) >> shift;
6429                 }
6430
6431                 ratio = obd_statfs_ratio(stat, flags & MNTDF_INODES);
6432
6433                 if (flags & MNTDF_COOKED) {
6434                         int base = flags & MNTDF_DECIMAL ? 1000 : 1024;
6435                         double cook_val;
6436                         int i;
6437
6438                         cook_val = (double)total;
6439                         i = COOK(cook_val, base);
6440                         if (i > 0)
6441                                 snprintf(tbuf, sizeof(tbuf), HDF, cook_val,
6442                                          suffix[i - 1]);
6443                         else
6444                                 snprintf(tbuf, sizeof(tbuf), CDF, total);
6445
6446                         cook_val = (double)used;
6447                         i = COOK(cook_val, base);
6448                         if (i > 0)
6449                                 snprintf(ubuf, sizeof(ubuf), HDF, cook_val,
6450                                          suffix[i - 1]);
6451                         else
6452                                 snprintf(ubuf, sizeof(ubuf), CDF, used);
6453
6454                         cook_val = (double)avail;
6455                         i = COOK(cook_val, base);
6456                         if (i > 0)
6457                                 snprintf(abuf, sizeof(abuf), HDF, cook_val,
6458                                          suffix[i - 1]);
6459                         else
6460                                 snprintf(abuf, sizeof(abuf), CDF, avail);
6461                 } else {
6462                         snprintf(tbuf, sizeof(tbuf), CDF, total);
6463                         snprintf(ubuf, sizeof(tbuf), CDF, used);
6464                         snprintf(abuf, sizeof(tbuf), CDF, avail);
6465                 }
6466
6467                 sprintf(rbuf, RDF, ratio);
6468                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
6469                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
6470                 if (type)
6471                         printf("[%s:%d]", type, index);
6472
6473                 if (stat->os_state) {
6474                         uint32_t i;
6475
6476                         printf(" ");
6477                         for (i = 0; i < ARRAY_SIZE(oss_names); i++) {
6478                                 if (oss_names[i].osn_state & stat->os_state &&
6479                                     (oss_names[i].osn_err ||
6480                                      flags & MNTDF_VERBOSE))
6481                                         printf("%c", oss_names[i].osn_name);
6482                         }
6483                 }
6484
6485                 printf("\n");
6486                 break;
6487         case -ENODATA:
6488                 printf(UUF": inactive device\n", uuid);
6489                 break;
6490         default:
6491                 printf(UUF": %s\n", uuid, strerror(-rc));
6492                 break;
6493         }
6494
6495         return 0;
6496 }
6497
6498 struct ll_stat_type {
6499         int   st_op;
6500         char *st_name;
6501 };
6502
6503 #define LL_STATFS_MAX   LOV_MAX_STRIPE_COUNT
6504
6505 struct ll_statfs_data {
6506         int                     sd_index;
6507         struct obd_statfs       sd_st;
6508 };
6509
6510 struct ll_statfs_buf {
6511         int                     sb_count;
6512         struct ll_statfs_data   sb_buf[LL_STATFS_MAX];
6513 };
6514
6515 static int mntdf(char *mntdir, char *fsname, char *pool, enum mntdf_flags flags,
6516                  int ops, struct ll_statfs_buf *lsb)
6517 {
6518         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
6519         struct obd_uuid uuid_buf;
6520         char *poolname = NULL;
6521         struct ll_stat_type types[] = {
6522                 { .st_op = LL_STATFS_LMV,       .st_name = "MDT" },
6523                 { .st_op = LL_STATFS_LOV,       .st_name = "OST" },
6524                 { .st_name = NULL } };
6525         struct ll_stat_type *tp;
6526         __u64 ost_files = 0;
6527         __u64 ost_ffree = 0;
6528         __u32 index;
6529         __u32 type;
6530         int fd;
6531         int rc = 0;
6532         int rc2;
6533
6534         if (pool) {
6535                 poolname = strchr(pool, '.');
6536                 if (poolname) {
6537                         if (strncmp(fsname, pool, strlen(fsname))) {
6538                                 fprintf(stderr, "filesystem name incorrect\n");
6539                                 return -ENODEV;
6540                         }
6541                         poolname++;
6542                 } else
6543                         poolname = pool;
6544         }
6545
6546         fd = open(mntdir, O_RDONLY);
6547         if (fd < 0) {
6548                 rc = -errno;
6549                 fprintf(stderr, "%s: cannot open '%s': %s\n", progname, mntdir,
6550                         strerror(errno));
6551                 return rc;
6552         }
6553
6554         if (flags & MNTDF_SHOW) {
6555                 if (flags & MNTDF_INODES)
6556                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
6557                                "UUID", "Inodes", "IUsed", "IFree",
6558                                "IUse%", "Mounted on");
6559                 else
6560                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
6561                                "UUID",
6562                                flags & MNTDF_COOKED ? "bytes" : "1K-blocks",
6563                                "Used", "Available", "Use%", "Mounted on");
6564         }
6565
6566         for (tp = types; tp->st_name != NULL; tp++) {
6567                 bool have_ost = false;
6568
6569                 if (!(tp->st_op & ops))
6570                         continue;
6571
6572                 for (index = 0; ; index++) {
6573                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
6574                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
6575                         type = flags & MNTDF_LAZY ?
6576                                 tp->st_op | LL_STATFS_NODELAY : tp->st_op;
6577                         rc2 = llapi_obd_fstatfs(fd, type, index,
6578                                                &stat_buf, &uuid_buf);
6579                         if (rc2 == -ENODEV)
6580                                 break;
6581                         if (rc2 == -EAGAIN)
6582                                 continue;
6583                         if (rc2 == -ENODATA) { /* Inactive device, OK. */
6584                                 if (!(flags & MNTDF_VERBOSE))
6585                                         continue;
6586                         } else if (rc2 < 0 && rc == 0) {
6587                                 rc = rc2;
6588                         }
6589
6590                         /*
6591                          * If we have OSTs then don't report MDT block counts.
6592                          * For MDT-only filesystems the expectation is that all
6593                          * layouts have a DoM component.  For filesystems with
6594                          * OSTs, files are not necessarily going to store data
6595                          * on MDTs, and MDT space is limited to a fraction of
6596                          * OST space, so don't include it in the summary.
6597                          */
6598                         if (tp->st_op == LL_STATFS_LOV && !have_ost) {
6599                                 have_ost = true;
6600                                 sum.os_blocks = 0;
6601                                 sum.os_bfree = 0;
6602                                 sum.os_bavail = 0;
6603                         }
6604
6605                         if (poolname && tp->st_op == LL_STATFS_LOV &&
6606                             llapi_search_ost(fsname, poolname,
6607                                              obd_uuid2str(&uuid_buf)) != 1)
6608                                 continue;
6609
6610                         /*
6611                          * the llapi_obd_fstatfs() call may have returned with
6612                          * an error, but if it filled in uuid_buf we will at
6613                          * lease use that to print out a message for that OBD.
6614                          * If we didn't get anything in the uuid_buf, then fill
6615                          * it in so that we can print an error message.
6616                          */
6617                         if (uuid_buf.uuid[0] == '\0')
6618                                 snprintf(uuid_buf.uuid, sizeof(uuid_buf.uuid),
6619                                          "%s%04x", tp->st_name, index);
6620                         if (!rc && lsb) {
6621                                 lsb->sb_buf[lsb->sb_count].sd_index = index;
6622                                 lsb->sb_buf[lsb->sb_count].sd_st = stat_buf;
6623                                 lsb->sb_count++;
6624                         }
6625                         if (flags & MNTDF_SHOW)
6626                                 showdf(mntdir, &stat_buf,
6627                                        obd_uuid2str(&uuid_buf), flags,
6628                                        tp->st_name, index, rc2);
6629
6630                         if (rc2)
6631                                 continue;
6632
6633                         if (tp->st_op == LL_STATFS_LMV) {
6634                                 sum.os_ffree += stat_buf.os_ffree;
6635                                 sum.os_files += stat_buf.os_files;
6636                         } else /* if (tp->st_op == LL_STATFS_LOV) */ {
6637                                 ost_files += stat_buf.os_files;
6638                                 ost_ffree += stat_buf.os_ffree;
6639                         }
6640                         sum.os_blocks += stat_buf.os_blocks *
6641                                          stat_buf.os_bsize;
6642                         sum.os_bfree  += stat_buf.os_bfree *
6643                                          stat_buf.os_bsize;
6644                         sum.os_bavail += stat_buf.os_bavail *
6645                                          stat_buf.os_bsize;
6646                 }
6647         }
6648
6649         close(fd);
6650
6651         /*
6652          * If we have _some_ OSTs, but don't have as many free objects on the
6653          * OST as inodes on the MDTs, reduce the reported number of inodes
6654          * to compensate, so that the "inodes in use" number is correct.
6655          * This should be kept in sync with ll_statfs_internal().
6656          */
6657         if (ost_files && ost_ffree < sum.os_ffree) {
6658                 sum.os_files = (sum.os_files - sum.os_ffree) + ost_ffree;
6659                 sum.os_ffree = ost_ffree;
6660         }
6661         if (flags & MNTDF_SHOW) {
6662                 printf("\n");
6663                 showdf(mntdir, &sum, "filesystem_summary:", flags, NULL, 0, 0);
6664                 printf("\n");
6665         }
6666
6667         return rc;
6668 }
6669
6670 enum {
6671         LAYOUT_INHERIT_UNSET    = -2,
6672 };
6673
6674 /* functions */
6675 static int lfs_setdirstripe(int argc, char **argv)
6676 {
6677         char *dname;
6678         struct lfs_setstripe_args lsa = { 0 };
6679         struct llapi_stripe_param *param = NULL;
6680         __u32 mdts[LMV_MAX_STRIPE_COUNT] = { 0 };
6681         char *end;
6682         int c;
6683         char *mode_opt = NULL;
6684         bool default_stripe = false;
6685         bool delete = false;
6686         bool foreign_mode = false;
6687         mode_t mode = S_IRWXU | S_IRWXG | S_IRWXO;
6688         mode_t previous_mode = 0;
6689         char *xattr = NULL;
6690         __u32 type = LU_FOREIGN_TYPE_SYMLINK, flags = 0;
6691         int max_inherit = LAYOUT_INHERIT_UNSET;
6692         int max_inherit_rr = LAYOUT_INHERIT_UNSET;
6693         struct option long_opts[] = {
6694         { .val = 'c',   .name = "count",        .has_arg = required_argument },
6695         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument },
6696         { .val = 'd',   .name = "delete",       .has_arg = no_argument },
6697         { .val = 'D',   .name = "default",      .has_arg = no_argument },
6698         { .val = 'D',   .name = "default_stripe", .has_arg = no_argument },
6699         { .val = LFS_LAYOUT_FLAGS_OPT,
6700                         .name = "flags",        .has_arg = required_argument },
6701         { .val = LFS_LAYOUT_FOREIGN_OPT,
6702                         .name = "foreign",      .has_arg = optional_argument},
6703         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6704         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
6705 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 17, 53, 0)
6706         { .val = 'i',   .name = "mdt-index",    .has_arg = required_argument },
6707         { .val = 'i',   .name = "mdt",          .has_arg = required_argument },
6708 #else
6709 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
6710         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
6711         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
6712 #endif
6713 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6714         { .val = 'i',   .name = "index",        .has_arg = required_argument },
6715 #endif
6716         { .val = 'o',   .name = "mode",         .has_arg = required_argument },
6717 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6718         { .val = 't',   .name = "hash-type",    .has_arg = required_argument },
6719 #endif
6720         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
6721         { .val = 'x',   .name = "xattr",        .has_arg = required_argument },
6722         { .val = 'X',   .name = "max-inherit",  .has_arg = required_argument },
6723         { .val = LFS_INHERIT_RR_OPT,
6724                         .name = "max-inherit-rr", .has_arg = required_argument},
6725 /* setstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
6726         { .name = NULL } };
6727         int result = 0;
6728
6729         setstripe_args_init(&lsa);
6730
6731         while ((c = getopt_long(argc, argv, "c:dDi:hH:m:o:t:T:x:X:",
6732                                 long_opts, NULL)) >= 0) {
6733                 switch (c) {
6734                 case 0:
6735                         /* Long options. */
6736                         break;
6737                 case 'c':
6738                 case 'T':
6739                         errno = 0;
6740                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
6741                         if (errno != 0 || *end != '\0' ||
6742                             lsa.lsa_stripe_count < -1 ||
6743                             lsa.lsa_stripe_count > LOV_MAX_STRIPE_COUNT) {
6744                                 fprintf(stderr,
6745                                         "%s: invalid stripe count '%s'\n",
6746                                         progname, optarg);
6747                                 return CMD_HELP;
6748                         }
6749                         break;
6750                 case 'd':
6751                         delete = true;
6752                         default_stripe = true;
6753                         break;
6754                 case 'D':
6755                         default_stripe = true;
6756                         break;
6757                 case LFS_LAYOUT_FOREIGN_OPT:
6758                         if (optarg) {
6759                                 /* check pure numeric */
6760                                 type = strtoul(optarg, &end, 0);
6761                                 if (*end) {
6762                                         /* check name */
6763                                         type = check_foreign_type_name(optarg);
6764                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
6765                                                 fprintf(stderr,
6766                                                         "%s %s: unknown foreign type '%s'\n",
6767                                                         progname, argv[0],
6768                                                         optarg);
6769                                                 return CMD_HELP;
6770                                         }
6771                                 } else if (type >= UINT32_MAX) {
6772                                         fprintf(stderr,
6773                                                 "%s %s: invalid foreign type '%s'\n",
6774                                                 progname, argv[0], optarg);
6775                                         return CMD_HELP;
6776                                 }
6777                         }
6778                         foreign_mode = true;
6779                         break;
6780                 case LFS_LAYOUT_FLAGS_OPT:
6781                         errno = 0;
6782                         flags = strtoul(optarg, &end, 16);
6783                         if (errno != 0 || *end != '\0' ||
6784                             flags >= UINT32_MAX) {
6785                                 fprintf(stderr,
6786                                         "%s %s: invalid hex flags '%s'\n",
6787                                         progname, argv[0], optarg);
6788                                 return CMD_HELP;
6789                         }
6790                         if (!foreign_mode) {
6791                                 fprintf(stderr,
6792                                         "%s %s: hex flags must be specified with --foreign option\n",
6793                                         progname, argv[0]);
6794                                 return CMD_HELP;
6795                         }
6796                         break;
6797 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6798                 case 't':
6799                         fprintf(stderr,
6800                                 "warning: '--hash-type' and '-t' deprecated, use '--mdt-hash' or '-H' instead\n");
6801                         /* fallthrough */
6802 #endif
6803                 case 'H':
6804                         lsa.lsa_pattern = check_hashtype(optarg);
6805                         if (lsa.lsa_pattern == 0) {
6806                                 fprintf(stderr,
6807                                         "%s %s: bad stripe hash type '%s'\n",
6808                                         progname, argv[0], optarg);
6809                                 return CMD_HELP;
6810                         }
6811                         break;
6812                 case 'i':
6813 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 17, 53, 0)
6814                 case 'm':
6815 #endif
6816 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6817                         if (strcmp(argv[optind - 1], "--index") == 0)
6818                                 fprintf(stderr,
6819                                         "%s %s: warning: '--index' deprecated, use '--mdt-index' instead\n",
6820                                         progname, argv[0]);
6821 #endif
6822                         lsa.lsa_nr_tgts = parse_targets(mdts,
6823                                                 sizeof(mdts) / sizeof(__u32),
6824                                                 lsa.lsa_nr_tgts, optarg, NULL);
6825                         if (lsa.lsa_nr_tgts < 0) {
6826                                 fprintf(stderr,
6827                                         "%s %s: invalid MDT target(s) '%s'\n",
6828                                         progname, argv[0], optarg);
6829                                 return CMD_HELP;
6830                         }
6831
6832                         lsa.lsa_tgts = mdts;
6833                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
6834                                 lsa.lsa_stripe_off = mdts[0];
6835                         break;
6836 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 15, 53, 0)
6837                 case 'm':
6838                         fprintf(stderr,
6839                                 "warning: '-m' is deprecated, use '--mode' or '-o' instead\n");
6840 #endif
6841                 case 'o':
6842                         mode_opt = optarg;
6843                         break;
6844                 case 'x':
6845                         xattr = optarg;
6846                         break;
6847                 case 'X':
6848                         if (!default_stripe) {
6849                                 fprintf(stderr,
6850                                         "%s %s: '--max-inherit' must be specified with '-D'\n",
6851                                         progname, argv[0]);
6852                                 return CMD_HELP;
6853                         }
6854                         errno = 0;
6855                         max_inherit = strtol(optarg, &end, 10);
6856                         if (errno != 0 || *end != '\0' || max_inherit < -2) {
6857                                 fprintf(stderr,
6858                                         "%s %s: invalid max-inherit '%s'\n",
6859                                         progname, argv[0], optarg);
6860                                 return CMD_HELP;
6861                         }
6862                         if (max_inherit == 0) {
6863                                 max_inherit = LMV_INHERIT_NONE;
6864                         } else if (max_inherit == -1) {
6865                                 max_inherit = LMV_INHERIT_UNLIMITED;
6866                         } else if (max_inherit > LMV_INHERIT_MAX) {
6867                                 fprintf(stderr,
6868                                         "%s %s: max-inherit %d exceeds maximum %u\n",
6869                                         progname, argv[0], max_inherit,
6870                                         LMV_INHERIT_MAX);
6871                                 return CMD_HELP;
6872                         }
6873                         break;
6874                 case LFS_INHERIT_RR_OPT:
6875                         if (!default_stripe) {
6876                                 fprintf(stderr,
6877                                         "%s %s: '--max-inherit-rr' must be specified with '-D'\n",
6878                                         progname, argv[0]);
6879                                 return CMD_HELP;
6880                         }
6881                         errno = 0;
6882                         max_inherit_rr = strtol(optarg, &end, 10);
6883                         if (errno != 0 || *end != '\0' || max_inherit_rr < -2) {
6884                                 fprintf(stderr,
6885                                         "%s %s: invalid max-inherit-rr '%s'\n",
6886                                         progname, argv[0], optarg);
6887                                 return CMD_HELP;
6888                         }
6889                         if (max_inherit_rr == 0) {
6890                                 max_inherit_rr = LMV_INHERIT_RR_NONE;
6891                         } else if (max_inherit_rr == -1) {
6892                                 max_inherit_rr = LMV_INHERIT_RR_UNLIMITED;
6893                         } else if (max_inherit_rr > LMV_INHERIT_RR_MAX) {
6894                                 fprintf(stderr,
6895                                         "%s %s: max-inherit-rr %d exceeds maximum %u\n",
6896                                         progname, argv[0], max_inherit_rr,
6897                                         LMV_INHERIT_RR_MAX);
6898                                 return CMD_HELP;
6899                         }
6900                         break;
6901                 default:
6902                         fprintf(stderr, "%s: unrecognized option '%s'\n",
6903                                 progname, argv[optind - 1]);
6904                         /* fallthrough */
6905                 case 'h':
6906                         return CMD_HELP;
6907                 }
6908         }
6909
6910         if (optind == argc) {
6911                 fprintf(stderr, "%s %s: DIR must be specified\n",
6912                         progname, argv[0]);
6913                 return CMD_HELP;
6914         }
6915
6916         if (xattr && !foreign_mode) {
6917                 /*
6918                  * only print a warning as this is armless and will be
6919                  * ignored
6920                  */
6921                 fprintf(stderr,
6922                         "%s %s: xattr has been specified for non-foreign layout\n",
6923                         progname, argv[0]);
6924         } else if (foreign_mode && !xattr) {
6925                 fprintf(stderr,
6926                         "%s %s: xattr must be provided in foreign mode\n",
6927                         progname, argv[0]);
6928                 return CMD_HELP;
6929         }
6930
6931         if (foreign_mode && (delete || default_stripe || lsa.lsa_nr_tgts ||
6932             lsa.lsa_tgts || setstripe_args_specified(&lsa))) {
6933                 fprintf(stderr,
6934                         "%s %s: only --xattr/--flags/--mode options are valid with --foreign\n",
6935                         progname, argv[0]);
6936                 return CMD_HELP;
6937         }
6938
6939         if (!delete && lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT &&
6940             lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT && !foreign_mode) {
6941                 /* if no parameters set, create directory on least-used MDTs */
6942                 lsa.lsa_stripe_off = -1;
6943                 lsa.lsa_stripe_count = 1;
6944         }
6945
6946         if (delete &&
6947             (lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
6948              lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)) {
6949                 fprintf(stderr,
6950                         "%s %s: cannot specify -d with -c or -i options\n",
6951                         progname, argv[0]);
6952                 return CMD_HELP;
6953         }
6954
6955         if (mode_opt) {
6956                 mode = strtoul(mode_opt, &end, 8);
6957                 if (*end != '\0') {
6958                         fprintf(stderr,
6959                                 "%s %s: bad MODE '%s'\n",
6960                                 progname, argv[0], mode_opt);
6961                         return CMD_HELP;
6962                 }
6963                 previous_mode = umask(0);
6964         }
6965
6966         if (max_inherit_rr != LAYOUT_INHERIT_UNSET &&
6967             lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT &&
6968             lsa.lsa_stripe_off != -1) {
6969                 fprintf(stderr,
6970                         "%s %s: max-inherit-rr is meaningless if stripe offset != -1\n",
6971                         progname, argv[0]);
6972                 return CMD_HELP;
6973         }
6974
6975         /* foreign LMV/dir case */
6976         if (foreign_mode) {
6977                 if (argc > optind + 1) {
6978                         fprintf(stderr,
6979                                 "%s %s: cannot specify multiple foreign dirs\n",
6980                                 progname, argv[0]);
6981                         return CMD_HELP;
6982                 }
6983
6984                 dname = argv[optind];
6985                 result = llapi_dir_create_foreign(dname, mode, type, flags,
6986                                                   xattr);
6987                 if (result != 0)
6988                         fprintf(stderr,
6989                                 "%s mkdir: can't create foreign dir '%s': %s\n",
6990                                 progname, dname, strerror(-result));
6991                 return result;
6992         }
6993
6994         /*
6995          * initialize stripe parameters, in case param is converted to specific,
6996          * i.e, 'lfs mkdir -i -1 -c N', always allocate space for lsp_tgts.
6997          */
6998         param = calloc(1, offsetof(typeof(*param),
6999                        lsp_tgts[lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ?
7000                                 lsa.lsa_stripe_count : lsa.lsa_nr_tgts]));
7001         if (!param) {
7002                 fprintf(stderr,
7003                         "%s %s: cannot allocate memory for parameters: %s\n",
7004                         progname, argv[0], strerror(ENOMEM));
7005                 return CMD_HELP;
7006         }
7007
7008         /* if "lfs setdirstripe -D -i -1" is used, assume 1-stripe directory */
7009         if (default_stripe && lsa.lsa_stripe_off == -1 &&
7010             (lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT ||
7011              lsa.lsa_stripe_count == 0))
7012                 lsa.lsa_stripe_count = 1;
7013         if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
7014                 param->lsp_stripe_count = lsa.lsa_stripe_count;
7015         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
7016                 param->lsp_stripe_offset = -1;
7017         else
7018                 param->lsp_stripe_offset = lsa.lsa_stripe_off;
7019         if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
7020                 param->lsp_stripe_pattern = lsa.lsa_pattern;
7021         else
7022                 param->lsp_stripe_pattern = LMV_HASH_TYPE_UNKNOWN;
7023         param->lsp_pool = lsa.lsa_pool_name;
7024         param->lsp_is_specific = false;
7025         if (default_stripe) {
7026                 if (max_inherit == LAYOUT_INHERIT_UNSET)
7027                         max_inherit = LMV_INHERIT_DEFAULT;
7028                 if (max_inherit_rr == LAYOUT_INHERIT_UNSET)
7029                         max_inherit_rr = LMV_INHERIT_RR_DEFAULT;
7030                 param->lsp_max_inherit = max_inherit;
7031                 param->lsp_max_inherit_rr = max_inherit_rr;
7032         }
7033         if (strcmp(argv[0], "mkdir") == 0)
7034                 param->lsp_is_create = true;
7035         if (lsa.lsa_nr_tgts > 1) {
7036                 if (lsa.lsa_stripe_count > 0 &&
7037                     lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
7038                     lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
7039                         fprintf(stderr,
7040                                 "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
7041                                 argv[0], lsa.lsa_stripe_count,
7042                                 lsa.lsa_nr_tgts);
7043                         free(param);
7044                         return CMD_HELP;
7045                 }
7046
7047                 param->lsp_is_specific = true;
7048                 param->lsp_stripe_count = lsa.lsa_nr_tgts;
7049                 memcpy(param->lsp_tgts, mdts, sizeof(*mdts) * lsa.lsa_nr_tgts);
7050         }
7051
7052         dname = argv[optind];
7053         do {
7054                 if (default_stripe) {
7055                         result = llapi_dir_set_default_lmv(dname, param);
7056                         if (result)
7057                                 fprintf(stderr,
7058                                         "%s setdirstripe: cannot set default stripe on dir '%s': %s\n",
7059                                         progname, dname, strerror(-result));
7060                         continue;
7061                 }
7062
7063                 result = llapi_dir_create(dname, mode, param);
7064                 if (result)
7065                         fprintf(stderr,
7066                                 "%s setdirstripe: cannot create dir '%s': %s\n",
7067                                 progname, dname, strerror(-result));
7068         } while (!result && (dname = argv[++optind]));
7069
7070         if (mode_opt)
7071                 umask(previous_mode);
7072
7073         free(param);
7074         return result;
7075 }
7076
7077 /* functions */
7078 static int lfs_rmentry(int argc, char **argv)
7079 {
7080         char *dname;
7081         int   index;
7082         int   result = 0;
7083
7084         if (argc <= 1) {
7085                 fprintf(stderr, "error: %s: missing dirname\n",
7086                         argv[0]);
7087                 return CMD_HELP;
7088         }
7089
7090         index = 1;
7091         dname = argv[index];
7092         while (dname) {
7093                 result = llapi_direntry_remove(dname);
7094                 if (result) {
7095                         fprintf(stderr,
7096                                 "error: %s: remove dir entry '%s' failed\n",
7097                                 argv[0], dname);
7098                         break;
7099                 }
7100                 dname = argv[++index];
7101         }
7102         return result;
7103 }
7104
7105 static int lfs_unlink_foreign(int argc, char **argv)
7106 {
7107         char *name;
7108         int   index;
7109         int   result = 0;
7110
7111         if (argc <= 1) {
7112                 fprintf(stderr, "error: %s: missing pathname\n",
7113                         argv[0]);
7114                 return CMD_HELP;
7115         }
7116
7117         index = 1;
7118         name = argv[index];
7119         while (name != NULL) {
7120                 result = llapi_unlink_foreign(name);
7121                 if (result) {
7122                         fprintf(stderr,
7123                                 "error: %s: unlink foreign entry '%s' failed\n",
7124                                 argv[0], name);
7125                         break;
7126                 }
7127                 name = argv[++index];
7128         }
7129         return result;
7130 }
7131
7132 static int lfs_mv(int argc, char **argv)
7133 {
7134         struct lmv_user_md lmu = { LMV_USER_MAGIC };
7135         struct find_param param = {
7136                 .fp_max_depth = -1,
7137                 .fp_mdt_index = -1,
7138         };
7139         char *end;
7140         int c;
7141         int rc = 0;
7142         struct option long_opts[] = {
7143         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
7144         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
7145         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
7146         { .name = NULL } };
7147
7148         while ((c = getopt_long(argc, argv, "m:M:v", long_opts, NULL)) != -1) {
7149                 switch (c) {
7150 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
7151                 case 'M':
7152                         fprintf(stderr,
7153                                 "warning: '-M' deprecated, use '--mdt-index' or '-m' instead\n");
7154 #endif
7155                 case 'm':
7156                         errno = 0;
7157                         lmu.lum_stripe_offset = strtoul(optarg, &end, 0);
7158                         if (errno != 0 || *end != '\0' ||
7159                             lmu.lum_stripe_offset >= UINT32_MAX) {
7160                                 fprintf(stderr, "%s mv: bad MDT index '%s'\n",
7161                                         progname, optarg);
7162                                 return CMD_HELP;
7163                         }
7164                         break;
7165                 case 'v':
7166                         param.fp_verbose = VERBOSE_DETAIL;
7167                         break;
7168                 default:
7169                         fprintf(stderr, "%s mv: unrecognized option '%s'\n",
7170                                 progname, argv[optind - 1]);
7171                         return CMD_HELP;
7172                 }
7173         }
7174
7175         if (lmu.lum_stripe_offset == LMV_OFFSET_DEFAULT) {
7176                 fprintf(stderr, "%s mv: MDT index must be specified\n",
7177                         progname);
7178                 return CMD_HELP;
7179         }
7180
7181         if (optind >= argc) {
7182                 fprintf(stderr, "%s mv: DIR must be specified\n", progname);
7183                 return CMD_HELP;
7184         }
7185
7186         lmu.lum_hash_type = LMV_HASH_TYPE_UNKNOWN;
7187
7188         /* initialize migrate mdt parameters */
7189         param.fp_lmv_md = &lmu;
7190         param.fp_migrate = 1;
7191         rc = llapi_migrate_mdt(argv[optind], &param);
7192         if (rc != 0)
7193                 fprintf(stderr, "%s mv: cannot migrate '%s' to MDT%04x: %s\n",
7194                         progname, argv[optind], lmu.lum_stripe_offset,
7195                         strerror(-rc));
7196         return rc;
7197 }
7198
7199 static int lfs_osts(int argc, char **argv)
7200 {
7201         return lfs_tgts(argc, argv);
7202 }
7203
7204 static int lfs_mdts(int argc, char **argv)
7205 {
7206         return lfs_tgts(argc, argv);
7207 }
7208
7209 static int lfs_df(int argc, char **argv)
7210 {
7211         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
7212         enum mntdf_flags flags = MNTDF_SHOW;
7213         int ops = LL_STATFS_LMV | LL_STATFS_LOV;
7214         int c, rc = 0, index = 0;
7215         char fsname[PATH_MAX] = "", *pool_name = NULL;
7216         struct option long_opts[] = {
7217         { .val = 'h',   .name = "human-readable", .has_arg = no_argument },
7218         { .val = 'H',   .name = "si",           .has_arg = no_argument },
7219         { .val = 'i',   .name = "inodes",       .has_arg = no_argument },
7220         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
7221         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
7222         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
7223         { .name = NULL} };
7224
7225         while ((c = getopt_long(argc, argv, "hHilp:v", long_opts, NULL)) != -1) {
7226                 switch (c) {
7227                 case 'h':
7228                         flags = (flags & ~MNTDF_DECIMAL) | MNTDF_COOKED;
7229                         break;
7230                 case 'H':
7231                         flags |= MNTDF_COOKED | MNTDF_DECIMAL;
7232                         break;
7233                 case 'i':
7234                         flags |= MNTDF_INODES;
7235                         break;
7236                 case 'l':
7237                         flags |= MNTDF_LAZY;
7238                         break;
7239                 case 'p':
7240                         pool_name = optarg;
7241                         break;
7242                 case 'v':
7243                         flags |= MNTDF_VERBOSE;
7244                         break;
7245                 default:
7246                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7247                                 progname, argv[optind - 1]);
7248                         return CMD_HELP;
7249                 }
7250         }
7251         if (optind < argc && !realpath(argv[optind], path)) {
7252                 rc = -errno;
7253                 fprintf(stderr, "%s: invalid path '%s': %s\n",
7254                         progname, argv[optind], strerror(-rc));
7255                 return rc;
7256         }
7257
7258         while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7259                 /* Check if we have a mount point */
7260                 if (mntdir[0] == '\0')
7261                         continue;
7262
7263                 rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
7264                 if (rc || path[0] != '\0')
7265                         break;
7266                 fsname[0] = '\0'; /* avoid matching in next loop */
7267                 mntdir[0] = '\0'; /* avoid matching in next loop */
7268         }
7269
7270         return rc;
7271 }
7272
7273 static int print_instance(const char *mntdir, char *buf, size_t buflen,
7274                           bool opt_instance, bool opt_fsname, bool opt_mntdir)
7275 {
7276         int rc = 0;
7277
7278         if (opt_fsname == opt_instance) { /* both true or both false */
7279                 rc = llapi_getname(mntdir, buf, buflen);
7280         } else if (opt_fsname) {
7281                 /*
7282                  * llapi_search_mounts() fills @buf with fsname, but that is not
7283                  * called if explicit paths are specified on the command-line
7284                  */
7285                 if (buf[0] == '\0')
7286                         rc = llapi_get_fsname(mntdir, buf, buflen);
7287         } else /* if (opt_instance) */ {
7288                 rc = llapi_get_instance(mntdir, buf, buflen);
7289         }
7290
7291         if (rc < 0) {
7292                 fprintf(stderr, "cannot get instance for '%s': %s\n",
7293                         mntdir, strerror(-rc));
7294                 return rc;
7295         }
7296
7297         if (opt_mntdir)
7298                 printf("%s %s\n", buf, mntdir);
7299         else
7300                 printf("%s\n", buf);
7301
7302         return 0;
7303 }
7304
7305 static int lfs_getname(int argc, char **argv)
7306 {
7307         struct option long_opts[] = {
7308         { .val = 'h',   .name = "help",         .has_arg = no_argument },
7309         { .val = 'i',   .name = "instance",     .has_arg = no_argument },
7310         { .val = 'n',   .name = "fsname",       .has_arg = no_argument },
7311         { .name = NULL} };
7312         bool opt_instance = false, opt_fsname = false;
7313         char fsname[PATH_MAX] = "";
7314         int rc = 0, rc2, c;
7315
7316         while ((c = getopt_long(argc, argv, "hin", long_opts, NULL)) != -1) {
7317                 switch (c) {
7318                 case 'i':
7319                         opt_instance = true;
7320                         break;
7321                 case 'n':
7322                         opt_fsname = true;
7323                         break;
7324                 default:
7325                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7326                                 progname, argv[optind - 1]);
7327                         /* fallthrough */
7328                 case 'h':
7329                         return CMD_HELP;
7330                 }
7331         }
7332
7333         if (optind == argc) { /* no paths specified, get all paths. */
7334                 char mntdir[PATH_MAX] = "", path[PATH_MAX] = "";
7335                 int index = 0;
7336
7337                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
7338                         rc2 = print_instance(mntdir, fsname, sizeof(fsname),
7339                                              opt_instance, opt_fsname, true);
7340                         if (!rc)
7341                                 rc = rc2;
7342                         path[0] = fsname[0] = mntdir[0] = '\0';
7343                 }
7344         } else { /* paths specified, only attempt to search these. */
7345                 bool opt_mntdir;
7346
7347                 /* if only one path is given, print only requested info */
7348                 opt_mntdir = argc - optind > 1 || (opt_instance == opt_fsname);
7349
7350                 for (; optind < argc; optind++) {
7351                         rc2 = print_instance(argv[optind], fsname,
7352                                              sizeof(fsname), opt_instance,
7353                                              opt_fsname, opt_mntdir);
7354                         if (!rc)
7355                                 rc = rc2;
7356                         fsname[0] = '\0';
7357                 }
7358         }
7359
7360         return rc;
7361 }
7362
7363 static int lfs_check(int argc, char **argv)
7364 {
7365         char mntdir[PATH_MAX] = {'\0'};
7366         int num_types = 1;
7367         char *obd_types[3];
7368         char obd_type1[4];
7369         char obd_type2[4];
7370         char obd_type3[4];
7371         int rc;
7372
7373         if (argc != 2) {
7374                 fprintf(stderr, "%s check: server type must be specified\n",
7375                         progname);
7376                 return CMD_HELP;
7377         }
7378
7379         obd_types[0] = obd_type1;
7380         obd_types[1] = obd_type2;
7381         obd_types[2] = obd_type3;
7382
7383         if (strcmp(argv[1], "osts") == 0) {
7384                 strcpy(obd_types[0], "osc");
7385         } else if (strcmp(argv[1], "mdts") == 0 ||
7386                    strcmp(argv[1], "mds") == 0) {
7387                 strcpy(obd_types[0], "mdc");
7388         } else if (strcmp(argv[1], "mgts") == 0) {
7389                 strcpy(obd_types[0], "mgc");
7390         } else if (strcmp(argv[1], "all") == 0 ||
7391                    strcmp(argv[1], "servers") == 0) {
7392                 num_types = 3;
7393                 strcpy(obd_types[0], "osc");
7394                 strcpy(obd_types[1], "mdc");
7395                 strcpy(obd_types[2], "mgc");
7396         } else {
7397                 fprintf(stderr, "%s check: unrecognized option '%s'\n",
7398                         progname, argv[1]);
7399                 return CMD_HELP;
7400         }
7401
7402         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
7403         if (rc < 0 || mntdir[0] == '\0') {
7404                 fprintf(stderr,
7405                         "%s check: cannot find mounted Lustre filesystem: %s\n",
7406                         progname, (rc < 0) ? strerror(-rc) : strerror(ENODEV));
7407                 return rc;
7408         }
7409
7410         rc = llapi_target_check(num_types, obd_types, mntdir);
7411         if (rc)
7412                 fprintf(stderr, "%s check: cannot check target '%s': %s\n",
7413                         progname, argv[1], strerror(-rc));
7414
7415         return rc;
7416 }
7417
7418 #ifdef HAVE_SYS_QUOTA_H
7419 #define ADD_OVERFLOW(a, b) \
7420                      ((((a) + (b)) < (a)) ? \
7421                       ((a) = ULONG_MAX) : ((a) = (a) + (b)))
7422
7423 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
7424  * returns the value or ULONG_MAX on integer overflow or incorrect format
7425  * Notes:
7426  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
7427  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
7428  *        3. empty integer value is interpreted as 0
7429  */
7430 static unsigned long str2sec(const char *timestr)
7431 {
7432         const char spec[] = "smhdw";
7433         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
7434         unsigned long val = 0;
7435         char *tail;
7436
7437         if (strpbrk(timestr, spec) == NULL) {
7438                 /*
7439                  * no specifiers inside the time string,
7440                  * should treat it as an integer value
7441                  */
7442                 val = strtoul(timestr, &tail, 10);
7443                 return *tail ? ULONG_MAX : val;
7444         }
7445
7446         /* format string is XXwXXdXXhXXmXXs */
7447         while (*timestr) {
7448                 unsigned long v;
7449                 int ind;
7450                 char *ptr;
7451
7452                 v = strtoul(timestr, &tail, 10);
7453                 if (v == ULONG_MAX || *tail == '\0')
7454                         /*
7455                          * value too large (ULONG_MAX or more)
7456                          * or missing specifier
7457                          */
7458                         goto error;
7459
7460                 ptr = strchr(spec, *tail);
7461                 if (!ptr)
7462                         /* unknown specifier */
7463                         goto error;
7464
7465                 ind = ptr - spec;
7466
7467                 /* check if product will overflow the type */
7468                 if (!(v < ULONG_MAX / mult[ind]))
7469                         goto error;
7470
7471                 ADD_OVERFLOW(val, mult[ind] * v);
7472                 if (val == ULONG_MAX)
7473                         goto error;
7474
7475                 timestr = tail + 1;
7476         }
7477
7478         return val;
7479
7480 error:
7481         return ULONG_MAX;
7482 }
7483
7484 #define ARG2ULL(nr, str, def_units)                                     \
7485 do {                                                                    \
7486         unsigned long long limit, units = def_units;                    \
7487         int rc;                                                         \
7488                                                                         \
7489         rc = llapi_parse_size(str, &limit, &units, 1);                  \
7490         if (rc < 0) {                                                   \
7491                 fprintf(stderr, "%s: invalid limit '%s'\n",             \
7492                         progname, str);                                 \
7493                 return CMD_HELP;                                        \
7494         }                                                               \
7495         nr = limit;                                                     \
7496 } while (0)
7497
7498 static inline int has_times_option(int argc, char **argv)
7499 {
7500         int i;
7501
7502         for (i = 1; i < argc; i++)
7503                 if (!strcmp(argv[i], "-t"))
7504                         return 1;
7505
7506         return 0;
7507 }
7508
7509 static inline int lfs_verify_poolarg(char *pool)
7510 {
7511         if (strnlen(optarg, LOV_MAXPOOLNAME + 1) > LOV_MAXPOOLNAME) {
7512                 fprintf(stderr,
7513                         "Pool name '%.*s' is longer than %d\n",
7514                         LOV_MAXPOOLNAME, pool, LOV_MAXPOOLNAME);
7515                 return 1;
7516         }
7517         return 0;
7518 }
7519
7520 int lfs_setquota_times(int argc, char **argv, struct if_quotactl *qctl)
7521 {
7522         int c, rc;
7523         char *mnt, *obd_type = (char *)qctl->obd_type;
7524         struct obd_dqblk *dqb = &qctl->qc_dqblk;
7525         struct obd_dqinfo *dqi = &qctl->qc_dqinfo;
7526         struct option long_opts[] = {
7527         { .val = 'b',   .name = "block-grace",  .has_arg = required_argument },
7528         { .val = 'g',   .name = "group",        .has_arg = no_argument },
7529         { .val = 'h',   .name = "help",         .has_arg = no_argument },
7530         { .val = 'i',   .name = "inode-grace",  .has_arg = required_argument },
7531         { .val = 'p',   .name = "projid",       .has_arg = no_argument },
7532         { .val = 't',   .name = "times",        .has_arg = no_argument },
7533         { .val = 'u',   .name = "user",         .has_arg = no_argument },
7534         { .val = LFS_POOL_OPT,
7535                         .name = "pool",         .has_arg = required_argument },
7536         { .name = NULL } };
7537         int qtype;
7538
7539         qctl->qc_cmd  = LUSTRE_Q_SETINFO;
7540         qctl->qc_type = ALLQUOTA;
7541
7542         while ((c = getopt_long(argc, argv, "b:ghi:ptu",
7543                                 long_opts, NULL)) != -1) {
7544                 switch (c) {
7545                 case 'u':
7546                         qtype = USRQUOTA;
7547                         goto quota_type;
7548                 case 'g':
7549                         qtype = GRPQUOTA;
7550                         goto quota_type;
7551                 case 'p':
7552                         qtype = PRJQUOTA;
7553 quota_type:
7554                         if (qctl->qc_type != ALLQUOTA) {
7555                                 fprintf(stderr,
7556                                         "%s: -u/g/p cannot be used more than once\n",
7557                                         progname);
7558                                 return CMD_HELP;
7559                         }
7560                         qctl->qc_type = qtype;
7561                         break;
7562                 case 'b':
7563                         if (strncmp(optarg, NOTIFY_GRACE,
7564                                     strlen(NOTIFY_GRACE)) == 0) {
7565                                 dqi->dqi_bgrace = NOTIFY_GRACE_TIME;
7566                         } else {
7567                                 dqi->dqi_bgrace = str2sec(optarg);
7568                                 if (dqi->dqi_bgrace >= NOTIFY_GRACE_TIME) {
7569                                         fprintf(stderr,
7570                                                 "%s: bad block-grace: %s\n",
7571                                                 progname, optarg);
7572                                         return CMD_HELP;
7573                                 }
7574                         }
7575                         dqb->dqb_valid |= QIF_BTIME;
7576                         break;
7577                 case 'i':
7578                         if (strncmp(optarg, NOTIFY_GRACE,
7579                                     strlen(NOTIFY_GRACE)) == 0) {
7580                                 dqi->dqi_igrace = NOTIFY_GRACE_TIME;
7581                         } else {
7582                                 dqi->dqi_igrace = str2sec(optarg);
7583                                 if (dqi->dqi_igrace >= NOTIFY_GRACE_TIME) {
7584                                         fprintf(stderr,
7585                                                 "%s: bad inode-grace: %s\n",
7586                                                 progname, optarg);
7587                                         return CMD_HELP;
7588                                 }
7589                         }
7590                         dqb->dqb_valid |= QIF_ITIME;
7591                         break;
7592                 case 't': /* Yes, of course! */
7593                         break;
7594                 case LFS_POOL_OPT:
7595                         if (lfs_verify_poolarg(optarg))
7596                                 return -1;
7597                         strncpy(qctl->qc_poolname, optarg, LOV_MAXPOOLNAME);
7598                         qctl->qc_cmd  = LUSTRE_Q_SETINFOPOOL;
7599                         break;
7600                 /* getopt prints error message for us when opterr != 0 */
7601                 default:
7602                         fprintf(stderr, "%s: unrecognized option '%s'\n",
7603                                 progname, argv[optind - 1]);
7604                         /* fallthrough */
7605                 case 'h':
7606                         return CMD_HELP;
7607                 }
7608         }
7609
7610         if (qctl->qc_type == ALLQUOTA) {
7611                 fprintf(stderr, "%s: neither -u, -g nor -p specified\n",
7612                         progname);
7613                 return CMD_HELP;
7614         }
7615
7616         if (optind != argc - 1) {
7617                 fprintf(stderr, "%s: unexpected parameter '%s'\n",
7618                         progname, argv[optind + 1]);
7619                 return CMD_HELP;
7620         }
7621
7622         mnt = argv[optind];
7623         rc = llapi_quotactl(mnt, qctl);
7624         if (rc) {
7625                 if (*obd_type)
7626                         fprintf(stderr, "%s %s ", obd_type,
7627                                 obd_uuid2str(&qctl->obd_uuid));
7628                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
7629                 return rc;
7630         }
7631
7632         return 0;
7633 }
7634
7635 #define BSLIMIT (1 << 0)
7636 #define BHLIMIT (1 << 1)
7637 #define ISLIMIT (1 << 2)
7638 #define IHLIMIT (1 << 3)
7639
7640 int lfs_setquota(int argc, char **argv)
7641 {
7642         int c, rc = 0;
7643         struct if_quotactl *qctl;
7644         char *mnt, *obd_type;
7645         struct obd_dqblk *dqb;
7646         struct option long_opts[] = {
7647         { .val = 'b',   .name = "block-softlimit",
7648                                                 .has_arg = required_argument },
7649         { .val = 'B',   .name = "block-hardlimit",
7650                                                 .has_arg = required_argument },
7651         { .val = 'd',   .name = "default",      .has_arg = no_argument },
7652         { .val = 'g',   .name = "group",        .has_arg = required_argument },
7653         { .val = 'G',   .name = "default-grp",  .has_arg = no_argument },
7654         { .val = 'h',   .name = "help",         .has_arg = no_argument },
7655         { .val = 'i',   .name = "inode-softlimit",
7656                                                 .has_arg = required_argument },
7657         { .val = 'I',   .name = "inode-hardlimit",
7658                                                 .has_arg = required_argument },
7659         { .val = 'p',   .name = "projid",       .has_arg = required_argument },
7660         { .val = 'P',   .name = "default-prj",  .has_arg = no_argument },
7661         { .val = 'u',   .name = "user",         .has_arg = required_argument },
7662         { .val = 'U',   .name = "default-usr",  .has_arg = no_argument },
7663         { .val = LFS_POOL_OPT,
7664                         .name = "pool",         .has_arg = required_argument },
7665         { .name = NULL } };
7666         unsigned int limit_mask = 0;
7667         bool use_default = false;
7668         int qtype, qctl_len;
7669
7670         qctl_len = sizeof(*qctl) + LOV_MAXPOOLNAME + 1;
7671         qctl = malloc(qctl_len);
7672         if (!qctl)
7673                 return -ENOMEM;
7674
7675         memset(qctl, 0, qctl_len);
7676         obd_type = (char *)qctl->obd_type;
7677         dqb = &qctl->qc_dqblk;
7678
7679         if (has_times_option(argc, argv)) {
7680                 rc = lfs_setquota_times(argc, argv, qctl);
7681                 goto out;
7682         }
7683
7684         qctl->qc_cmd  = LUSTRE_Q_SETQUOTA;
7685         qctl->qc_type = ALLQUOTA; /* ALLQUOTA makes no sense for setquota,
7686                                    * so it can be used as a marker that qc_type
7687                                    * isn't reinitialized from command line
7688                                    */
7689
7690         while ((c = getopt_long(argc, argv, "b:B:dg:Ghi:I:p:Pu:U",
7691                 long_opts, NULL)) != -1) {
7692                 switch (c) {
7693                 case 'U':
7694                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7695                         qtype = USRQUOTA;
7696                         qctl->qc_id = 0;
7697                         goto quota_type_def;
7698                 case 'u':
7699                         qtype = USRQUOTA;
7700                         rc = name2uid(&qctl->qc_id, optarg);
7701                         goto quota_type;
7702                 case 'G':
7703                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7704                         qtype = GRPQUOTA;
7705                         qctl->qc_id = 0;
7706                         goto quota_type_def;
7707                 case 'g':
7708                         qtype = GRPQUOTA;
7709                         rc = name2gid(&qctl->qc_id, optarg);
7710                         goto quota_type;
7711                 case 'P':
7712                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7713                         qtype = PRJQUOTA;
7714                         qctl->qc_id = 0;
7715                         goto quota_type_def;
7716                 case 'p':
7717                         qtype = PRJQUOTA;
7718                         rc = name2projid(&qctl->qc_id, optarg);
7719 quota_type:
7720                         if (rc) {
7721                                 if (str2quotaid(&qctl->qc_id, optarg)) {
7722                                         fprintf(stderr,
7723                                                 "%s setquota: invalid id '%s'\n",
7724                                                 progname, optarg);
7725                                         rc = -1;
7726                                         goto out;
7727                                 }
7728                         }
7729
7730                         if (qctl->qc_id == 0) {
7731                                 fprintf(stderr,
7732                                         "%s setquota: can't set quota for root usr/group/project.\n",
7733                                         progname);
7734                                 rc = -1;
7735                                 goto out;
7736                         }
7737
7738 quota_type_def:
7739                         if (qctl->qc_type != ALLQUOTA) {
7740                                 fprintf(stderr,
7741                                         "%s setquota: only one of -u, -U, -g, -G, -p or -P may be specified\n",
7742                                         progname);
7743                                 rc = CMD_HELP;
7744                                 goto out;
7745                         }
7746                         qctl->qc_type = qtype;
7747                         break;
7748                 case 'd':
7749                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7750                         use_default = true;
7751                         break;
7752                 case 'b':
7753                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
7754                         dqb->dqb_bsoftlimit >>= 10;
7755                         limit_mask |= BSLIMIT;
7756                         if (dqb->dqb_bsoftlimit &&
7757                             dqb->dqb_bsoftlimit <= 1024) /* <= 1M? */
7758                                 fprintf(stderr,
7759                                         "%s setquota: warning: block softlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
7760                                         progname,
7761                                         (unsigned long long)dqb->dqb_bsoftlimit,
7762                                         progname);
7763                         break;
7764                 case 'B':
7765                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
7766                         dqb->dqb_bhardlimit >>= 10;
7767                         limit_mask |= BHLIMIT;
7768                         if (dqb->dqb_bhardlimit &&
7769                             dqb->dqb_bhardlimit <= 1024) /* <= 1M? */
7770                                 fprintf(stderr,
7771                                         "%s setquota: warning: block hardlimit '%llu' smaller than minimum qunit size\n"
7772                                         "See '%s help setquota' or Lustre manual for details\n",
7773                                         progname,
7774                                         (unsigned long long)dqb->dqb_bhardlimit,
7775                                         progname);
7776                         break;
7777                 case 'i':
7778                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
7779                         limit_mask |= ISLIMIT;
7780                         if (dqb->dqb_isoftlimit &&
7781                             dqb->dqb_isoftlimit <= 1024) /* <= 1K inodes? */
7782                                 fprintf(stderr,
7783                                         "%s setquota: warning: inode softlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
7784                                         progname,
7785                                         (unsigned long long)dqb->dqb_isoftlimit,
7786                                         progname);
7787                         break;
7788                 case 'I':
7789                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
7790                         limit_mask |= IHLIMIT;
7791                         if (dqb->dqb_ihardlimit &&
7792                             dqb->dqb_ihardlimit <= 1024) /* <= 1K inodes? */
7793                                 fprintf(stderr,
7794                                         "%s setquota: warning: inode hardlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
7795                                         progname,
7796                                         (unsigned long long)dqb->dqb_ihardlimit,
7797                                         progname);
7798                         break;
7799                 case LFS_POOL_OPT:
7800                         if (lfs_verify_poolarg(optarg)) {
7801                                 rc = -1;
7802                                 goto out;
7803                         }
7804                         strncpy(qctl->qc_poolname, optarg, LOV_MAXPOOLNAME);
7805                         qctl->qc_cmd = qctl->qc_cmd == LUSTRE_Q_SETDEFAULT ?
7806                                                 LUSTRE_Q_SETDEFAULT_POOL :
7807                                                 LUSTRE_Q_SETQUOTAPOOL;
7808                         break;
7809                 default:
7810                         fprintf(stderr,
7811                                 "%s setquota: unrecognized option '%s'\n",
7812                                 progname, argv[optind - 1]);
7813                         /* fallthrough */
7814                 case 'h':
7815                         rc = CMD_HELP;
7816                         goto out;
7817                 }
7818         }
7819
7820         if (qctl->qc_type == ALLQUOTA) {
7821                 fprintf(stderr,
7822                         "%s setquota: either -u or -g must be specified\n",
7823                         progname);
7824                 rc = CMD_HELP;
7825                 goto out;
7826         }
7827
7828         if (!use_default && limit_mask == 0) {
7829                 fprintf(stderr,
7830                         "%s setquota: at least one limit must be specified\n",
7831                         progname);
7832                 rc = CMD_HELP;
7833                 goto out;
7834         }
7835
7836         if (use_default && limit_mask != 0) {
7837                 fprintf(stderr,
7838                         "%s setquota: limits should not be specified when using default quota\n",
7839                         progname);
7840                 rc = CMD_HELP;
7841                 goto out;
7842         }
7843
7844         if (use_default && qctl->qc_id == 0) {
7845                 fprintf(stderr,
7846                         "%s setquota: can not set default quota for root user/group/project\n",
7847                         progname);
7848                 rc = CMD_HELP;
7849                 goto out;
7850         }
7851
7852         if (optind != argc - 1) {
7853                 fprintf(stderr,
7854                         "%s setquota: filesystem not specified or unexpected argument '%s'\n",
7855                         progname, argv[optind]);
7856                 rc = CMD_HELP;
7857                 goto out;
7858         }
7859
7860         mnt = argv[optind];
7861
7862         if (use_default) {
7863                 dqb->dqb_bhardlimit = 0;
7864                 dqb->dqb_bsoftlimit = 0;
7865                 dqb->dqb_ihardlimit = 0;
7866                 dqb->dqb_isoftlimit = 0;
7867                 dqb->dqb_itime = 0;
7868                 dqb->dqb_btime = 0;
7869                 dqb->dqb_valid |= QIF_LIMITS | QIF_TIMES;
7870                 /* do not set inode limits for Pool Quotas */
7871                 if (qctl->qc_cmd  == LUSTRE_Q_SETDEFAULT_POOL)
7872                         dqb->dqb_valid ^= QIF_ILIMITS | QIF_ITIME;
7873         } else if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
7874                    (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
7875                 /* sigh, we can't just set blimits/ilimits */
7876                 struct if_quotactl tmp_qctl = {.qc_cmd  = LUSTRE_Q_GETQUOTA,
7877                                                .qc_type = qctl->qc_type,
7878                                                .qc_id   = qctl->qc_id};
7879
7880                 rc = llapi_quotactl(mnt, &tmp_qctl);
7881                 if (rc < 0)
7882                         goto out;
7883
7884                 if (!(limit_mask & BHLIMIT))
7885                         dqb->dqb_bhardlimit = tmp_qctl.qc_dqblk.dqb_bhardlimit;
7886                 if (!(limit_mask & BSLIMIT))
7887                         dqb->dqb_bsoftlimit = tmp_qctl.qc_dqblk.dqb_bsoftlimit;
7888                 if (!(limit_mask & IHLIMIT))
7889                         dqb->dqb_ihardlimit = tmp_qctl.qc_dqblk.dqb_ihardlimit;
7890                 if (!(limit_mask & ISLIMIT))
7891                         dqb->dqb_isoftlimit = tmp_qctl.qc_dqblk.dqb_isoftlimit;
7892
7893                 /* Keep grace times if we have got no softlimit arguments */
7894                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
7895                         dqb->dqb_valid |= QIF_BTIME;
7896                         dqb->dqb_btime = tmp_qctl.qc_dqblk.dqb_btime;
7897                 }
7898
7899                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
7900                         dqb->dqb_valid |= QIF_ITIME;
7901                         dqb->dqb_itime = tmp_qctl.qc_dqblk.dqb_itime;
7902                 }
7903         }
7904
7905         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
7906         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
7907
7908         rc = llapi_quotactl(mnt, qctl);
7909         if (rc) {
7910                 if (*obd_type)
7911                         fprintf(stderr,
7912                                 "%s setquota: cannot quotactl '%s' '%s': %s",
7913                                 progname, obd_type,
7914                                 obd_uuid2str(&qctl->obd_uuid), strerror(-rc));
7915         }
7916 out:
7917         free(qctl);
7918         return rc;
7919 }
7920
7921 /* Converts seconds value into format string
7922  * result is returned in buf
7923  * Notes:
7924  *        1. result is in descenting order: 1w2d3h4m5s
7925  *        2. zero fields are not filled (except for p. 3): 5d1s
7926  *        3. zero seconds value is presented as "0s"
7927  */
7928 static char *__sec2str(time_t seconds, char *buf)
7929 {
7930         const char spec[] = "smhdw";
7931         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
7932         unsigned long c;
7933         char *tail = buf;
7934         int i;
7935
7936         for (i = ARRAY_SIZE(mult) - 1 ; i >= 0; i--) {
7937                 c = seconds / mult[i];
7938
7939                 if (c > 0 || (i == 0 && buf == tail))
7940                         tail += scnprintf(tail, 40-(tail-buf), "%lu%c", c,
7941                                           spec[i]);
7942
7943                 seconds %= mult[i];
7944         }
7945
7946         return tail;
7947 }
7948
7949 static void sec2str(time_t seconds, char *buf, int rc)
7950 {
7951         char *tail = buf;
7952
7953         if (rc)
7954                 *tail++ = '[';
7955
7956         tail = __sec2str(seconds, tail);
7957
7958         if (rc && tail - buf < 39) {
7959                 *tail++ = ']';
7960                 *tail++ = 0;
7961         }
7962 }
7963
7964 static void diff2str(time_t seconds, char *buf, time_t now)
7965 {
7966         buf[0] = 0;
7967         if (!seconds)
7968                 return;
7969         if (seconds <= now) {
7970                 strcpy(buf, "none");
7971                 return;
7972         }
7973         __sec2str(seconds - now, buf);
7974 }
7975
7976 static void print_quota_title(char *name, struct if_quotactl *qctl,
7977                               bool human_readable, bool show_default)
7978 {
7979         if (show_default) {
7980                 printf("Disk default %s quota:\n", qtype_name(qctl->qc_type));
7981                 printf("%15s %8s%8s%8s %8s%8s%8s\n",
7982                        "Filesystem", "bquota", "blimit", "bgrace",
7983                        "iquota", "ilimit", "igrace");
7984         } else {
7985                 printf("Disk quotas for %s %s (%cid %u):\n",
7986                        qtype_name(qctl->qc_type), name,
7987                        *qtype_name(qctl->qc_type), qctl->qc_id);
7988                 printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
7989                        "Filesystem", human_readable ? "used" : "kbytes",
7990                        "quota", "limit", "grace",
7991                        "files", "quota", "limit", "grace");
7992         }
7993 }
7994
7995 static void kbytes2str(__u64 num, char *buf, int buflen, bool h)
7996 {
7997         if (!h) {
7998                 snprintf(buf, buflen, "%ju", (uintmax_t)num);
7999         } else {
8000                 if (num >> 40)
8001                         snprintf(buf, buflen, "%5.4gP",
8002                                  (double)num / ((__u64)1 << 40));
8003                 else if (num >> 30)
8004                         snprintf(buf, buflen, "%5.4gT",
8005                                  (double)num / (1 << 30));
8006                 else if (num >> 20)
8007                         snprintf(buf, buflen, "%5.4gG",
8008                                  (double)num / (1 << 20));
8009                 else if (num >> 10)
8010                         snprintf(buf, buflen, "%5.4gM",
8011                                  (double)num / (1 << 10));
8012                 else
8013                         snprintf(buf, buflen, "%ju%s", (uintmax_t)num, "k");
8014         }
8015 }
8016
8017 #define STRBUF_LEN      24
8018 static void print_quota(char *mnt, struct if_quotactl *qctl, int type,
8019                         int rc, bool h, bool show_default)
8020 {
8021         time_t now;
8022
8023         time(&now);
8024
8025         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA ||
8026             qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ||
8027             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT ||
8028             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT_POOL) {
8029                 int bover = 0, iover = 0;
8030                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
8031                 char numbuf[3][STRBUF_LEN + 2]; /* 2 for brackets or wildcard */
8032                 char timebuf[40];
8033                 char strbuf[STRBUF_LEN];
8034
8035                 if (dqb->dqb_bhardlimit &&
8036                     lustre_stoqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
8037                         bover = 1;
8038                 } else if (dqb->dqb_bsoftlimit && dqb->dqb_btime) {
8039                         if (dqb->dqb_btime > now)
8040                                 bover = 2;
8041                         else
8042                                 bover = 3;
8043                 }
8044
8045                 if (dqb->dqb_ihardlimit &&
8046                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
8047                         iover = 1;
8048                 } else if (dqb->dqb_isoftlimit && dqb->dqb_itime) {
8049                         if (dqb->dqb_itime > now)
8050                                 iover = 2;
8051                         else
8052                                 iover = 3;
8053                 }
8054
8055                 if (strlen(mnt) > 15)
8056                         printf("%s\n%15s", mnt, "");
8057                 else
8058                         printf("%15s", mnt);
8059
8060                 if (bover)
8061                         diff2str(dqb->dqb_btime, timebuf, now);
8062                 else if (show_default)
8063                         snprintf(timebuf, sizeof(timebuf), "%llu",
8064                                  (unsigned long long)dqb->dqb_btime);
8065
8066                 kbytes2str(lustre_stoqb(dqb->dqb_curspace),
8067                            strbuf, sizeof(strbuf), h);
8068                 if (rc == -EREMOTEIO)
8069                         sprintf(numbuf[0], "%s*", strbuf);
8070                 else
8071                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
8072                                 "%s" : "[%s]", strbuf);
8073
8074                 kbytes2str(dqb->dqb_bsoftlimit, strbuf, sizeof(strbuf), h);
8075                 if (type == QC_GENERAL)
8076                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS) ?
8077                                 "%s" : "[%s]", strbuf);
8078                 else
8079                         sprintf(numbuf[1], "%s", "-");
8080
8081                 kbytes2str(dqb->dqb_bhardlimit, strbuf, sizeof(strbuf), h);
8082                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS) ?
8083                         "%s" : "[%s]", strbuf);
8084
8085                 if (show_default)
8086                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
8087                 else
8088                         printf(" %7s%c %6s %7s %7s",
8089                                numbuf[0], bover ? '*' : ' ', numbuf[1],
8090                                numbuf[2], bover > 1 ? timebuf : "-");
8091
8092                 if (iover)
8093                         diff2str(dqb->dqb_itime, timebuf, now);
8094                 else if (show_default)
8095                         snprintf(timebuf, sizeof(timebuf), "%llu",
8096                                  (unsigned long long)dqb->dqb_itime);
8097
8098                 snprintf(numbuf[0], sizeof(numbuf),
8099                          (dqb->dqb_valid & QIF_INODES) ? "%ju" : "[%ju]",
8100                          (uintmax_t)dqb->dqb_curinodes);
8101
8102                 if (type == QC_GENERAL)
8103                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS) ?
8104                                 "%ju" : "[%ju]",
8105                                 (uintmax_t)dqb->dqb_isoftlimit);
8106                 else
8107                         sprintf(numbuf[1], "%s", "-");
8108
8109                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
8110                         "%ju" : "[%ju]", (uintmax_t)dqb->dqb_ihardlimit);
8111
8112                 if (show_default)
8113                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
8114                 else if (type != QC_OSTIDX)
8115                         printf(" %7s%c %6s %7s %7s",
8116                                numbuf[0], iover ? '*' : ' ', numbuf[1],
8117                                numbuf[2], iover > 1 ? timebuf : "-");
8118                 else
8119                         printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
8120                 printf("\n");
8121         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO || LUSTRE_Q_GETINFOPOOL ||
8122                    qctl->qc_cmd == Q_GETOINFO) {
8123                 char bgtimebuf[40];
8124                 char igtimebuf[40];
8125
8126                 if (qctl->qc_dqinfo.dqi_bgrace == NOTIFY_GRACE_TIME)
8127                         strncpy(bgtimebuf, NOTIFY_GRACE, 40);
8128                 else
8129                         sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
8130                 if (qctl->qc_dqinfo.dqi_igrace == NOTIFY_GRACE_TIME)
8131                         strncpy(igtimebuf, NOTIFY_GRACE, 40);
8132                 else
8133                         sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
8134
8135                 printf("Block grace time: %s; Inode grace time: %s\n",
8136                        bgtimebuf, igtimebuf);
8137         }
8138 }
8139
8140 static int tgt_name2index(const char *tgtname, unsigned int *idx)
8141 {
8142         char *dash, *endp;
8143
8144         /* format is "lustre-OST0001" */
8145         dash = memchr(tgtname, '-', LUSTRE_MAXFSNAME + 1);
8146         if (!dash) {
8147                 fprintf(stderr, "wrong tgtname format '%s'\n", tgtname);
8148                 return -EINVAL;
8149         }
8150         dash += 4;
8151
8152         *idx = strtoul(dash, &endp, 16);
8153         if (*idx > 0xffff) {
8154                 fprintf(stderr, "wrong index %s\n", tgtname);
8155                 return -ERANGE;
8156         }
8157
8158         return 0;
8159 }
8160
8161 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt,
8162                            bool h, __u64 *total)
8163 {
8164         int rc = 0, rc1 = 0, count = 0, i = 0;
8165         char **list = NULL, *buffer = NULL;
8166         __u32 valid = qctl->qc_valid;
8167
8168         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL && is_mdt)
8169                 return 0;
8170
8171         /* Is it correct for the case OST0000, OST0002, OST0003 -
8172          * we will ask OST0001 that is absent and won't ask OST0003? */
8173         rc = llapi_get_obd_count(mnt, &count, is_mdt);
8174         if (rc) {
8175                 fprintf(stderr, "can not get %s count: %s\n",
8176                         is_mdt ? "mdt" : "ost", strerror(-rc));
8177                 return rc;
8178         }
8179
8180         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8181                 char fname[PATH_MAX];
8182                 char fsname[LUSTRE_MAXFSNAME + 1];
8183                 int bufsize = sizeof(struct obd_uuid) * count;
8184
8185                 rc = llapi_search_fsname(mnt, fsname);
8186                 if (rc) {
8187                         fprintf(stderr, "cannot get fsname for mountpoint %s\n",
8188                                 mnt);
8189                         goto out;
8190                 }
8191                 buffer = malloc(bufsize + sizeof(*list) * count);
8192                 if (!buffer)
8193                         return -ENOMEM;
8194                 list = (char **)(buffer + bufsize);
8195                 snprintf(fname, PATH_MAX, "%s.%s", fsname, qctl->qc_poolname);
8196                 count = llapi_get_poolmembers(fname, list, count,
8197                                               buffer, bufsize);
8198                 if (count <= 0)
8199                         goto out;
8200         }
8201
8202         for (i = 0; i < count; i++) {
8203                 if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8204                         unsigned int index;
8205
8206                         if (tgt_name2index(list[i], &index))
8207                                 continue;
8208                         qctl->qc_idx = index;
8209                 } else {
8210                         qctl->qc_idx = i;
8211                 }
8212
8213                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
8214                 rc = llapi_quotactl(mnt, qctl);
8215                 if (rc) {
8216                         /* It is remote client case. */
8217                         if (rc == -EOPNOTSUPP) {
8218                                 rc = 0;
8219                                 goto out;
8220                         }
8221
8222                         if (!rc1)
8223                                 rc1 = rc;
8224                         fprintf(stderr, "quotactl %s%d failed.\n",
8225                                 is_mdt ? "mdt" : "ost", qctl->qc_idx);
8226                         continue;
8227                 }
8228
8229                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl,
8230                             qctl->qc_valid, 0, h, false);
8231                 *total += is_mdt ? qctl->qc_dqblk.dqb_ihardlimit :
8232                                    qctl->qc_dqblk.dqb_bhardlimit;
8233         }
8234 out:
8235         if (buffer)
8236                 free(buffer);
8237         qctl->qc_valid = valid;
8238         return rc ? : rc1;
8239 }
8240
8241 static int get_print_quota(char *mnt, char *name, struct if_quotactl *qctl,
8242                            int verbose, int quiet, bool human_readable,
8243                            bool show_default)
8244 {
8245         int rc1 = 0, rc2 = 0, rc3 = 0;
8246         char *obd_type = (char *)qctl->obd_type;
8247         char *obd_uuid = (char *)qctl->obd_uuid.uuid;
8248         __u64 total_ialloc = 0, total_balloc = 0;
8249         bool use_default_for_blk = false;
8250         bool use_default_for_file = false;
8251         int inacc;
8252
8253         rc1 = llapi_quotactl(mnt, qctl);
8254         if (rc1 < 0) {
8255                 switch (rc1) {
8256                 case -ESRCH:
8257                         fprintf(stderr, "%s quotas are not enabled.\n",
8258                                 qtype_name(qctl->qc_type));
8259                         goto out;
8260                 case -EPERM:
8261                         fprintf(stderr, "Permission denied.\n");
8262                 case -ENODEV:
8263                 case -ENOENT:
8264                         /* We already got error message. */
8265                         goto out;
8266                 default:
8267                         fprintf(stderr, "Unexpected quotactl error: %s\n",
8268                                 strerror(-rc1));
8269                 }
8270         }
8271
8272         if (!show_default && qctl->qc_id == 0) {
8273                 qctl->qc_dqblk.dqb_bhardlimit = 0;
8274                 qctl->qc_dqblk.dqb_bsoftlimit = 0;
8275                 qctl->qc_dqblk.dqb_ihardlimit = 0;
8276                 qctl->qc_dqblk.dqb_isoftlimit = 0;
8277                 qctl->qc_dqblk.dqb_btime = 0;
8278                 qctl->qc_dqblk.dqb_itime = 0;
8279                 qctl->qc_dqblk.dqb_valid |= QIF_LIMITS | QIF_TIMES;
8280         }
8281
8282         if (qctl->qc_dqblk.dqb_valid & QIF_BTIME &&
8283             LQUOTA_FLAG(qctl->qc_dqblk.dqb_btime) & LQUOTA_FLAG_DEFAULT) {
8284                 use_default_for_blk = true;
8285                 qctl->qc_dqblk.dqb_btime &= LQUOTA_GRACE_MASK;
8286         }
8287
8288         if (qctl->qc_dqblk.dqb_valid & QIF_ITIME &&
8289             LQUOTA_FLAG(qctl->qc_dqblk.dqb_itime) & LQUOTA_FLAG_DEFAULT) {
8290                 use_default_for_file = true;
8291                 qctl->qc_dqblk.dqb_itime &= LQUOTA_GRACE_MASK;
8292         }
8293
8294         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8295              qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ||
8296              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT_POOL ||
8297              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) && !quiet)
8298                 print_quota_title(name, qctl, human_readable, show_default);
8299
8300         if (rc1 && *obd_type)
8301                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
8302
8303         if (qctl->qc_valid != QC_GENERAL)
8304                 mnt = "";
8305
8306         inacc = (qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8307                  qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) &&
8308                 ((qctl->qc_dqblk.dqb_valid & (QIF_LIMITS|QIF_USAGE)) !=
8309                  (QIF_LIMITS|QIF_USAGE));
8310
8311         print_quota(mnt, qctl, QC_GENERAL, rc1, human_readable, show_default);
8312
8313         if (!show_default && verbose &&
8314             qctl->qc_valid == QC_GENERAL && qctl->qc_cmd != LUSTRE_Q_GETINFO &&
8315             qctl->qc_cmd != LUSTRE_Q_GETINFOPOOL) {
8316                 char strbuf[STRBUF_LEN];
8317
8318                 rc2 = print_obd_quota(mnt, qctl, 1, human_readable,
8319                                       &total_ialloc);
8320                 rc3 = print_obd_quota(mnt, qctl, 0, human_readable,
8321                                       &total_balloc);
8322                 kbytes2str(total_balloc, strbuf, sizeof(strbuf),
8323                            human_readable);
8324                 printf("Total allocated inode limit: %ju, total allocated block limit: %s\n",
8325                        (uintmax_t)total_ialloc, strbuf);
8326         }
8327
8328         if (use_default_for_blk)
8329                 printf("%cid %u is using default block quota setting\n",
8330                        *qtype_name(qctl->qc_type), qctl->qc_id);
8331
8332         if (use_default_for_file)
8333                 printf("%cid %u is using default file quota setting\n",
8334                        *qtype_name(qctl->qc_type), qctl->qc_id);
8335
8336         if (rc1 || rc2 || rc3 || inacc)
8337                 printf("Some errors happened when getting quota info. Some devices may be not working or deactivated. The data in \"[]\" is inaccurate.\n");
8338 out:
8339         if (rc1)
8340                 return rc1;
8341         if (rc2)
8342                 return rc2;
8343         if (rc3)
8344                 return rc3;
8345         if (inacc)
8346                 return -EIO;
8347
8348         return 0;
8349 }
8350
8351 static int lfs_project(int argc, char **argv)
8352 {
8353         int ret = 0, err = 0, c, i;
8354         struct project_handle_control phc = { 0 };
8355         enum lfs_project_ops_t op;
8356
8357         phc.newline = true;
8358         phc.assign_projid = false;
8359         /* default action */
8360         op = LFS_PROJECT_LIST;
8361
8362         while ((c = getopt(argc, argv, "p:cCsdkr0")) != -1) {
8363                 switch (c) {
8364                 case 'c':
8365                         if (op != LFS_PROJECT_LIST) {
8366                                 fprintf(stderr,
8367                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8368                                         progname);
8369                                 return CMD_HELP;
8370                         }
8371
8372                         op = LFS_PROJECT_CHECK;
8373                         break;
8374                 case 'C':
8375                         if (op != LFS_PROJECT_LIST) {
8376                                 fprintf(stderr,
8377                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8378                                         progname);
8379                                 return CMD_HELP;
8380                         }
8381
8382                         op = LFS_PROJECT_CLEAR;
8383                         break;
8384                 case 's':
8385                         if (op != LFS_PROJECT_LIST) {
8386                                 fprintf(stderr,
8387                                         "%s: cannot specify '-c' '-C' '-s' together\n",
8388                                         progname);
8389                                 return CMD_HELP;
8390                         }
8391
8392                         phc.set_inherit = true;
8393                         op = LFS_PROJECT_SET;
8394                         break;
8395                 case 'd':
8396                         phc.dironly = true;
8397                         break;
8398                 case 'k':
8399                         phc.keep_projid = true;
8400                         break;
8401                 case 'r':
8402                         phc.recursive = true;
8403                         break;
8404                 case 'p':
8405                         if (str2quotaid(&phc.projid, optarg)) {
8406                                 fprintf(stderr,
8407                                         "Invalid project ID: %s\n",
8408                                         optarg);
8409                                 return CMD_HELP;
8410                         }
8411
8412                         phc.assign_projid = true;
8413
8414                         break;
8415                 case '0':
8416                         phc.newline = false;
8417                         break;
8418                 default:
8419                         fprintf(stderr, "%s: invalid option '%c'\n",
8420                                 progname, optopt);
8421                         return CMD_HELP;
8422                 }
8423         }
8424
8425         if (phc.assign_projid && op == LFS_PROJECT_LIST) {
8426                 op = LFS_PROJECT_SET;
8427                 phc.set_projid = true;
8428         } else if (phc.assign_projid && op == LFS_PROJECT_SET) {
8429                 phc.set_projid = true;
8430         }
8431
8432         switch (op) {
8433         case LFS_PROJECT_CHECK:
8434                 if (phc.keep_projid) {
8435                         fprintf(stderr,
8436                                 "%s: '-k' is useless together with '-c'\n",
8437                                 progname);
8438                         return CMD_HELP;
8439                 }
8440                 break;
8441         case LFS_PROJECT_CLEAR:
8442                 if (!phc.newline) {
8443                         fprintf(stderr,
8444                                 "%s: '-0' is useless together with '-C'\n",
8445                                 progname);
8446                         return CMD_HELP;
8447                 }
8448                 if (phc.assign_projid) {
8449                         fprintf(stderr,
8450                                 "%s: '-p' is useless together with '-C'\n",
8451                                 progname);
8452                         return CMD_HELP;
8453                 }
8454                 break;
8455         case LFS_PROJECT_SET:
8456                 if (!phc.newline) {
8457                         fprintf(stderr,
8458                                 "%s: '-0' is useless together with '-s'\n",
8459                                 progname);
8460                         return CMD_HELP;
8461                 }
8462                 if (phc.keep_projid) {
8463                         fprintf(stderr,
8464                                 "%s: '-k' is useless together with '-s'\n",
8465                                 progname);
8466                         return CMD_HELP;
8467                 }
8468                 break;
8469         default:
8470                 if (!phc.newline) {
8471                         fprintf(stderr,
8472                                 "%s: '-0' is useless for list operations\n",
8473                                 progname);
8474                         return CMD_HELP;
8475                 }
8476                 break;
8477         }
8478
8479         argv += optind;
8480         argc -= optind;
8481         if (argc == 0) {
8482                 fprintf(stderr, "%s: missing file or directory target(s)\n",
8483                         progname);
8484                 return CMD_HELP;
8485         }
8486
8487         for (i = 0; i < argc; i++) {
8488                 switch (op) {
8489                 case LFS_PROJECT_CHECK:
8490                         err = lfs_project_check(argv[i], &phc);
8491                         break;
8492                 case LFS_PROJECT_LIST:
8493                         err = lfs_project_list(argv[i], &phc);
8494                         break;
8495                 case LFS_PROJECT_CLEAR:
8496                         err = lfs_project_clear(argv[i], &phc);
8497                         break;
8498                 case LFS_PROJECT_SET:
8499                         err = lfs_project_set(argv[i], &phc);
8500                         break;
8501                 default:
8502                         break;
8503                 }
8504                 if (err && !ret)
8505                         ret = err;
8506         }
8507
8508         return ret;
8509 }
8510
8511 static int lfs_quota(int argc, char **argv)
8512 {
8513         int c;
8514         char *mnt, *name = NULL;
8515         struct if_quotactl *qctl;
8516         char *obd_uuid;
8517         int rc = 0, rc1 = 0, verbose = 0, quiet = 0;
8518         __u32 valid = QC_GENERAL, idx = 0;
8519         bool human_readable = false;
8520         bool show_default = false;
8521         int qtype;
8522         bool show_pools = false;
8523         struct option long_opts[] = {
8524         { .val = LFS_POOL_OPT, .name = "pool", .has_arg = optional_argument },
8525         { .name = NULL } };
8526         char **poollist = NULL;
8527         char *buf = NULL;
8528         int poolcount, i;
8529
8530         qctl = calloc(1, sizeof(*qctl) + LOV_MAXPOOLNAME + 1);
8531         if (!qctl)
8532                 return -ENOMEM;
8533
8534         qctl->qc_cmd = LUSTRE_Q_GETQUOTA;
8535         qctl->qc_type = ALLQUOTA;
8536         obd_uuid = (char *)qctl->obd_uuid.uuid;
8537
8538         while ((c = getopt_long(argc, argv, "gGi:I:o:pPqtuUvh",
8539                 long_opts, NULL)) != -1) {
8540                 switch (c) {
8541                 case 'U':
8542                         show_default = true;
8543                 case 'u':
8544                         qtype = USRQUOTA;
8545                         goto quota_type;
8546                 case 'G':
8547                         show_default = true;
8548                 case 'g':
8549                         qtype = GRPQUOTA;
8550                         goto quota_type;
8551                 case 'P':
8552                         show_default = true;
8553                 case 'p':
8554                         qtype = PRJQUOTA;
8555 quota_type:
8556                         if (qctl->qc_type != ALLQUOTA) {
8557                                 fprintf(stderr,
8558                                         "%s quota: only one of -u, -g, or -p may be specified\n",
8559                                         progname);
8560                                 rc = CMD_HELP;
8561                                 goto out;
8562                         }
8563                         qctl->qc_type = qtype;
8564                         break;
8565                 case 't':
8566                         qctl->qc_cmd = LUSTRE_Q_GETINFO;
8567                         break;
8568                 case 'o':
8569                         valid = qctl->qc_valid = QC_UUID;
8570                         snprintf(obd_uuid, sizeof(*obd_uuid), "%s", optarg);
8571                         break;
8572                 case 'i':
8573                         valid = qctl->qc_valid = QC_MDTIDX;
8574                         idx = qctl->qc_idx = atoi(optarg);
8575                         if (idx == 0 && *optarg != '0') {
8576                                 fprintf(stderr,
8577                                         "%s quota: invalid MDT index '%s'\n",
8578                                         progname, optarg);
8579                                 rc = CMD_HELP;
8580                                 goto out;
8581                         }
8582                         break;
8583                 case 'I':
8584                         valid = qctl->qc_valid = QC_OSTIDX;
8585                         idx = qctl->qc_idx = atoi(optarg);
8586                         if (idx == 0 && *optarg != '0') {
8587                                 fprintf(stderr,
8588                                         "%s quota: invalid OST index '%s'\n",
8589                                         progname, optarg);
8590                                 rc = CMD_HELP;
8591                                 goto out;
8592                         }
8593                         break;
8594                 case 'v':
8595                         verbose = 1;
8596                         break;
8597                 case 'q':
8598                         quiet = 1;
8599                         break;
8600                 case 'h':
8601                         human_readable = true;
8602                         break;
8603                 case LFS_POOL_OPT:
8604                         if ((!optarg) && (argv[optind] != NULL) &&
8605                                 (argv[optind][0] != '-') &&
8606                                 (argv[optind][0] != '/')) {
8607                                 optarg = argv[optind++];
8608                                 if (lfs_verify_poolarg(optarg)) {
8609                                         rc = -EINVAL;
8610                                         goto out;
8611                                 }
8612                                 strncpy(qctl->qc_poolname, optarg,
8613                                         LOV_MAXPOOLNAME);
8614                                 if (qctl->qc_cmd == LUSTRE_Q_GETINFO)
8615                                         qctl->qc_cmd = LUSTRE_Q_GETINFOPOOL;
8616                                 else
8617                                         qctl->qc_cmd = LUSTRE_Q_GETQUOTAPOOL;
8618                                 break;
8619                         }
8620
8621                         /* optarg is NULL */
8622                         show_pools = true;
8623                         qctl->qc_cmd = LUSTRE_Q_GETQUOTAPOOL;
8624                         break;
8625                 default:
8626                         fprintf(stderr, "%s quota: unrecognized option '%s'\n",
8627                                 progname, argv[optind - 1]);
8628                         rc = CMD_HELP;
8629                         goto out;
8630                 }
8631         }
8632
8633         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
8634         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8635              qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) &&
8636              qctl->qc_type == ALLQUOTA &&
8637              optind == argc - 1 && !show_default) {
8638                 qctl->qc_idx = idx;
8639
8640                 for (qtype = USRQUOTA; qtype <= GRPQUOTA; qtype++) {
8641                         qctl->qc_type = qtype;
8642                         qctl->qc_valid = valid;
8643                         if (qtype == USRQUOTA) {
8644                                 qctl->qc_id = geteuid();
8645                                 rc = uid2name(&name, qctl->qc_id);
8646                         } else {
8647                                 qctl->qc_id = getegid();
8648                                 rc = gid2name(&name, qctl->qc_id);
8649                                 memset(&qctl->qc_dqblk, 0,
8650                                        sizeof(qctl->qc_dqblk));
8651                         }
8652                         if (rc)
8653                                 name = "<unknown>";
8654                         mnt = argv[optind];
8655                         rc1 = get_print_quota(mnt, name, qctl, verbose, quiet,
8656                                               human_readable, show_default);
8657                         if (rc1 && !rc)
8658                                 rc = rc1;
8659                 }
8660                 goto out;
8661         /* lfs quota -u username /path/to/lustre/mount */
8662         } else if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8663                    qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8664                 /* options should be followed by u/g-name and mntpoint */
8665                 if ((!show_default && optind + 2 != argc) ||
8666                     (show_default && optind + 1 != argc) ||
8667                     qctl->qc_type == ALLQUOTA) {
8668                         fprintf(stderr,
8669                                 "%s quota: name and mount point must be specified\n",
8670                                 progname);
8671                         rc = CMD_HELP;
8672                         goto out;
8673                 }
8674
8675                 if (!show_default) {
8676                         name = argv[optind++];
8677                         switch (qctl->qc_type) {
8678                         case USRQUOTA:
8679                                 rc = name2uid(&qctl->qc_id, name);
8680                                 break;
8681                         case GRPQUOTA:
8682                                 rc = name2gid(&qctl->qc_id, name);
8683                                 break;
8684                         case PRJQUOTA:
8685                                 rc = name2projid(&qctl->qc_id, name);
8686                                 break;
8687                         default:
8688                                 rc = -ENOTSUP;
8689                                 break;
8690                         }
8691                 } else {
8692                         qctl->qc_valid = QC_GENERAL;
8693                         qctl->qc_cmd = qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ?
8694                                         LUSTRE_Q_GETDEFAULT_POOL :
8695                                         LUSTRE_Q_GETDEFAULT;
8696                         qctl->qc_id = 0;
8697                 }
8698
8699                 if (rc) {
8700                         if (str2quotaid(&qctl->qc_id, name)) {
8701                                 fprintf(stderr, "%s quota: invalid id '%s'\n",
8702                                         progname, name);
8703                                 rc = CMD_HELP;
8704                                 goto out;
8705                         }
8706                 }
8707         } else if (optind + 1 != argc || qctl->qc_type == ALLQUOTA) {
8708                 fprintf(stderr, "%s quota: missing quota info argument(s)\n",
8709                         progname);
8710                 rc = CMD_HELP;
8711                 goto out;
8712         }
8713
8714         mnt = argv[optind];
8715         if (show_pools) {
8716                 char *p;
8717
8718                 i = 0;
8719                 rc = llapi_get_poolbuf(mnt, &buf, &poollist, &poolcount);
8720                 if (rc)
8721                         goto out;
8722
8723                 for (i = 0; i < poolcount; i++) {
8724                         p = memchr(poollist[i], '.', MAXNAMLEN);
8725                         if (!p) {
8726                                 fprintf(stderr, "bad string format %.*s\n",
8727                                         MAXNAMLEN, poollist[i]);
8728                                 rc = -EINVAL;
8729                                 goto out;
8730                         }
8731                         p++;
8732                         printf("Quotas for pool: %s\n", p);
8733                         strncpy(qctl->qc_poolname, p, LOV_MAXPOOLNAME);
8734                         rc = get_print_quota(mnt, name, qctl, verbose, quiet,
8735                                              human_readable, show_default);
8736                         if (rc)
8737                                 break;
8738                 }
8739                 goto out;
8740         }
8741
8742         rc = get_print_quota(mnt, name, qctl, verbose, quiet,
8743                              human_readable, show_default);
8744 out:
8745         free(buf);
8746         free(qctl);
8747         return rc;
8748 }
8749 #endif /* HAVE_SYS_QUOTA_H! */
8750
8751 static int flushctx_ioctl(char *mp)
8752 {
8753         int fd, rc;
8754
8755         fd = open(mp, O_RDONLY);
8756         if (fd == -1) {
8757                 fprintf(stderr, "flushctx: error open %s: %s\n",
8758                         mp, strerror(errno));
8759                 return -1;
8760         }
8761
8762         rc = ioctl(fd, LL_IOC_FLUSHCTX);
8763         if (rc == -1)
8764                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
8765                         mp, strerror(errno));
8766
8767         close(fd);
8768         return rc;
8769 }
8770
8771 static int lfs_flushctx(int argc, char **argv)
8772 {
8773         int     kdestroy = 0, reap = 0, c;
8774         char    mntdir[PATH_MAX] = {'\0'};
8775         int     index = 0;
8776         int     rc = 0;
8777
8778         while ((c = getopt(argc, argv, "kr")) != -1) {
8779                 switch (c) {
8780                 case 'k':
8781                         kdestroy = 1;
8782                         break;
8783                 case 'r':
8784                         reap = 1;
8785                         break;
8786                 default:
8787                         fprintf(stderr,
8788                                 "error: %s: option '-%c' unrecognized\n",
8789                                 argv[0], c);
8790                         return CMD_HELP;
8791                 }
8792         }
8793
8794         if (kdestroy) {
8795                 rc = system("kdestroy > /dev/null");
8796                 if (rc) {
8797                         rc = WEXITSTATUS(rc);
8798                         fprintf(stderr,
8799                                 "error destroying tickets: %d, continuing\n",
8800                                 rc);
8801                 }
8802         }
8803
8804         if (optind >= argc) {
8805                 /* flush for all mounted lustre fs. */
8806                 while (!llapi_search_mounts(NULL, index++, mntdir, NULL)) {
8807                         /* Check if we have a mount point */
8808                         if (mntdir[0] == '\0')
8809                                 continue;
8810
8811                         if (flushctx_ioctl(mntdir))
8812                                 rc = -1;
8813
8814                         mntdir[0] = '\0'; /* avoid matching in next loop */
8815                 }
8816         } else {
8817                 /* flush fs as specified */
8818                 while (optind < argc) {
8819                         if (flushctx_ioctl(argv[optind++]))
8820                                 rc = -1;
8821                 }
8822         }
8823
8824         if (reap) {
8825                 rc = system("keyctl reap > /dev/null");
8826                 if (rc != 0) {
8827                         rc = WEXITSTATUS(rc);
8828                         fprintf(stderr, "error reaping keyring: %d\n", rc);
8829                 }
8830         }
8831
8832         return rc;
8833 }
8834
8835 static int lfs_changelog(int argc, char **argv)
8836 {
8837         void *changelog_priv;
8838         struct changelog_rec *rec;
8839         long long startrec = 0, endrec = 0;
8840         char *mdd;
8841         struct option long_opts[] = {
8842                 { .val = 'f', .name = "follow", .has_arg = no_argument },
8843                 { .name = NULL } };
8844         char short_opts[] = "f";
8845         int rc, follow = 0;
8846
8847         while ((rc = getopt_long(argc, argv, short_opts,
8848                 long_opts, NULL)) != -1) {
8849                 switch (rc) {
8850                 case 'f':
8851                         follow++;
8852                         break;
8853                 default:
8854                         fprintf(stderr,
8855                                 "%s changelog: unrecognized option '%s'\n",
8856                                 progname, argv[optind - 1]);
8857                         return CMD_HELP;
8858                 }
8859         }
8860         if (optind >= argc) {
8861                 fprintf(stderr, "%s changelog: mdtname must be specified\n",
8862                         progname);
8863                 return CMD_HELP;
8864         }
8865
8866         mdd = argv[optind++];
8867         if (argc > optind) {
8868                 errno = 0;
8869                 startrec = strtoll(argv[optind++], NULL, 10);
8870                 if (errno != 0 || startrec < 0) {
8871                         fprintf(stderr,
8872                                 "%s changelog: bad startrec\n",
8873                                 progname);
8874                         return CMD_HELP;
8875                 }
8876         }
8877
8878         if (argc > optind) {
8879                 errno = 0;
8880                 endrec = strtoll(argv[optind++], NULL, 10);
8881                 if (errno != 0 || endrec < 0) {
8882                         fprintf(stderr,
8883                                 "%s changelog: bad endrec\n",
8884                                 progname);
8885                         return CMD_HELP;
8886                 }
8887         }
8888
8889         rc = llapi_changelog_start(&changelog_priv,
8890                                    CHANGELOG_FLAG_BLOCK |
8891                                    CHANGELOG_FLAG_JOBID |
8892                                    CHANGELOG_FLAG_EXTRA_FLAGS |
8893                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
8894                                    mdd, startrec);
8895         if (rc < 0) {
8896                 fprintf(stderr, "%s changelog: cannot start changelog: %s\n",
8897                         progname, strerror(errno = -rc));
8898                 return rc;
8899         }
8900
8901         rc = llapi_changelog_set_xflags(changelog_priv,
8902                                         CHANGELOG_EXTRA_FLAG_UIDGID |
8903                                         CHANGELOG_EXTRA_FLAG_NID |
8904                                         CHANGELOG_EXTRA_FLAG_OMODE |
8905                                         CHANGELOG_EXTRA_FLAG_XATTR);
8906         if (rc < 0) {
8907                 fprintf(stderr,
8908                         "%s changelog: cannot set xflags for changelog: %s\n",
8909                         progname, strerror(errno = -rc));
8910                 return rc;
8911         }
8912
8913         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
8914                 time_t secs;
8915                 struct tm ts;
8916
8917                 if (endrec && rec->cr_index > endrec) {
8918                         llapi_changelog_free(&rec);
8919                         break;
8920                 }
8921                 if (rec->cr_index < startrec) {
8922                         llapi_changelog_free(&rec);
8923                         continue;
8924                 }
8925
8926                 secs = rec->cr_time >> 30;
8927                 gmtime_r(&secs, &ts);
8928                 printf("%ju %02d%-5s %02d:%02d:%02d.%09d %04d.%02d.%02d "
8929                        "0x%x t="DFID, (uintmax_t)rec->cr_index, rec->cr_type,
8930                        changelog_type2str(rec->cr_type),
8931                        ts.tm_hour, ts.tm_min, ts.tm_sec,
8932                        (int)(rec->cr_time & ((1 << 30) - 1)),
8933                        ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday,
8934                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
8935
8936                 if (rec->cr_flags & CLF_JOBID) {
8937                         struct changelog_ext_jobid *jid =
8938                                 changelog_rec_jobid(rec);
8939
8940                         if (jid->cr_jobid[0] != '\0')
8941                                 printf(" j=%s", jid->cr_jobid);
8942                 }
8943
8944                 if (rec->cr_flags & CLF_EXTRA_FLAGS) {
8945                         struct changelog_ext_extra_flags *ef =
8946                                 changelog_rec_extra_flags(rec);
8947
8948                         printf(" ef=0x%llx",
8949                                (unsigned long long)ef->cr_extra_flags);
8950
8951                         if (ef->cr_extra_flags & CLFE_UIDGID) {
8952                                 struct changelog_ext_uidgid *uidgid =
8953                                         changelog_rec_uidgid(rec);
8954
8955                                 printf(" u=%llu:%llu",
8956                                        (unsigned long long)uidgid->cr_uid,
8957                                        (unsigned long long)uidgid->cr_gid);
8958                         }
8959                         if (ef->cr_extra_flags & CLFE_NID) {
8960                                 struct changelog_ext_nid *nid =
8961                                         changelog_rec_nid(rec);
8962
8963                                 printf(" nid=%s",
8964                                        libcfs_nid2str(nid->cr_nid));
8965                         }
8966
8967                         if (ef->cr_extra_flags & CLFE_OPEN) {
8968                                 struct changelog_ext_openmode *omd =
8969                                         changelog_rec_openmode(rec);
8970                                 char mode[] = "---";
8971
8972                                 /* exec mode must be exclusive */
8973                                 if (omd->cr_openflags & MDS_FMODE_EXEC) {
8974                                         mode[2] = 'x';
8975                                 } else {
8976                                         if (omd->cr_openflags & MDS_FMODE_READ)
8977                                                 mode[0] = 'r';
8978                                         if (omd->cr_openflags &
8979                                             (MDS_FMODE_WRITE |
8980                                              MDS_OPEN_TRUNC |
8981                                              MDS_OPEN_APPEND))
8982                                                 mode[1] = 'w';
8983                                 }
8984
8985                                 if (strcmp(mode, "---") != 0)
8986                                         printf(" m=%s", mode);
8987                         }
8988
8989                         if (ef->cr_extra_flags & CLFE_XATTR) {
8990                                 struct changelog_ext_xattr *xattr =
8991                                         changelog_rec_xattr(rec);
8992
8993                                 if (xattr->cr_xattr[0] != '\0')
8994                                         printf(" x=%s", xattr->cr_xattr);
8995                         }
8996                 }
8997
8998                 if (!fid_is_zero(&rec->cr_pfid))
8999                         printf(" p="DFID, PFID(&rec->cr_pfid));
9000                 if (rec->cr_namelen)
9001                         printf(" %.*s", rec->cr_namelen,
9002                                changelog_rec_name(rec));
9003
9004                 if (rec->cr_flags & CLF_RENAME) {
9005                         struct changelog_ext_rename *rnm =
9006                                 changelog_rec_rename(rec);
9007
9008                         if (!fid_is_zero(&rnm->cr_sfid))
9009                                 printf(" s="DFID" sp="DFID" %.*s",
9010                                        PFID(&rnm->cr_sfid),
9011                                        PFID(&rnm->cr_spfid),
9012                                        (int)changelog_rec_snamelen(rec),
9013                                        changelog_rec_sname(rec));
9014                 }
9015                 printf("\n");
9016
9017                 llapi_changelog_free(&rec);
9018         }
9019
9020         llapi_changelog_fini(&changelog_priv);
9021
9022         if (rc < 0)
9023                 fprintf(stderr, "%s changelog: cannot access changelog: %s\n",
9024                         progname, strerror(errno = -rc));
9025
9026         return (rc == 1 ? 0 : rc);
9027 }
9028
9029 static int lfs_changelog_clear(int argc, char **argv)
9030 {
9031         long long endrec;
9032         int rc;
9033
9034         if (argc != 4)
9035                 return CMD_HELP;
9036
9037         errno = 0;
9038         endrec = strtoll(argv[3], NULL, 10);
9039         if (errno != 0 || endrec < 0) {
9040                 fprintf(stderr,
9041                         "%s: bad endrec '%s'\n",
9042                         argv[0], argv[3]);
9043                 return CMD_HELP;
9044         }
9045
9046         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
9047
9048         if (rc == -EINVAL)
9049                 fprintf(stderr, "%s: record out of range: %llu\n",
9050                         argv[0], endrec);
9051         else if (rc == -ENOENT)
9052                 fprintf(stderr, "%s: no changelog user: %s\n",
9053                         argv[0], argv[2]);
9054         else if (rc)
9055                 fprintf(stderr, "%s error: %s\n", argv[0],
9056                         strerror(-rc));
9057
9058         if (rc)
9059                 errno = -rc;
9060
9061         return rc;
9062 }
9063
9064 static void rstripc(char *str, int c)
9065 {
9066         char *end = str + strlen(str);
9067
9068         for (; str < end && end[-1] == c; --end)
9069                 end[-1] = '\0';
9070 }
9071
9072 static int lfs_fid2path(int argc, char **argv)
9073 {
9074         struct option long_opts[] = {
9075                 { .val = 'c',   .name = "cur",  .has_arg = no_argument },
9076                 { .val = 'c',   .name = "current",      .has_arg = no_argument },
9077                 { .val = 'c',   .name = "print-link",   .has_arg = no_argument },
9078                 { .val = 'f',   .name = "print-fid",    .has_arg = no_argument },
9079                 { .val = 'l',   .name = "link", .has_arg = required_argument },
9080                 { .name = NULL } };
9081         char short_opts[] = "cfl:pr:";
9082         bool print_link = false;
9083         bool print_fid = false;
9084         bool print_mnt_dir;
9085         char mnt_dir[PATH_MAX] = "";
9086         int mnt_fd = -1;
9087         char *path_or_fsname;
9088         long long recno = -1;
9089         int linkno = -1;
9090         char *endptr = NULL;
9091         int rc = 0;
9092         int c;
9093         int i;
9094
9095         while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
9096                 switch (c) {
9097                 case 'c':
9098                         print_link = true;
9099                         break;
9100                 case 'f':
9101                         print_fid = true;
9102                         break;
9103                 case 'l':
9104                         errno = 0;
9105                         linkno = strtol(optarg, &endptr, 10);
9106                         if (errno != 0 || *endptr != '\0' || linkno < 0) {
9107                                 fprintf(stderr,
9108                                         "%s fid2path: invalid linkno '%s'\n",
9109                                         progname, optarg);
9110                                 return CMD_HELP;
9111                         }
9112                         break;
9113                 case 'r':
9114                         /* recno is something to do with changelogs
9115                          * that was never implemented. We just pass it
9116                          * through for the MDT to ignore.
9117                          */
9118                         errno = 0;
9119                         recno = strtoll(optarg, &endptr, 10);
9120                         if (errno != 0 || *endptr != '\0' || recno < 0) {
9121                                 fprintf(stderr,
9122                                         "%s fid2path: invalid recno '%s'\n",
9123                                         progname, optarg);
9124                                 return CMD_HELP;
9125                         }
9126                         break;
9127                 default:
9128                         fprintf(stderr,
9129                                 "%s fid2path: unrecognized option '%s'\n",
9130                                 progname, argv[optind - 1]);
9131                         return CMD_HELP;
9132                 }
9133         }
9134
9135         if (argc - optind < 2) {
9136                 fprintf(stderr,
9137                         "Usage: %s fid2path FSNAME|ROOT FID...\n",
9138                         progname);
9139                 return CMD_HELP;
9140         }
9141
9142         path_or_fsname = argv[optind];
9143
9144         if (*path_or_fsname == '/') {
9145                 print_mnt_dir = true;
9146                 rc = llapi_search_mounts(path_or_fsname, 0, mnt_dir, NULL);
9147         } else {
9148                 print_mnt_dir = false;
9149                 rc = llapi_search_rootpath(mnt_dir, path_or_fsname);
9150         }
9151
9152         if (rc < 0) {
9153                 fprintf(stderr,
9154                         "%s fid2path: cannot resolve mount point for '%s': %s\n",
9155                         progname, path_or_fsname, strerror(-rc));
9156                 goto out;
9157         }
9158
9159         mnt_fd = open(mnt_dir, O_RDONLY | O_DIRECTORY);
9160         if (mnt_fd < 0) {
9161                 fprintf(stderr,
9162                         "%s fid2path: cannot open mount point for '%s': %s\n",
9163                         progname, path_or_fsname, strerror(-rc));
9164                 goto out;
9165         }
9166
9167         /* Strip trailing slashes from mnt_dir. */
9168         rstripc(mnt_dir + 1, '/');
9169
9170         for (i = optind + 1; i < argc; i++) {
9171                 const char *fid_str = argv[i];
9172                 struct lu_fid fid;
9173                 int rc2;
9174
9175                 rc2 = llapi_fid_parse(fid_str, &fid, NULL);
9176                 if (rc2 < 0) {
9177                         fprintf(stderr,
9178                                 "%s fid2path: invalid FID '%s'\n",
9179                                 progname, fid_str);
9180                         if (rc == 0)
9181                                 rc = rc2;
9182
9183                         continue;
9184                 }
9185
9186                 int linktmp = (linkno >= 0) ? linkno : 0;
9187                 while (1) {
9188                         int oldtmp = linktmp;
9189                         long long rectmp = recno;
9190                         char path_buf[PATH_MAX];
9191
9192                         rc2 = llapi_fid2path_at(mnt_fd, &fid,
9193                                 path_buf, sizeof(path_buf), &rectmp, &linktmp);
9194                         if (rc2 < 0) {
9195                                 fprintf(stderr,
9196                                         "%s fid2path: cannot find %s %s: %s\n",
9197                                         progname, path_or_fsname, fid_str,
9198                                         strerror(-rc2));
9199                                 if (rc == 0)
9200                                         rc = rc2;
9201                                 break;
9202                         }
9203
9204                         if (print_fid)
9205                                 printf("%s ", fid_str);
9206
9207                         if (print_link)
9208                                 printf("%d ", linktmp);
9209
9210                         /* You may think this looks wrong or weird (and it is!)
9211                          * but we are actually trying to preserve the old quirky
9212                          * behaviors (enforced by our old quirky tests!) that
9213                          * make lfs so much fun to work on:
9214                          *
9215                          *   lustre 0x200000007:0x1:0x0 => "/"
9216                          *   /mnt/lustre 0x200000007:0x1:0x0 => "/mnt/lustre//"
9217                          *
9218                          * Note that llapi_fid2path() returns "" for the root
9219                          * FID. */
9220
9221                         printf("%s%s%s\n",
9222                                print_mnt_dir ? mnt_dir : "",
9223                                (print_mnt_dir || *path_buf == '\0') ? "/" : "",
9224                                path_buf);
9225
9226                         if (linkno >= 0)
9227                                 /* specified linkno */
9228                                 break;
9229
9230                         if (oldtmp == linktmp)
9231                                 /* no more links */
9232                                 break;
9233                 }
9234         }
9235 out:
9236         if (!(mnt_fd < 0))
9237                 close(mnt_fd);
9238
9239         return rc;
9240 }
9241
9242 static int lfs_path2fid(int argc, char **argv)
9243 {
9244         struct option long_opts[] = {
9245                 { .val = 'p', .name = "parents", .has_arg = no_argument },
9246                 { .name = NULL } };
9247         char            **path;
9248         const char        short_opts[] = "p";
9249         const char       *sep = "";
9250         struct lu_fid     fid;
9251         int               rc = 0;
9252         bool              show_parents = false;
9253
9254         while ((rc = getopt_long(argc, argv, short_opts,
9255                                  long_opts, NULL)) != -1) {
9256                 switch (rc) {
9257                 case 'p':
9258                         show_parents = true;
9259                         break;
9260                 default:
9261                         fprintf(stderr,
9262                                 "%s path2fid: unrecognized option '%s'\n",
9263                                 progname, argv[optind - 1]);
9264                         return CMD_HELP;
9265                 }
9266         }
9267
9268         if (optind > argc - 1) {
9269                 fprintf(stderr, "%s path2fid: FILE... must be specified\n",
9270                         progname);
9271                 return CMD_HELP;
9272         } else if (optind < argc - 1) {
9273                 sep = ": ";
9274         }
9275
9276         rc = 0;
9277         for (path = argv + optind; *path != NULL; path++) {
9278                 int err = 0;
9279
9280                 if (!show_parents) {
9281                         err = llapi_path2fid(*path, &fid);
9282                         if (!err)
9283                                 printf("%s%s"DFID"\n",
9284                                        *sep != '\0' ? *path : "", sep,
9285                                        PFID(&fid));
9286                 } else {
9287                         char            name[NAME_MAX + 1];
9288                         unsigned int    linkno = 0;
9289
9290                         while ((err = llapi_path2parent(*path, linkno, &fid,
9291                                                 name, sizeof(name))) == 0) {
9292                                 if (*sep != '\0' && linkno == 0)
9293                                         printf("%s%s", *path, sep);
9294
9295                                 printf("%s"DFID"/%s", linkno != 0 ? "\t" : "",
9296                                        PFID(&fid), name);
9297                                 linkno++;
9298                         }
9299
9300                         /* err == -ENODATA is end-of-loop */
9301                         if (linkno > 0 && err == -ENODATA) {
9302                                 printf("\n");
9303                                 err = 0;
9304                         }
9305                 }
9306
9307                 if (err) {
9308                         fprintf(stderr,
9309                                 "%s path2fid: cannot get %sfid for '%s': %s\n",
9310                                 progname, show_parents ? "parent " : "", *path,
9311                                 strerror(-err));
9312                         if (rc == 0) {
9313                                 rc = err;
9314                                 errno = -err;
9315                         }
9316                 }
9317         }
9318
9319         return rc;
9320 }
9321
9322 #define MAX_ERRNO       4095
9323 #define IS_ERR_VALUE(x) ((unsigned long)(x) >= (unsigned long)-MAX_ERRNO)
9324
9325 static int lfs_rmfid_and_show_errors(const char *device, struct fid_array *fa)
9326 {
9327         int rc, rc2, k;
9328
9329         rc = llapi_rmfid(device, fa);
9330         if (rc < 0) {
9331                 fprintf(stderr, "%s rmfid: cannot remove FIDs: %s\n",
9332                         progname, strerror(-rc));
9333                 return rc;
9334         }
9335
9336         for (k = 0; k < fa->fa_nr; k++) {
9337                 rc2 = (__s32)fa->fa_fids[k].f_ver;
9338                 if (!IS_ERR_VALUE(rc2))
9339                         continue;
9340
9341                 if (rc == 0)
9342                         rc = rc2;
9343
9344                 fa->fa_fids[k].f_ver = 0;
9345                 fprintf(stderr, "%s rmfid: cannot remove "DFID": %s\n",
9346                         progname, PFID(&fa->fa_fids[k]), strerror(-rc2));
9347         }
9348
9349         return rc;
9350 }
9351
9352 static int lfs_rmfid(int argc, char **argv)
9353 {
9354         char *fidstr, *device;
9355         int rc = 0, rc2, nr;
9356         struct fid_array *fa;
9357
9358         if (optind > argc - 1) {
9359                 fprintf(stderr, "%s rmfid: missing dirname\n", progname);
9360                 return CMD_HELP;
9361         }
9362
9363         device = argv[optind++];
9364
9365         nr = argc - optind;
9366         fa = malloc(offsetof(struct fid_array, fa_fids[nr + 1]));
9367         if (!fa)
9368                 return -ENOMEM;
9369
9370         fa->fa_nr = 0;
9371         rc = 0;
9372         while (optind < argc) {
9373                 int found;
9374
9375                 fidstr = argv[optind++];
9376                 while (*fidstr == '[')
9377                         fidstr++;
9378                 found = sscanf(fidstr, SFID, RFID(&fa->fa_fids[fa->fa_nr]));
9379                 if (found != 3) {
9380                         fprintf(stderr, "unrecognized FID: %s\n",
9381                                 argv[optind - 1]);
9382                         exit(1);
9383                 }
9384                 fa->fa_nr++;
9385                 if (fa->fa_nr == OBD_MAX_FIDS_IN_ARRAY) {
9386                         /* start another batch */
9387                         rc2 = lfs_rmfid_and_show_errors(device, fa);
9388                         if (rc2 && !rc)
9389                                 rc = rc2;
9390                         fa->fa_nr = 0;
9391                 }
9392         }
9393         if (fa->fa_nr) {
9394                 rc2 = lfs_rmfid_and_show_errors(device, fa);
9395                 if (rc2 && !rc)
9396                         rc = rc2;
9397         }
9398
9399         return rc;
9400 }
9401
9402 static int lfs_data_version(int argc, char **argv)
9403 {
9404         int data_version_flags = LL_DV_RD_FLUSH; /* Read by default */
9405         __u64 data_version;
9406         char *path;
9407         int fd;
9408         int rc;
9409         int c;
9410
9411         if (argc < 2) {
9412                 fprintf(stderr, "%s: FILE must be specified\n",
9413                         progname);
9414                 return CMD_HELP;
9415         }
9416
9417         while ((c = getopt(argc, argv, "hnrw")) != -1) {
9418                 switch (c) {
9419                 case 'n':
9420                         data_version_flags = 0;
9421                         break;
9422                 case 'r':
9423                         data_version_flags |= LL_DV_RD_FLUSH;
9424                         break;
9425                 case 'w':
9426                         data_version_flags |= LL_DV_WR_FLUSH;
9427                         break;
9428                 default:
9429                         fprintf(stderr,
9430                                 "%s data_version: unrecognized option '%s'\n",
9431                                 progname, argv[optind - 1]);
9432                         /* fallthrough */
9433                 case 'h':
9434                         return CMD_HELP;
9435                 }
9436         }
9437         if (optind == argc) {
9438                 fprintf(stderr, "%s data_version: FILE must be specified\n",
9439                         progname);
9440                 return CMD_HELP;
9441         }
9442
9443         path = argv[optind];
9444         fd = open(path, O_RDONLY);
9445         if (fd < 0) {
9446                 rc = -errno;
9447                 fprintf(stderr, "%s data_version: cannot open file '%s': %s\n",
9448                         progname, path, strerror(-rc));
9449                 return rc;
9450         }
9451
9452         rc = llapi_get_data_version(fd, &data_version, data_version_flags);
9453         if (rc < 0)
9454                 fprintf(stderr,
9455                         "%s data_version: cannot get version for '%s': %s\n",
9456                         progname, path, strerror(-rc));
9457         else
9458                 printf("%ju" "\n", (uintmax_t)data_version);
9459
9460         close(fd);
9461         return rc;
9462 }
9463
9464 static int lfs_hsm_state(int argc, char **argv)
9465 {
9466         int rc;
9467         int i = 1;
9468         char *path;
9469         struct hsm_user_state hus;
9470
9471         if (argc < 2)
9472                 return CMD_HELP;
9473
9474         do {
9475                 path = argv[i];
9476
9477                 rc = llapi_hsm_state_get(path, &hus);
9478                 if (rc) {
9479                         fprintf(stderr, "can't get hsm state for %s: %s\n",
9480                                 path, strerror(errno = -rc));
9481                         return rc;
9482                 }
9483
9484                 /* Display path name and status flags */
9485                 printf("%s: (0x%08x)", path, hus.hus_states);
9486
9487                 if (hus.hus_states & HS_RELEASED)
9488                         printf(" released");
9489                 if (hus.hus_states & HS_EXISTS)
9490                         printf(" exists");
9491                 if (hus.hus_states & HS_DIRTY)
9492                         printf(" dirty");
9493                 if (hus.hus_states & HS_ARCHIVED)
9494                         printf(" archived");
9495                 /* Display user-settable flags */
9496                 if (hus.hus_states & HS_NORELEASE)
9497                         printf(" never_release");
9498                 if (hus.hus_states & HS_NOARCHIVE)
9499                         printf(" never_archive");
9500                 if (hus.hus_states & HS_LOST)
9501                         printf(" lost_from_hsm");
9502
9503                 if (hus.hus_archive_id != 0)
9504                         printf(", archive_id:%d", hus.hus_archive_id);
9505                 printf("\n");
9506
9507         } while (++i < argc);
9508
9509         return 0;
9510 }
9511
9512 #define LFS_HSM_SET   0
9513 #define LFS_HSM_CLEAR 1
9514
9515 /**
9516  * Generic function to set or clear HSM flags.
9517  * Used by hsm_set and hsm_clear.
9518  *
9519  * @mode  if LFS_HSM_SET, set the flags, if LFS_HSM_CLEAR, clear the flags.
9520  */
9521 static int lfs_hsm_change_flags(int argc, char **argv, int mode)
9522 {
9523         struct option long_opts[] = {
9524         { .val = 'A',   .name = "archived",     .has_arg = no_argument },
9525         { .val = 'a',   .name = "noarchive",    .has_arg = no_argument },
9526         { .val = 'd',   .name = "dirty",        .has_arg = no_argument },
9527         { .val = 'e',   .name = "exists",       .has_arg = no_argument },
9528         { .val = 'h',   .name = "help",         .has_arg = no_argument },
9529         { .val = 'i',   .name = "archive-id",   .has_arg = required_argument },
9530         { .val = 'l',   .name = "lost",         .has_arg = no_argument },
9531         { .val = 'r',   .name = "norelease",    .has_arg = no_argument },
9532         { .name = NULL } };
9533         __u64 mask = 0;
9534         int c, rc;
9535         char *path;
9536         __u32 archive_id = 0;
9537         char *end = NULL;
9538
9539         if (argc < 3)
9540                 return CMD_HELP;
9541
9542         while ((c = getopt_long(argc, argv, "aAdehi:lr",
9543                                 long_opts, NULL)) != -1) {
9544                 switch (c) {
9545                 case 'l':
9546                         mask |= HS_LOST;
9547                         break;
9548                 case 'a':
9549                         mask |= HS_NOARCHIVE;
9550                         break;
9551                 case 'A':
9552                         mask |= HS_ARCHIVED;
9553                         break;
9554                 case 'r':
9555                         mask |= HS_NORELEASE;
9556                         break;
9557                 case 'd':
9558                         mask |= HS_DIRTY;
9559                         break;
9560                 case 'e':
9561                         mask |= HS_EXISTS;
9562                         break;
9563                 case 'i':
9564                         errno = 0;
9565                         archive_id = strtol(optarg, &end, 10);
9566                         if (errno != 0 || *end != '\0' || archive_id < 0) {
9567                                 fprintf(stderr,
9568                                         "%s: invalid archive_id: '%s'\n",
9569                                         progname, end);
9570                                 return CMD_HELP;
9571                         }
9572                         break;
9573                 default:
9574                         fprintf(stderr, "%s: unrecognized option '%s'\n",
9575                                 progname, argv[optind - 1]);
9576                         /* fallthrough */
9577                 case 'h':
9578                         return CMD_HELP;
9579                 }
9580         }
9581
9582         /* User should have specified a flag */
9583         if (mask == 0)
9584                 return CMD_HELP;
9585
9586         while (optind < argc) {
9587                 path = argv[optind];
9588
9589                 /* If mode == 0, this means we apply the mask. */
9590                 if (mode == LFS_HSM_SET)
9591                         rc = llapi_hsm_state_set(path, mask, 0, archive_id);
9592                 else
9593                         rc = llapi_hsm_state_set(path, 0, mask, 0);
9594
9595                 if (rc != 0) {
9596                         fprintf(stderr, "Can't change hsm flags for %s: %s\n",
9597                                 path, strerror(errno = -rc));
9598                         return rc;
9599                 }
9600                 optind++;
9601         }
9602
9603         return 0;
9604 }
9605
9606 static int lfs_hsm_action(int argc, char **argv)
9607 {
9608         int                              rc;
9609         int                              i = 1;
9610         char                            *path;
9611         struct hsm_current_action        hca;
9612         struct hsm_extent                he;
9613         enum hsm_user_action             hua;
9614         enum hsm_progress_states         hps;
9615
9616         if (argc < 2)
9617                 return CMD_HELP;
9618
9619         do {
9620                 path = argv[i];
9621
9622                 rc = llapi_hsm_current_action(path, &hca);
9623                 if (rc) {
9624                         fprintf(stderr, "can't get hsm action for %s: %s\n",
9625                                 path, strerror(errno = -rc));
9626                         return rc;
9627                 }
9628                 he = hca.hca_location;
9629                 hua = hca.hca_action;
9630                 hps = hca.hca_state;
9631
9632                 printf("%s: %s", path, hsm_user_action2name(hua));
9633
9634                 /* Skip file without action */
9635                 if (hca.hca_action == HUA_NONE) {
9636                         printf("\n");
9637                         continue;
9638                 }
9639
9640                 printf(" %s ", hsm_progress_state2name(hps));
9641
9642                 if ((hps == HPS_RUNNING) &&
9643                     (hua == HUA_ARCHIVE || hua == HUA_RESTORE))
9644                         printf("(%llu bytes moved)\n",
9645                                (unsigned long long)he.length);
9646                 else if ((he.offset + he.length) == LUSTRE_EOF)
9647                         printf("(from %llu to EOF)\n",
9648                                (unsigned long long)he.offset);
9649                 else
9650                         printf("(from %llu to %llu)\n",
9651                                (unsigned long long)he.offset,
9652                                (unsigned long long)(he.offset + he.length));
9653
9654         } while (++i < argc);
9655
9656         return 0;
9657 }
9658
9659 static int lfs_hsm_set(int argc, char **argv)
9660 {
9661         return lfs_hsm_change_flags(argc, argv, LFS_HSM_SET);
9662 }
9663
9664 static int lfs_hsm_clear(int argc, char **argv)
9665 {
9666         return lfs_hsm_change_flags(argc, argv, LFS_HSM_CLEAR);
9667 }
9668
9669 /**
9670  * Check file state and return its fid, to be used by lfs_hsm_request().
9671  *
9672  * \param[in]     file      Path to file to check
9673  * \param[in,out] fid       Pointer to allocated lu_fid struct.
9674  * \param[in,out] last_dev  Pointer to last device id used.
9675  *
9676  * \return 0 on success.
9677  */
9678 static int lfs_hsm_prepare_file(const char *file, struct lu_fid *fid,
9679                                 dev_t *last_dev)
9680 {
9681         struct stat     st;
9682         int             rc;
9683
9684         rc = lstat(file, &st);
9685         if (rc) {
9686                 fprintf(stderr, "Cannot stat %s: %s\n", file, strerror(errno));
9687                 return -errno;
9688         }
9689         /*
9690          * Checking for regular file as archiving as posix copytool
9691          * rejects archiving files other than regular files
9692          */
9693         if (!S_ISREG(st.st_mode)) {
9694                 fprintf(stderr, "error: \"%s\" is not a regular file\n", file);
9695                 return CMD_HELP;
9696         }
9697         /* A request should be ... */
9698         if (*last_dev != st.st_dev && *last_dev != 0) {
9699                 fprintf(stderr,
9700                         "All files should be on the same filesystem: %s\n",
9701                         file);
9702                 return -EINVAL;
9703         }
9704         *last_dev = st.st_dev;
9705
9706         rc = llapi_path2fid(file, fid);
9707         if (rc) {
9708                 fprintf(stderr, "Cannot read FID of %s: %s\n",
9709                         file, strerror(-rc));
9710                 return rc;
9711         }
9712         return 0;
9713 }
9714
9715 /* Fill an HSM HUR item with a given file name.
9716  *
9717  * If mntpath is set, then the filename is actually a FID, and no
9718  * lookup on the filesystem will be performed.
9719  *
9720  * \param[in]  hur         the user request to fill
9721  * \param[in]  idx         index of the item inside the HUR to fill
9722  * \param[in]  mntpath     mountpoint of Lustre
9723  * \param[in]  fname       filename (if mtnpath is NULL)
9724  *                         or FID (if mntpath is set)
9725  * \param[in]  last_dev    pointer to last device id used
9726  *
9727  * \retval 0 on success
9728  * \retval CMD_HELP or a negative errno on error
9729  */
9730 static int fill_hur_item(struct hsm_user_request *hur, unsigned int idx,
9731                          const char *mntpath, const char *fname,
9732                          dev_t *last_dev)
9733 {
9734         struct hsm_user_item *hui = &hur->hur_user_item[idx];
9735         int rc;
9736
9737         hui->hui_extent.length = -1;
9738
9739         if (mntpath) {
9740                 rc = llapi_fid_parse(fname, &hui->hui_fid, NULL);
9741                 if (rc)
9742                         fprintf(stderr, "hsm: '%s' is not a valid FID\n",
9743                                 fname);
9744         } else {
9745                 rc = lfs_hsm_prepare_file(fname, &hui->hui_fid, last_dev);
9746         }
9747
9748         if (rc == 0)
9749                 hur->hur_request.hr_itemcount++;
9750
9751         return rc;
9752 }
9753
9754 static int lfs_hsm_request(int argc, char **argv, int action)
9755 {
9756         struct option long_opts[] = {
9757         { .val = 'a',   .name = "archive",      .has_arg = required_argument },
9758         { .val = 'D',   .name = "data",         .has_arg = required_argument },
9759         { .val = 'h',   .name = "help",         .has_arg = no_argument },
9760         { .val = 'l',   .name = "filelist",     .has_arg = required_argument },
9761         { .val = 'm',   .name = "mntpath",      .has_arg = required_argument },
9762         { .name = NULL } };
9763         dev_t last_dev = 0;
9764         struct hsm_user_request *hur, *oldhur;
9765         int c, i;
9766         size_t len;
9767         int nbfile;
9768         char *line = NULL;
9769         char *filelist = NULL;
9770         char fullpath[PATH_MAX];
9771         char *opaque = NULL;
9772         int opaque_len = 0;
9773         int archive_id = 0;
9774         FILE *fp;
9775         int nbfile_alloc = 0;
9776         char *some_file = NULL;
9777         char *mntpath = NULL;
9778         int rc;
9779
9780         if (argc < 2)
9781                 return CMD_HELP;
9782
9783         while ((c = getopt_long(argc, argv, "a:D:hl:m:",
9784                                 long_opts, NULL)) != -1) {
9785                 switch (c) {
9786                 case 'l':
9787                         filelist = optarg;
9788                         break;
9789                 case 'D':
9790                         opaque = optarg;
9791                         break;
9792                 case 'a':
9793                         if (action != HUA_ARCHIVE &&
9794                             action != HUA_REMOVE) {
9795                                 fprintf(stderr,
9796                                         "error: -a is supported only when archiving or removing\n");
9797                                 return CMD_HELP;
9798                         }
9799                         archive_id = atoi(optarg);
9800                         break;
9801                 case 'm':
9802                         if (!some_file) {
9803                                 mntpath = optarg;
9804                                 some_file = strdup(optarg);
9805                         }
9806                         break;
9807                 default:
9808                         fprintf(stderr, "%s: unrecognized option '%s'\n",
9809                                 progname, argv[optind - 1]);
9810                         /* fallthrough */
9811                 case 'h':
9812                         return CMD_HELP;
9813                 }
9814         }
9815
9816         /* All remaining args are files, so we have at least nbfile */
9817         nbfile = argc - optind;
9818
9819         if ((nbfile == 0) && (!filelist))
9820                 return CMD_HELP;
9821
9822         if (opaque)
9823                 opaque_len = strlen(opaque);
9824
9825         /*
9826          * Alloc the request structure with enough place to store all files
9827          * from command line.
9828          */
9829         hur = llapi_hsm_user_request_alloc(nbfile, opaque_len);
9830         if (!hur) {
9831                 fprintf(stderr, "Cannot create the request: %s\n",
9832                         strerror(errno));
9833                 return errno;
9834         }
9835         nbfile_alloc = nbfile;
9836
9837         hur->hur_request.hr_action = action;
9838         hur->hur_request.hr_archive_id = archive_id;
9839         hur->hur_request.hr_flags = 0;
9840
9841         /* All remaining args are files, add them */
9842         if (nbfile != 0 && some_file == NULL)
9843                 some_file = strdup(argv[optind]);
9844
9845         for (i = 0; i < nbfile; i++) {
9846                 rc = fill_hur_item(hur, i, mntpath, argv[optind + i],
9847                                    &last_dev);
9848                 if (rc)
9849                         goto out_free;
9850         }
9851
9852         /* from here stop using nb_file, use hur->hur_request.hr_itemcount */
9853
9854         /* If a filelist was specified, read the filelist from it. */
9855         if (filelist) {
9856                 fp = fopen(filelist, "r");
9857                 if (!fp) {
9858                         fprintf(stderr, "Cannot read the file list %s: %s\n",
9859                                 filelist, strerror(errno));
9860                         rc = -errno;
9861                         goto out_free;
9862                 }
9863
9864                 while ((rc = getline(&line, &len, fp)) != -1) {
9865                         /*
9866                          * If allocated buffer was too small, get something
9867                          * larger
9868                          */
9869                         if (nbfile_alloc <= hur->hur_request.hr_itemcount) {
9870                                 ssize_t size;
9871
9872                                 nbfile_alloc = nbfile_alloc * 2 + 1;
9873                                 oldhur = hur;
9874                                 hur = llapi_hsm_user_request_alloc(nbfile_alloc,
9875                                                                    opaque_len);
9876                                 if (!hur) {
9877                                         fprintf(stderr,
9878                                                 "hsm: cannot allocate the request: %s\n",
9879                                                 strerror(errno));
9880                                         hur = oldhur;
9881                                         rc = -errno;
9882                                         fclose(fp);
9883                                         goto out_free;
9884                                 }
9885                                 size = hur_len(oldhur);
9886                                 if (size < 0) {
9887                                         fprintf(stderr,
9888                                                 "hsm: cannot allocate %u files + %u bytes data\n",
9889                                                 oldhur->hur_request.hr_itemcount,
9890                                                 oldhur->hur_request.hr_data_len);
9891                                         free(hur);
9892                                         hur = oldhur;
9893                                         rc = -E2BIG;
9894                                         fclose(fp);
9895                                         goto out_free;
9896                                 }
9897                                 memcpy(hur, oldhur, size);
9898                                 free(oldhur);
9899                         }
9900
9901                         /* Chop CR */
9902                         if (line[strlen(line) - 1] == '\n')
9903                                 line[strlen(line) - 1] = '\0';
9904
9905                         rc = fill_hur_item(hur, hur->hur_request.hr_itemcount,
9906                                            mntpath, line, &last_dev);
9907                         if (rc) {
9908                                 fclose(fp);
9909                                 goto out_free;
9910                         }
9911
9912                         if (!some_file) {
9913                                 some_file = line;
9914                                 line = NULL;
9915                         }
9916                 }
9917
9918                 rc = fclose(fp);
9919                 free(line);
9920         }
9921
9922         /* If a --data was used, add it to the request */
9923         hur->hur_request.hr_data_len = opaque_len;
9924         if (opaque)
9925                 memcpy(hur_data(hur), opaque, opaque_len);
9926
9927         /* Send the HSM request */
9928         if (realpath(some_file, fullpath) == NULL) {
9929                 fprintf(stderr, "Could not find path '%s': %s\n",
9930                         some_file, strerror(errno));
9931         }
9932         rc = llapi_hsm_request(fullpath, hur);
9933         if (rc) {
9934                 fprintf(stderr, "Cannot send HSM request (use of %s): %s\n",
9935                         some_file, strerror(-rc));
9936                 goto out_free;
9937         }
9938
9939 out_free:
9940         free(some_file);
9941         free(hur);
9942         return rc;
9943 }
9944
9945 static int lfs_hsm_archive(int argc, char **argv)
9946 {
9947         return lfs_hsm_request(argc, argv, HUA_ARCHIVE);
9948 }
9949
9950 static int lfs_hsm_restore(int argc, char **argv)
9951 {
9952         return lfs_hsm_request(argc, argv, HUA_RESTORE);
9953 }
9954
9955 static int lfs_hsm_release(int argc, char **argv)
9956 {
9957         return lfs_hsm_request(argc, argv, HUA_RELEASE);
9958 }
9959
9960 static int lfs_hsm_remove(int argc, char **argv)
9961 {
9962         return lfs_hsm_request(argc, argv, HUA_REMOVE);
9963 }
9964
9965 static int lfs_hsm_cancel(int argc, char **argv)
9966 {
9967         return lfs_hsm_request(argc, argv, HUA_CANCEL);
9968 }
9969
9970 static int lfs_swap_layouts(int argc, char **argv)
9971 {
9972         if (argc != 3)
9973                 return CMD_HELP;
9974
9975         return llapi_swap_layouts(argv[1], argv[2], 0, 0,
9976                                   SWAP_LAYOUTS_KEEP_MTIME |
9977                                   SWAP_LAYOUTS_KEEP_ATIME);
9978 }
9979
9980 static const char *const ladvise_names[] = LU_LADVISE_NAMES;
9981
9982 static const char *const lock_mode_names[] = LOCK_MODE_NAMES;
9983
9984 int lfs_get_mode(const char *string)
9985 {
9986         enum lock_mode_user mode;
9987
9988         for (mode = 0; mode < ARRAY_SIZE(lock_mode_names); mode++) {
9989                 if (lock_mode_names[mode] == NULL)
9990                         continue;
9991                 if (strcasecmp(string, lock_mode_names[mode]) == 0)
9992                         return mode;
9993         }
9994
9995         return -EINVAL;
9996 }
9997
9998 static enum lu_ladvise_type lfs_get_ladvice(const char *string)
9999 {
10000         enum lu_ladvise_type advice;
10001
10002         for (advice = 0;
10003              advice < ARRAY_SIZE(ladvise_names); advice++) {
10004                 if (ladvise_names[advice] == NULL)
10005                         continue;
10006                 if (strcmp(string, ladvise_names[advice]) == 0)
10007                         return advice;
10008         }
10009
10010         return LU_LADVISE_INVALID;
10011 }
10012
10013 static int lfs_ladvise(int argc, char **argv)
10014 {
10015         struct option long_opts[] = {
10016         { .val = 'a',   .name = "advice",       .has_arg = required_argument },
10017         { .val = 'b',   .name = "background",   .has_arg = no_argument },
10018         { .val = 'e',   .name = "end",          .has_arg = required_argument },
10019         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10020         { .val = 'l',   .name = "length",       .has_arg = required_argument },
10021         { .val = 'm',   .name = "mode",         .has_arg = required_argument },
10022         { .val = 's',   .name = "start",        .has_arg = required_argument },
10023         { .val = 'u',   .name = "unset",        .has_arg = no_argument },
10024         { .name = NULL } };
10025         struct llapi_lu_ladvise advice;
10026         enum lu_ladvise_type advice_type = LU_LADVISE_INVALID;
10027         unsigned long long start = 0;
10028         unsigned long long end = LUSTRE_EOF;
10029         unsigned long long length = 0;
10030         unsigned long long size_units;
10031         unsigned long long flags = 0;
10032         int c, fd, rc = 0;
10033         const char *path;
10034         int mode = 0;
10035
10036         optind = 0;
10037         while ((c = getopt_long(argc, argv, "a:be:hl:m:s:u",
10038                                 long_opts, NULL)) != -1) {
10039                 switch (c) {
10040                 case 'a':
10041                         advice_type = lfs_get_ladvice(optarg);
10042                         if (advice_type == LU_LADVISE_INVALID) {
10043                                 fprintf(stderr,
10044                                         "%s: invalid advice type '%s'\n",
10045                                         progname, optarg);
10046                                 fprintf(stderr, "Valid types:");
10047
10048                                 for (advice_type = 0;
10049                                      advice_type < ARRAY_SIZE(ladvise_names);
10050                                      advice_type++) {
10051                                         if (ladvise_names[advice_type] == NULL)
10052                                                 continue;
10053                                         fprintf(stderr, " %s",
10054                                                 ladvise_names[advice_type]);
10055                                 }
10056                                 fprintf(stderr, "\n");
10057
10058                                 return CMD_HELP;
10059                         }
10060                         break;
10061                 case 'b':
10062                         flags |= LF_ASYNC;
10063                         break;
10064                 case 'u':
10065                         flags |= LF_UNSET;
10066                         break;
10067                 case 'e':
10068                         size_units = 1;
10069                         rc = llapi_parse_size(optarg, &end,
10070                                               &size_units, 0);
10071                         if (rc) {
10072                                 fprintf(stderr, "%s: bad end offset '%s'\n",
10073                                         argv[0], optarg);
10074                                 return CMD_HELP;
10075                         }
10076                         break;
10077                 case 's':
10078                         size_units = 1;
10079                         rc = llapi_parse_size(optarg, &start,
10080                                               &size_units, 0);
10081                         if (rc) {
10082                                 fprintf(stderr,
10083                                         "%s: bad start offset '%s'\n",
10084                                         argv[0], optarg);
10085                                 return CMD_HELP;
10086                         }
10087                         break;
10088                 case 'l':
10089                         size_units = 1;
10090                         rc = llapi_parse_size(optarg, &length,
10091                                               &size_units, 0);
10092                         if (rc) {
10093                                 fprintf(stderr, "%s: bad length '%s'\n",
10094                                         argv[0], optarg);
10095                                 return CMD_HELP;
10096                         }
10097                         break;
10098                 case 'm':
10099                         mode = lfs_get_mode(optarg);
10100                         if (mode < 0) {
10101                                 fprintf(stderr,
10102                                         "%s: bad mode '%s', valid modes are READ or WRITE\n",
10103                                         argv[0], optarg);
10104                                 return CMD_HELP;
10105                         }
10106                         break;
10107                 default:
10108                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10109                                 progname, argv[optind - 1]);
10110                         /* fallthrough */
10111                 case 'h':
10112                         return CMD_HELP;
10113                 }
10114         }
10115
10116         if (advice_type == LU_LADVISE_INVALID) {
10117                 fprintf(stderr, "%s: please give an advice type\n", argv[0]);
10118                 fprintf(stderr, "Valid types:");
10119                 for (advice_type = 0; advice_type < ARRAY_SIZE(ladvise_names);
10120                      advice_type++) {
10121                         if (ladvise_names[advice_type] == NULL)
10122                                 continue;
10123                         fprintf(stderr, " %s", ladvise_names[advice_type]);
10124                 }
10125                 fprintf(stderr, "\n");
10126                 return CMD_HELP;
10127         }
10128
10129         if (advice_type == LU_LADVISE_LOCKNOEXPAND) {
10130                 fprintf(stderr,
10131                         "%s: Lock no expand advice is a per file descriptor advice, so when called from lfs, it does nothing.\n",
10132                         argv[0]);
10133                 return CMD_HELP;
10134         }
10135
10136         if (argc <= optind) {
10137                 fprintf(stderr, "%s: please give one or more file names\n",
10138                         argv[0]);
10139                 return CMD_HELP;
10140         }
10141
10142         if (end != LUSTRE_EOF && length != 0 && end != start + length) {
10143                 fprintf(stderr, "%s: conflicting arguments of -l and -e\n",
10144                         argv[0]);
10145                 return CMD_HELP;
10146         }
10147
10148         if (end == LUSTRE_EOF && length != 0)
10149                 end = start + length;
10150
10151         if (end <= start) {
10152                 fprintf(stderr, "%s: range [%llu, %llu] is invalid\n",
10153                         argv[0], start, end);
10154                 return CMD_HELP;
10155         }
10156
10157         if (advice_type != LU_LADVISE_LOCKAHEAD && mode != 0) {
10158                 fprintf(stderr, "%s: mode is only valid with lockahead\n",
10159                         argv[0]);
10160                 return CMD_HELP;
10161         }
10162
10163         if (advice_type == LU_LADVISE_LOCKAHEAD && mode == 0) {
10164                 fprintf(stderr, "%s: mode is required with lockahead\n",
10165                         argv[0]);
10166                 return CMD_HELP;
10167         }
10168
10169         while (optind < argc) {
10170                 int rc2;
10171
10172                 path = argv[optind++];
10173
10174                 fd = open(path, O_RDONLY);
10175                 if (fd < 0) {
10176                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10177                                 argv[0], path, strerror(errno));
10178                         rc2 = -errno;
10179                         goto next;
10180                 }
10181
10182                 advice.lla_start = start;
10183                 advice.lla_end = end;
10184                 advice.lla_advice = advice_type;
10185                 advice.lla_value1 = 0;
10186                 advice.lla_value2 = 0;
10187                 advice.lla_value3 = 0;
10188                 advice.lla_value4 = 0;
10189                 if (advice_type == LU_LADVISE_LOCKAHEAD) {
10190                         advice.lla_lockahead_mode = mode;
10191                         advice.lla_peradvice_flags = flags;
10192                 }
10193
10194                 rc2 = llapi_ladvise(fd, flags, 1, &advice);
10195                 close(fd);
10196                 if (rc2 < 0) {
10197                         fprintf(stderr,
10198                                 "%s: cannot give advice '%s' to file '%s': %s\n",
10199                                 argv[0], ladvise_names[advice_type],
10200                                 path, strerror(errno));
10201
10202                         goto next;
10203                 }
10204
10205 next:
10206                 if (rc == 0 && rc2 < 0)
10207                         rc = rc2;
10208         }
10209         return rc;
10210 }
10211
10212 static const char *const heat_names[] = LU_HEAT_NAMES;
10213
10214 static int lfs_heat_get(int argc, char **argv)
10215 {
10216         struct lu_heat *heat;
10217         int rc = 0, rc2;
10218         char *path;
10219         int fd;
10220         int i;
10221
10222         if (argc <= 1)
10223                 return CMD_HELP;
10224
10225         heat = calloc(sizeof(*heat) + sizeof(__u64) * OBD_HEAT_COUNT, 1);
10226         if (!heat) {
10227                 fprintf(stderr, "%s: memory allocation failed\n", argv[0]);
10228                 return -ENOMEM;
10229         }
10230
10231         optind = 1;
10232         while (optind < argc) {
10233                 path = argv[optind++];
10234
10235                 fd = open(path, O_RDONLY);
10236                 if (fd < 0) {
10237                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10238                                 argv[0], path, strerror(errno));
10239                         rc2 = -errno;
10240                         goto next;
10241                 }
10242
10243                 heat->lh_count = OBD_HEAT_COUNT;
10244                 rc2 = llapi_heat_get(fd, heat);
10245                 close(fd);
10246                 if (rc2 < 0) {
10247                         fprintf(stderr,
10248                                 "%s: cannot get heat of file '%s': %s\n",
10249                                 argv[0], path, strerror(errno));
10250                         goto next;
10251                 }
10252
10253                 printf("flags: %x\n", heat->lh_flags);
10254                 for (i = 0; i < heat->lh_count; i++)
10255                         printf("%s: %llu\n", heat_names[i],
10256                                (unsigned long long)heat->lh_heat[i]);
10257 next:
10258                 if (rc == 0 && rc2 < 0)
10259                         rc = rc2;
10260         }
10261
10262         free(heat);
10263         return rc;
10264 }
10265
10266 static int lfs_heat_set(int argc, char **argv)
10267 {
10268         struct option long_opts[] = {
10269         { .val = 'c',   .name = "clear",        .has_arg = no_argument },
10270         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10271         { .val = 'o',   .name = "off",          .has_arg = no_argument },
10272         { .val = 'O',   .name = "on",           .has_arg = no_argument },
10273         { .name = NULL } };
10274         enum lu_heat_flag flags = 0;
10275         int rc = 0, rc2;
10276         char *path;
10277         int fd;
10278         int c;
10279
10280         if (argc <= 1)
10281                 return CMD_HELP;
10282
10283         optind = 0;
10284         while ((c = getopt_long(argc, argv, "choO", long_opts, NULL)) != -1) {
10285                 switch (c) {
10286                 case 'c':
10287                         flags |= LU_HEAT_FLAG_CLEAR;
10288                         break;
10289                 case 'o':
10290                         flags |= LU_HEAT_FLAG_CLEAR;
10291                         flags |= LU_HEAT_FLAG_OFF;
10292                         break;
10293                 case 'O':
10294                         flags &= ~LU_HEAT_FLAG_OFF;
10295                         break;
10296                 default:
10297                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10298                                 progname, argv[optind - 1]);
10299                         /* fallthrough */
10300                 case 'h':
10301                         return CMD_HELP;
10302                 }
10303         }
10304
10305         if (argc <= optind) {
10306                 fprintf(stderr, "%s: please give one or more file names\n",
10307                         argv[0]);
10308                 return CMD_HELP;
10309         }
10310
10311         while (optind < argc) {
10312                 path = argv[optind++];
10313
10314                 fd = open(path, O_RDONLY);
10315                 if (fd < 0) {
10316                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
10317                                 argv[0], path, strerror(errno));
10318                         rc2 = -errno;
10319                         goto next;
10320                 }
10321
10322                 rc2 = llapi_heat_set(fd, flags);
10323                 close(fd);
10324                 if (rc2 < 0) {
10325                         fprintf(stderr,
10326                                 "%s: cannot setflags heat of file '%s': %s\n",
10327                                 argv[0], path, strerror(errno));
10328                         goto next;
10329                 }
10330 next:
10331                 if (rc == 0 && rc2 < 0)
10332                         rc = rc2;
10333         }
10334         return rc;
10335 }
10336
10337 /**
10338  * The input string contains a comma delimited list of component ids and
10339  * ranges, for example "1,2-4,7".
10340  */
10341 static int parse_mirror_ids(__u16 *ids, int size, char *arg)
10342 {
10343         bool end_of_loop = false;
10344         char *ptr = NULL;
10345         int nr = 0;
10346         int rc;
10347
10348         if (!arg)
10349                 return -EINVAL;
10350
10351         while (!end_of_loop) {
10352                 int start_index;
10353                 int end_index;
10354                 int i;
10355                 char *endptr = NULL;
10356
10357                 rc = -EINVAL;
10358                 ptr = strchrnul(arg, ',');
10359                 end_of_loop = *ptr == '\0';
10360                 *ptr = '\0';
10361
10362                 start_index = strtol(arg, &endptr, 0);
10363                 if (endptr == arg) /* no data at all */
10364                         break;
10365                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
10366                         break;
10367                 if (start_index < 0)
10368                         break;
10369
10370                 end_index = start_index;
10371                 if (*endptr == '-') {
10372                         end_index = strtol(endptr + 1, &endptr, 0);
10373                         if (*endptr != '\0')
10374                                 break;
10375                         if (end_index < start_index)
10376                                 break;
10377                 }
10378
10379                 for (i = start_index; i <= end_index && size > 0; i++) {
10380                         int j;
10381
10382                         /* remove duplicate */
10383                         for (j = 0; j < nr; j++) {
10384                                 if (ids[j] == i)
10385                                         break;
10386                         }
10387                         if (j == nr) { /* no duplicate */
10388                                 ids[nr++] = i;
10389                                 --size;
10390                         }
10391                 }
10392
10393                 if (size == 0 && i < end_index)
10394                         break;
10395
10396                 *ptr = ',';
10397                 arg = ++ptr;
10398                 rc = 0;
10399         }
10400         if (!end_of_loop && ptr)
10401                 *ptr = ',';
10402
10403         return rc < 0 ? rc : nr;
10404 }
10405
10406 /**
10407  * struct verify_mirror_id - Mirror id to be verified.
10408  * @mirror_id:   A specified mirror id.
10409  * @is_valid_id: @mirror_id is valid or not in the mirrored file.
10410  */
10411 struct verify_mirror_id {
10412         __u16 mirror_id;
10413         bool is_valid_id;
10414 };
10415
10416 /**
10417  * compare_mirror_ids() - Compare mirror ids.
10418  * @layout: Mirror component list.
10419  * @cbdata: Callback data in verify_mirror_id structure.
10420  *
10421  * This is a callback function called by llapi_layout_comp_iterate()
10422  * to compare the specified mirror id with the one in the current
10423  * component of @layout. If they are the same, then the specified
10424  * mirror id is valid.
10425  *
10426  * Return: a negative error code on failure or
10427  *         LLAPI_LAYOUT_ITER_CONT: Proceed iteration
10428  *         LLAPI_LAYOUT_ITER_STOP: Stop iteration
10429  */
10430 static inline
10431 int compare_mirror_ids(struct llapi_layout *layout, void *cbdata)
10432 {
10433         struct verify_mirror_id *mirror_id_cbdata =
10434                                  (struct verify_mirror_id *)cbdata;
10435         uint32_t mirror_id;
10436         int rc = 0;
10437
10438         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
10439         if (rc < 0) {
10440                 rc = -errno;
10441                 fprintf(stderr,
10442                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
10443                         progname, strerror(errno));
10444                 return rc;
10445         }
10446
10447         if (mirror_id_cbdata->mirror_id == mirror_id) {
10448                 mirror_id_cbdata->is_valid_id = true;
10449                 return LLAPI_LAYOUT_ITER_STOP;
10450         }
10451
10452         return LLAPI_LAYOUT_ITER_CONT;
10453 }
10454
10455 /**
10456  * verify_mirror_ids() - Verify specified mirror ids.
10457  * @fname:      Mirrored file name.
10458  * @mirror_ids: Specified mirror ids to be verified.
10459  * @ids_nr:     Number of specified mirror ids.
10460  *
10461  * This function verifies that specified @mirror_ids are valid
10462  * in the mirrored file @fname.
10463  *
10464  * Return: 0 on success or a negative error code on failure.
10465  */
10466 static inline
10467 int verify_mirror_ids(const char *fname, __u16 *mirror_ids, int ids_nr)
10468 {
10469         struct llapi_layout *layout = NULL;
10470         struct verify_mirror_id mirror_id_cbdata = { 0 };
10471         struct stat stbuf;
10472         uint32_t flr_state;
10473         int i;
10474         int fd;
10475         int rc = 0;
10476         int rc2 = 0;
10477
10478         if (ids_nr <= 0)
10479                 return -EINVAL;
10480
10481         if (stat(fname, &stbuf) < 0) {
10482                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
10483                         progname, fname, strerror(errno));
10484                 rc = -errno;
10485                 goto error;
10486         }
10487
10488         if (!S_ISREG(stbuf.st_mode)) {
10489                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
10490                         progname, fname);
10491                 rc = -EINVAL;
10492                 goto error;
10493         }
10494
10495         fd = open(fname, O_DIRECT | O_RDONLY);
10496         if (fd < 0) {
10497                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
10498                         progname, fname, strerror(errno));
10499                 rc = -errno;
10500                 goto error;
10501         }
10502
10503         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
10504         if (rc < 0) {
10505                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
10506                         progname, fname, strerror(errno));
10507                 goto close_fd;
10508         }
10509
10510         layout = llapi_layout_get_by_fd(fd, 0);
10511         if (!layout) {
10512                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
10513                         progname, fname, strerror(errno));
10514                 rc = -errno;
10515                 llapi_lease_release(fd);
10516                 goto close_fd;
10517         }
10518
10519         rc = llapi_layout_flags_get(layout, &flr_state);
10520         if (rc < 0) {
10521                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
10522                         progname, fname, strerror(errno));
10523                 rc = -errno;
10524                 goto free_layout;
10525         }
10526
10527         flr_state &= LCM_FL_FLR_MASK;
10528         switch (flr_state) {
10529         case LCM_FL_NONE:
10530                 rc = -EINVAL;
10531                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
10532                         progname, fname, llapi_layout_flags_string(flr_state));
10533                 goto free_layout;
10534         default:
10535                 break;
10536         }
10537
10538         rc2 = 0;
10539         for (i = 0; i < ids_nr; i++) {
10540                 mirror_id_cbdata.mirror_id = mirror_ids[i];
10541                 mirror_id_cbdata.is_valid_id = false;
10542
10543                 rc = llapi_layout_comp_iterate(layout, compare_mirror_ids,
10544                                                &mirror_id_cbdata);
10545                 if (rc < 0) {
10546                         rc = -errno;
10547                         fprintf(stderr,
10548                                 "%s: '%s' failed to verify mirror id: %u.\n",
10549                                 progname, fname, mirror_ids[i]);
10550                         goto free_layout;
10551                 }
10552
10553                 if (!mirror_id_cbdata.is_valid_id) {
10554                         rc2 = -EINVAL;
10555                         fprintf(stderr,
10556                                 "%s: '%s' invalid specified mirror id: %u.\n",
10557                                 progname, fname, mirror_ids[i]);
10558                 }
10559         }
10560         rc = rc2;
10561
10562 free_layout:
10563         llapi_layout_free(layout);
10564         llapi_lease_release(fd);
10565 close_fd:
10566         close(fd);
10567 error:
10568         return rc;
10569 }
10570
10571 static inline
10572 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
10573                            __u16 *mirror_ids, int ids_nr)
10574 {
10575         struct llapi_resync_comp comp_array[1024] = { { 0 } };
10576         struct llapi_layout *layout;
10577         struct stat stbuf;
10578         uint32_t flr_state;
10579         uint64_t start;
10580         uint64_t end;
10581         int comp_size = 0;
10582         int idx;
10583         int fd;
10584         int rc;
10585         int rc2;
10586
10587         if (stat(fname, &stbuf) < 0) {
10588                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
10589                         progname, fname, strerror(errno));
10590                 rc = -errno;
10591                 goto error;
10592         }
10593         if (!S_ISREG(stbuf.st_mode)) {
10594                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
10595                         progname, fname);
10596                 rc = -EINVAL;
10597                 goto error;
10598         }
10599
10600         fd = open(fname, O_DIRECT | O_RDWR);
10601         if (fd < 0) {
10602                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
10603                         progname, fname, strerror(errno));
10604                 rc = -errno;
10605                 goto error;
10606         }
10607
10608         layout = llapi_layout_get_by_fd(fd, 0);
10609         if (!layout) {
10610                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
10611                         progname, fname, strerror(errno));
10612                 rc = -errno;
10613                 goto close_fd;
10614         }
10615
10616         rc = llapi_layout_flags_get(layout, &flr_state);
10617         if (rc) {
10618                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
10619                         progname, fname, strerror(errno));
10620                 rc = -errno;
10621                 goto free_layout;
10622         }
10623
10624         flr_state &= LCM_FL_FLR_MASK;
10625         if (flr_state == LCM_FL_NONE) {
10626                 rc = -EINVAL;
10627                 fprintf(stderr, "%s: '%s' is not a FLR file.\n",
10628                         progname, fname);
10629                 goto free_layout;
10630         }
10631
10632         /* get stale component info */
10633         comp_size = llapi_mirror_find_stale(layout, comp_array,
10634                                             ARRAY_SIZE(comp_array),
10635                                             mirror_ids, ids_nr);
10636         if (comp_size <= 0) {
10637                 rc = comp_size;
10638                 goto free_layout;
10639         }
10640
10641         ioc->lil_mode = LL_LEASE_WRLCK;
10642         ioc->lil_flags = LL_LEASE_RESYNC;
10643         rc = llapi_lease_set(fd, ioc);
10644         if (rc < 0) {
10645                 if (rc == -EALREADY)
10646                         rc = 0;
10647                 else
10648                         fprintf(stderr,
10649                             "%s: '%s' llapi_lease_get_ext resync failed: %s.\n",
10650                                 progname, fname, strerror(-rc));
10651                 goto free_layout;
10652         }
10653
10654         /* get the read range [start, end) */
10655         start = comp_array[0].lrc_start;
10656         end = comp_array[0].lrc_end;
10657         for (idx = 1; idx < comp_size; idx++) {
10658                 if (comp_array[idx].lrc_start < start)
10659                         start = comp_array[idx].lrc_start;
10660                 if (end < comp_array[idx].lrc_end)
10661                         end = comp_array[idx].lrc_end;
10662         }
10663
10664         rc = llapi_lease_check(fd);
10665         if (rc != LL_LEASE_WRLCK) {
10666                 fprintf(stderr, "%s: '%s' lost lease lock.\n",
10667                         progname, fname);
10668                 goto free_layout;
10669         }
10670
10671         rc = llapi_mirror_resync_many(fd, layout, comp_array, comp_size,
10672                                       start, end);
10673         if (rc < 0)
10674                 fprintf(stderr, "%s: '%s' llapi_mirror_resync_many: %s.\n",
10675                         progname, fname, strerror(-rc));
10676
10677         /* need to do the lease unlock even resync fails */
10678         ioc->lil_mode = LL_LEASE_UNLCK;
10679         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
10680         ioc->lil_count = 0;
10681         for (idx = 0; idx < comp_size; idx++) {
10682                 if (comp_array[idx].lrc_synced) {
10683                         ioc->lil_ids[ioc->lil_count] = comp_array[idx].lrc_id;
10684                         ioc->lil_count++;
10685                 }
10686         }
10687
10688         rc2 = llapi_lease_set(fd, ioc);
10689         /**
10690          * llapi_lease_set returns lease mode when it request to unlock
10691          * the lease lock.
10692          */
10693         if (rc2 <= 0) {
10694                 /* rc2 == 0 means lost lease lock */
10695                 if (rc2 == 0 && rc == 0)
10696                         rc = -EBUSY;
10697                 fprintf(stderr, "%s: resync file '%s' failed: %s.\n",
10698                         progname, fname,
10699                         rc2 == 0 ? "lost lease lock" : strerror(-rc2));
10700         }
10701
10702 free_layout:
10703         llapi_layout_free(layout);
10704 close_fd:
10705         close(fd);
10706 error:
10707         return rc;
10708 }
10709
10710 static inline int lfs_mirror_resync(int argc, char **argv)
10711 {
10712         struct option long_opts[] = {
10713         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10714         { .val = 'o',   .name = "only",         .has_arg = required_argument },
10715         { .name = NULL } };
10716         struct ll_ioc_lease *ioc = NULL;
10717         __u16 mirror_ids[128] = { 0 };
10718         int ids_nr = 0;
10719         int c;
10720         int rc = 0;
10721
10722         while ((c = getopt_long(argc, argv, "ho:", long_opts, NULL)) >= 0) {
10723                 switch (c) {
10724                 case 'o':
10725                         rc = parse_mirror_ids(mirror_ids,
10726                                         sizeof(mirror_ids) / sizeof(__u16),
10727                                         optarg);
10728                         if (rc < 0) {
10729                                 fprintf(stderr,
10730                                         "%s: bad mirror ids '%s'.\n",
10731                                         argv[0], optarg);
10732                                 goto error;
10733                         }
10734                         ids_nr = rc;
10735                         break;
10736                 default:
10737                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10738                                 progname, argv[optind - 1]);
10739                         /* fallthrough */
10740                 case 'h':
10741                         rc = CMD_HELP;
10742                         goto error;
10743                 }
10744         }
10745
10746         if (argc == optind) {
10747                 fprintf(stderr, "%s: no file name given.\n", argv[0]);
10748                 rc = CMD_HELP;
10749                 goto error;
10750         }
10751
10752         if (ids_nr > 0 && argc > optind + 1) {
10753                 fprintf(stderr,
10754                     "%s: option '--only' cannot be used upon multiple files.\n",
10755                         argv[0]);
10756                 rc = CMD_HELP;
10757                 goto error;
10758         }
10759
10760         if (ids_nr > 0) {
10761                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
10762                 if (rc < 0)
10763                         goto error;
10764         }
10765
10766         /* set the lease on the file */
10767         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
10768         if (!ioc) {
10769                 fprintf(stderr, "%s: cannot alloc id array for ioc: %s.\n",
10770                         argv[0], strerror(errno));
10771                 rc = -errno;
10772                 goto error;
10773         }
10774
10775         for (; optind < argc; optind++) {
10776                 rc = lfs_mirror_resync_file(argv[optind], ioc,
10777                                             mirror_ids, ids_nr);
10778                 /* ignore previous file's error, continue with next file */
10779
10780                 /* reset ioc */
10781                 memset(ioc, 0, sizeof(*ioc) + sizeof(__u32) * 4096);
10782         }
10783
10784         free(ioc);
10785 error:
10786         return rc;
10787 }
10788
10789 static inline int verify_mirror_id_by_fd(int fd, __u16 mirror_id)
10790 {
10791         struct llapi_layout *layout;
10792         int rc;
10793
10794         layout = llapi_layout_get_by_fd(fd, 0);
10795         if (!layout) {
10796                 fprintf(stderr, "could not get layout.\n");
10797                 return  -EINVAL;
10798         }
10799
10800         rc = llapi_layout_comp_iterate(layout, find_mirror_id, &mirror_id);
10801         if (rc < 0) {
10802                 fprintf(stderr, "failed to iterate layout\n");
10803                 llapi_layout_free(layout);
10804
10805                 return rc;
10806         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
10807                 fprintf(stderr, "does not find mirror with ID %u\n", mirror_id);
10808                 llapi_layout_free(layout);
10809
10810                 return -EINVAL;
10811         }
10812         llapi_layout_free(layout);
10813
10814         return 0;
10815 }
10816
10817 /**
10818  * Check whether two files are the same file
10819  * \retval      0  same file
10820  * \retval      1  not the same file
10821  * \retval      <0 error code
10822  */
10823 static inline int check_same_file(int fd, const char *f2)
10824 {
10825         struct stat stbuf1;
10826         struct stat stbuf2;
10827
10828         if (fstat(fd, &stbuf1) < 0)
10829                 return -errno;
10830
10831         if (stat(f2, &stbuf2) < 0)
10832                 return 1;
10833
10834         if (stbuf1.st_rdev == stbuf2.st_rdev &&
10835             stbuf1.st_ino == stbuf2.st_ino)
10836                 return 0;
10837
10838         return 1;
10839 }
10840
10841 static inline int lfs_mirror_read(int argc, char **argv)
10842 {
10843         int rc = CMD_HELP;
10844         __u16 mirror_id = 0;
10845         const char *outfile = NULL;
10846         char *fname;
10847         int fd = 0;
10848         int outfd;
10849         int c;
10850         void *buf;
10851         const size_t buflen = 4 << 20;
10852         off_t pos;
10853         struct option long_opts[] = {
10854         { .val = 'h',   .name = "help",         .has_arg = no_argument },
10855         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
10856         { .val = 'o',   .name = "outfile",      .has_arg = required_argument },
10857         { .name = NULL } };
10858
10859         while ((c = getopt_long(argc, argv, "hN:o:", long_opts, NULL)) >= 0) {
10860                 char *end;
10861
10862                 switch (c) {
10863                 case 'N': {
10864                         unsigned long int id;
10865
10866                         errno = 0;
10867                         id = strtoul(optarg, &end, 0);
10868                         if (errno != 0 || *end != '\0' || id == 0 ||
10869                             id > UINT16_MAX) {
10870                                 fprintf(stderr,
10871                                         "%s %s: invalid mirror ID '%s'\n",
10872                                         progname, argv[0], optarg);
10873                                 return rc;
10874                         }
10875
10876                         mirror_id = (__u16)id;
10877                         break;
10878                 }
10879                 case 'o':
10880                         outfile = optarg;
10881                         break;
10882                 default:
10883                         fprintf(stderr, "%s: unrecognized option '%s'\n",
10884                                 progname, argv[optind - 1]);
10885                         /* fallthrough */
10886                 case 'h':
10887                         return CMD_HELP;
10888                 }
10889         }
10890
10891         if (argc == optind) {
10892                 fprintf(stderr, "%s %s: no mirrored file provided\n",
10893                         progname, argv[0]);
10894                 return rc;
10895         } else if (argc > optind + 1) {
10896                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
10897                 return rc;
10898         }
10899
10900         if (mirror_id == 0) {
10901                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
10902                         progname, argv[0]);
10903                 return rc;
10904         }
10905
10906         /* open mirror file */
10907         fname = argv[optind];
10908         fd = open(fname, O_DIRECT | O_RDONLY);
10909         if (fd < 0) {
10910                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
10911                         progname, argv[0], fname, strerror(errno));
10912                 return rc;
10913         }
10914
10915         /* verify mirror id */
10916         rc = verify_mirror_id_by_fd(fd, mirror_id);
10917         if (rc) {
10918                 fprintf(stderr,
10919                         "%s %s: cannot find mirror with ID %u in '%s'\n",
10920                         progname, argv[0], mirror_id, fname);
10921                 goto close_fd;
10922         }
10923
10924         /* open output file - O_EXCL ensures output is not the same as input */
10925         if (outfile) {
10926                 outfd = open(outfile, O_EXCL | O_WRONLY | O_CREAT, 0644);
10927                 if (outfd < 0) {
10928                         fprintf(stderr, "%s %s: cannot create file '%s': %s\n",
10929                                 progname, argv[0], outfile, strerror(errno));
10930                         rc = -errno;
10931                         goto close_fd;
10932                 }
10933         } else {
10934                 outfd = STDOUT_FILENO;
10935         }
10936
10937         /* allocate buffer */
10938         rc = posix_memalign(&buf, sysconf(_SC_PAGESIZE), buflen);
10939         if (rc) {
10940                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
10941                                 progname, argv[0], rc);
10942                 goto close_outfd;
10943         }
10944
10945         pos = 0;
10946         while (1) {
10947                 ssize_t bytes_read;
10948                 ssize_t written = 0;
10949
10950                 bytes_read = llapi_mirror_read(fd, mirror_id, buf, buflen, pos);
10951                 if (bytes_read < 0) {
10952                         rc = bytes_read;
10953                         fprintf(stderr,
10954                                 "%s %s: fail to read data from mirror %u: %s\n",
10955                                 progname, argv[0], mirror_id, strerror(-rc));
10956                         goto free_buf;
10957                 }
10958
10959                 /* EOF reached */
10960                 if (bytes_read == 0)
10961                         break;
10962
10963                 while (written < bytes_read) {
10964                         ssize_t written2;
10965
10966                         written2 = write(outfd, buf + written,
10967                                          bytes_read - written);
10968                         if (written2 < 0) {
10969                                 fprintf(stderr,
10970                                         "%s %s: fail to write %s: %s\n",
10971                                         progname, argv[0], outfile ? : "STDOUT",
10972                                         strerror(errno));
10973                                 rc = -errno;
10974                                 goto free_buf;
10975                         }
10976                         written += written2;
10977                 }
10978
10979                 if (written != bytes_read) {
10980                         fprintf(stderr,
10981                 "%s %s: written %ld bytes does not match with %ld read.\n",
10982                                 progname, argv[0], written, bytes_read);
10983                         rc = -EIO;
10984                         goto free_buf;
10985                 }
10986
10987                 pos += bytes_read;
10988         }
10989
10990         fsync(outfd);
10991         rc = 0;
10992
10993 free_buf:
10994         free(buf);
10995 close_outfd:
10996         if (outfile)
10997                 close(outfd);
10998 close_fd:
10999         close(fd);
11000
11001         return rc;
11002 }
11003
11004 static inline int lfs_mirror_write(int argc, char **argv)
11005 {
11006         int rc = CMD_HELP;
11007         __u16 mirror_id = 0;
11008         const char *inputfile = NULL;
11009         char *fname;
11010         int fd = 0;
11011         int inputfd;
11012         int c;
11013         void *buf;
11014         const size_t buflen = 4 << 20;
11015         off_t pos;
11016         size_t page_size = sysconf(_SC_PAGESIZE);
11017         struct ll_ioc_lease_id ioc;
11018         struct option long_opts[] = {
11019         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11020         { .val = 'i',   .name = "inputfile",    .has_arg = required_argument },
11021         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
11022         { .name = NULL } };
11023
11024         while ((c = getopt_long(argc, argv, "hi:N:", long_opts, NULL)) >= 0) {
11025                 char *end;
11026
11027                 switch (c) {
11028                 case 'N': {
11029                         unsigned long int id;
11030
11031                         errno = 0;
11032                         id = strtoul(optarg, &end, 0);
11033                         if (errno != 0 || *end != '\0' || id == 0 ||
11034                             id > UINT16_MAX) {
11035                                 fprintf(stderr,
11036                                         "%s %s: invalid mirror ID '%s'\n",
11037                                         progname, argv[0], optarg);
11038                                 return rc;
11039                         }
11040
11041                         mirror_id = (__u16)id;
11042                         break;
11043                 }
11044                 case 'i':
11045                         inputfile = optarg;
11046                         break;
11047                 default:
11048                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11049                                 progname, argv[optind - 1]);
11050                         /* fallthrough */
11051                 case 'h':
11052                         return CMD_HELP;
11053                 }
11054         }
11055
11056         if (argc == optind) {
11057                 fprintf(stderr, "%s %s: no mirrored file provided\n",
11058                         progname, argv[0]);
11059                 return rc;
11060         } else if (argc > optind + 1) {
11061                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
11062                 return rc;
11063         }
11064
11065         if (mirror_id == 0) {
11066                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
11067                         progname, argv[0]);
11068                 return rc;
11069         }
11070
11071         /* open mirror file */
11072         fname = argv[optind];
11073         fd = open(fname, O_DIRECT | O_WRONLY);
11074         if (fd < 0) {
11075                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
11076                         progname, argv[0], fname, strerror(errno));
11077                 return rc;
11078         }
11079
11080         /* verify mirror id */
11081         rc = verify_mirror_id_by_fd(fd, mirror_id);
11082         if (rc) {
11083                 fprintf(stderr,
11084                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11085                         progname, argv[0], mirror_id, fname);
11086                 goto close_fd;
11087         }
11088
11089         /* open input file */
11090         if (inputfile) {
11091                 rc = check_same_file(fd, inputfile);
11092                 if (rc == 0) {
11093                         fprintf(stderr,
11094                         "%s %s: input file cannot be the mirrored file\n",
11095                                 progname, argv[0]);
11096                         goto close_fd;
11097                 }
11098                 if (rc < 0)
11099                         goto close_fd;
11100
11101                 inputfd = open(inputfile, O_RDONLY, 0644);
11102                 if (inputfd < 0) {
11103                         fprintf(stderr, "%s %s: cannot open file '%s': %s\n",
11104                                 progname, argv[0], inputfile, strerror(errno));
11105                         rc = -errno;
11106                         goto close_fd;
11107                 }
11108         } else {
11109                 inputfd = STDIN_FILENO;
11110         }
11111
11112         /* allocate buffer */
11113         rc = posix_memalign(&buf, page_size, buflen);
11114         if (rc) {
11115                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
11116                         progname, argv[0], rc);
11117                 goto close_inputfd;
11118         }
11119
11120         /* prepare target mirror components instantiation */
11121         ioc.lil_mode = LL_LEASE_WRLCK;
11122         ioc.lil_flags = LL_LEASE_RESYNC;
11123         ioc.lil_mirror_id = mirror_id;
11124         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
11125         if (rc < 0) {
11126                 fprintf(stderr,
11127                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
11128                         progname, argv[0], fname, strerror(errno));
11129                 goto free_buf;
11130         }
11131
11132         pos = 0;
11133         while (1) {
11134                 ssize_t bytes_read;
11135                 ssize_t written;
11136                 size_t to_write;
11137
11138                 rc = llapi_lease_check(fd);
11139                 if (rc != LL_LEASE_WRLCK) {
11140                         fprintf(stderr, "%s %s: '%s' lost lease lock\n",
11141                                 progname, argv[0], fname);
11142                         goto free_buf;
11143                 }
11144
11145                 bytes_read = read(inputfd, buf, buflen);
11146                 if (bytes_read < 0) {
11147                         rc = bytes_read;
11148                         fprintf(stderr,
11149                                 "%s %s: fail to read data from '%s': %s\n",
11150                                 progname, argv[0], inputfile ? : "STDIN",
11151                                 strerror(errno));
11152                         rc = -errno;
11153                         goto free_buf;
11154                 }
11155
11156                 /* EOF reached */
11157                 if (bytes_read == 0)
11158                         break;
11159
11160                 /* round up to page align to make direct IO happy. */
11161                 to_write = (bytes_read + page_size - 1) & ~(page_size - 1);
11162
11163                 written = llapi_mirror_write(fd, mirror_id, buf, to_write,
11164                                              pos);
11165                 if (written < 0) {
11166                         rc = written;
11167                         fprintf(stderr,
11168                               "%s %s: fail to write to mirror %u: %s\n",
11169                                 progname, argv[0], mirror_id,
11170                                 strerror(-rc));
11171                         goto free_buf;
11172                 }
11173
11174                 pos += bytes_read;
11175         }
11176
11177         if (pos & (page_size - 1)) {
11178                 rc = llapi_mirror_truncate(fd, mirror_id, pos);
11179                 if (rc < 0)
11180                         goto free_buf;
11181         }
11182
11183         ioc.lil_mode = LL_LEASE_UNLCK;
11184         ioc.lil_flags = LL_LEASE_RESYNC_DONE;
11185         ioc.lil_count = 0;
11186         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
11187         if (rc <= 0) {
11188                 if (rc == 0)
11189                         rc = -EBUSY;
11190                 fprintf(stderr,
11191                         "%s %s: release lease lock of '%s' failed: %s\n",
11192                         progname, argv[0], fname, strerror(errno));
11193                 goto free_buf;
11194         }
11195
11196         rc = 0;
11197
11198 free_buf:
11199         free(buf);
11200 close_inputfd:
11201         if (inputfile)
11202                 close(inputfd);
11203 close_fd:
11204         close(fd);
11205
11206         return rc;
11207 }
11208
11209 static inline int get_other_mirror_ids(int fd, __u16 *ids, __u16 exclude_id)
11210 {
11211         struct llapi_layout *layout;
11212         struct collect_ids_data cid = { .cid_ids = ids,
11213                                         .cid_count = 0,
11214                                         .cid_exclude = exclude_id, };
11215         int rc;
11216
11217         layout = llapi_layout_get_by_fd(fd, 0);
11218         if (!layout) {
11219                 fprintf(stderr, "could not get layout\n");
11220                 return -EINVAL;
11221         }
11222
11223         rc = llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
11224         if (rc < 0) {
11225                 fprintf(stderr, "failed to iterate layout\n");
11226                 llapi_layout_free(layout);
11227
11228                 return rc;
11229         }
11230         llapi_layout_free(layout);
11231
11232         return cid.cid_count;
11233 }
11234
11235 static inline int lfs_mirror_copy(int argc, char **argv)
11236 {
11237         int rc = CMD_HELP;
11238         __u16 read_mirror_id = 0;
11239         __u16 ids[128] = { 0 };
11240         int count = 0;
11241         struct llapi_layout *layout = NULL;
11242         struct llapi_resync_comp comp_array[1024] = { { 0 } };
11243         int comp_size = 0;
11244         char *fname;
11245         int fd = 0;
11246         int c;
11247         int i;
11248         ssize_t copied;
11249         struct ll_ioc_lease *ioc = NULL;
11250         struct ll_ioc_lease_id *resync_ioc;
11251         struct option long_opts[] = {
11252         { .val = 'h',   .name = "help",         .has_arg = no_argument },
11253         { .val = 'i',   .name = "read-mirror",  .has_arg = required_argument },
11254         { .val = 'o',   .name = "write-mirror", .has_arg = required_argument },
11255         { .name = NULL } };
11256         char cmd[PATH_MAX];
11257
11258         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
11259         progname = cmd;
11260         while ((c = getopt_long(argc, argv, "hi:o:", long_opts, NULL)) >= 0) {
11261                 char *end;
11262
11263                 switch (c) {
11264                 case 'i': {
11265                         unsigned long int id;
11266
11267                         errno = 0;
11268                         id = strtoul(optarg, &end, 0);
11269                         if (errno != 0 || *end != '\0' || id == 0 ||
11270                             id > UINT16_MAX) {
11271                                 fprintf(stderr,
11272                                         "%s: invalid read mirror ID '%s'\n",
11273                                         progname, optarg);
11274                                 return rc;
11275                         }
11276
11277                         read_mirror_id = (__u16)id;
11278                         break;
11279                 }
11280                 case 'o':
11281                         if (!strcmp(optarg, "-1")) {
11282                                 /* specify all other mirrors */
11283                                 ids[0] = (__u16)-1;
11284                                 count = 1;
11285                         } else {
11286                                 count = parse_mirror_ids((__u16 *)ids,
11287                                                          ARRAY_SIZE(ids),
11288                                                          optarg);
11289                                 if (count < 0)
11290                                         return rc;
11291                         }
11292                         break;
11293                 default:
11294                         fprintf(stderr, "%s: unrecognized option '%s'\n",
11295                                 progname, argv[optind - 1]);
11296                         /* fallthrough */
11297                 case 'h':
11298                         return CMD_HELP;
11299                 }
11300         }
11301
11302         if (argc == optind) {
11303                 fprintf(stderr, "%s %s: no mirrored file provided\n",
11304                         progname, argv[0]);
11305                 return rc;
11306         } else if (argc > optind + 1) {
11307                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
11308                 return rc;
11309         }
11310
11311         if (read_mirror_id == 0) {
11312                 fprintf(stderr,
11313                         "%s %s: no valid read mirror ID %d is provided\n",
11314                         progname, argv[0], read_mirror_id);
11315                 return rc;
11316         }
11317
11318         if (count == 0) {
11319                 fprintf(stderr,
11320                         "%s %s: no write mirror ID is provided\n",
11321                         progname, argv[0]);
11322                 return rc;
11323         }
11324
11325         for (i = 0; i < count; i++) {
11326                 if (read_mirror_id == ids[i]) {
11327                         fprintf(stderr,
11328                         "%s %s: read and write mirror ID cannot be the same\n",
11329                                 progname, argv[0]);
11330                         return rc;
11331                 }
11332         }
11333
11334         /* open mirror file */
11335         fname = argv[optind];
11336
11337         fd = open(fname, O_DIRECT | O_RDWR);
11338         if (fd < 0) {
11339                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
11340                         progname, argv[0], fname, strerror(errno));
11341                 return rc;
11342         }
11343
11344         /* write to all other mirrors */
11345         if (ids[0] == (__u16)-1) {
11346                 count = get_other_mirror_ids(fd, ids, read_mirror_id);
11347                 if (count <= 0) {
11348                         rc = count;
11349                         fprintf(stderr,
11350                         "%s %s: failed to get other mirror ids in '%s': %d\n",
11351                                 progname, argv[0], fname, rc);
11352                         goto close_fd;
11353                 }
11354         }
11355
11356         /* verify mirror id */
11357         rc = verify_mirror_id_by_fd(fd, read_mirror_id);
11358         if (rc) {
11359                 fprintf(stderr,
11360                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11361                         progname, argv[0], read_mirror_id, fname);
11362                 goto close_fd;
11363         }
11364
11365         for (i = 0; i < count; i++) {
11366                 rc = verify_mirror_id_by_fd(fd, ids[i]);
11367                 if (rc) {
11368                         fprintf(stderr,
11369                         "%s %s: cannot find mirror with ID %u in '%s'\n",
11370                                 progname, argv[0], ids[i], fname);
11371                         goto close_fd;
11372                 }
11373         }
11374
11375         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
11376         if (!ioc) {
11377                 fprintf(stderr,
11378                         "%s %s: cannot alloc comp id array for ioc: %s\n",
11379                         progname, argv[0], strerror(errno));
11380                 rc = -errno;
11381                 goto close_fd;
11382         }
11383
11384         /* get stale component info */
11385         layout = llapi_layout_get_by_fd(fd, 0);
11386         if (!layout) {
11387                 fprintf(stderr, "%s %s: failed to get layout of '%s': %s\n",
11388                         progname, argv[0], fname, strerror(errno));
11389                 rc = -errno;
11390                 goto free_ioc;
11391         }
11392         comp_size = llapi_mirror_find_stale(layout, comp_array,
11393                                             ARRAY_SIZE(comp_array),
11394                                             ids, count);
11395         llapi_layout_free(layout);
11396         if (comp_size < 0) {
11397                 rc = comp_size;
11398                 goto free_ioc;
11399         }
11400
11401         /* prepare target mirror components instantiation */
11402         resync_ioc = (struct ll_ioc_lease_id *)ioc;
11403         resync_ioc->lil_mode = LL_LEASE_WRLCK;
11404         resync_ioc->lil_flags = LL_LEASE_RESYNC;
11405         if (count == 1)
11406                 resync_ioc->lil_mirror_id = ids[0];
11407         else
11408                 resync_ioc->lil_mirror_id = read_mirror_id | MIRROR_ID_NEG;
11409         rc = llapi_lease_set(fd, ioc);
11410         if (rc < 0) {
11411                 fprintf(stderr,
11412                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
11413                         progname, argv[0], fname, strerror(errno));
11414                 goto free_ioc;
11415         }
11416
11417         copied = llapi_mirror_copy_many(fd, read_mirror_id, ids, count);
11418         if (copied < 0) {
11419                 rc = copied;
11420                 fprintf(stderr, "%s %s: copy error: %d\n",
11421                         progname, argv[0], rc);
11422                 goto free_ioc;
11423         }
11424
11425         fprintf(stdout, "mirror copied successfully: ");
11426         for (i = 0; i < copied; i++)
11427                 fprintf(stdout, "%d ", ids[i]);
11428         fprintf(stdout, "\n");
11429
11430         ioc->lil_mode = LL_LEASE_UNLCK;
11431         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
11432         ioc->lil_count = 0;
11433         for (i = 0; i < comp_size; i++) {
11434                 int j;
11435
11436                 for (j = 0; j < copied; j++) {
11437                         if (comp_array[i].lrc_mirror_id != ids[j])
11438                                 continue;
11439
11440                         ioc->lil_ids[ioc->lil_count] = comp_array[i].lrc_id;
11441                         ioc->lil_count++;
11442                 }
11443         }
11444         rc = llapi_lease_set(fd, ioc);
11445         if (rc <= 0) {
11446                 if (rc == 0)
11447                         rc = -EBUSY;
11448                 fprintf(stderr,
11449                         "%s %s: release lease lock of '%s' failed: %s\n",
11450                         progname, argv[0], fname, strerror(errno));
11451                 goto free_ioc;
11452         }
11453
11454         rc = 0;
11455
11456 free_ioc:
11457         free(ioc);
11458 close_fd:
11459         close(fd);
11460
11461         return rc;
11462 }
11463
11464 /**
11465  * struct verify_chunk - Mirror chunk to be verified.
11466  * @chunk:        [start, end) of the chunk.
11467  * @mirror_count: Number of mirror ids in @mirror_id array.
11468  * @mirror_id:    Array of valid mirror ids that cover the chunk.
11469  */
11470 struct verify_chunk {
11471         struct lu_extent chunk;
11472         unsigned int mirror_count;
11473         __u16 mirror_id[LUSTRE_MIRROR_COUNT_MAX];
11474 };
11475
11476 /**
11477  * print_chunks() - Print chunk information.
11478  * @fname:       Mirrored file name.
11479  * @chunks:      Array of chunks.
11480  * @chunk_count: Number of chunks in @chunks array.
11481  *
11482  * This function prints [start, end) of each chunk in @chunks
11483  * for mirrored file @fname, and also prints the valid mirror ids
11484  * that cover the chunk.
11485  *
11486  * Return: void.
11487  */
11488 static inline
11489 void print_chunks(const char *fname, struct verify_chunk *chunks,
11490                   int chunk_count)
11491 {
11492         int i;
11493         int j;
11494
11495         fprintf(stdout, "Chunks to be verified in %s:\n", fname);
11496         for (i = 0; i < chunk_count; i++) {
11497                 fprintf(stdout, DEXT, PEXT(&chunks[i].chunk));
11498
11499                 if (chunks[i].mirror_count == 0)
11500                         fprintf(stdout, "\t[");
11501                 else {
11502                         fprintf(stdout, "\t[%u", chunks[i].mirror_id[0]);
11503                         for (j = 1; j < chunks[i].mirror_count; j++)
11504                                 fprintf(stdout, ", %u", chunks[i].mirror_id[j]);
11505                 }
11506                 fprintf(stdout, "]\t%u\n", chunks[i].mirror_count);
11507         }
11508         fprintf(stdout, "\n");
11509 }
11510
11511 /**
11512  * print_checksums() - Print CRC-32 checksum values.
11513  * @chunk: A chunk and its corresponding valid mirror ids.
11514  * @crc:   CRC-32 checksum values on the chunk for each valid mirror.
11515  *
11516  * This function prints CRC-32 checksum values on @chunk for
11517  * each valid mirror that covers it.
11518  *
11519  * Return: void.
11520  */
11521 static inline
11522 void print_checksums(struct verify_chunk *chunk, unsigned long *crc)
11523 {
11524         int i;
11525
11526         fprintf(stdout,
11527                 "CRC-32 checksum value for chunk "DEXT":\n",
11528                 PEXT(&chunk->chunk));
11529         for (i = 0; i < chunk->mirror_count; i++)
11530                 fprintf(stdout, "Mirror %u:\t%#lx\n",
11531                         chunk->mirror_id[i], crc[i]);
11532         fprintf(stdout, "\n");
11533 }
11534
11535 /**
11536  * filter_mirror_id() - Filter specified mirror ids.
11537  * @chunks:      Array of chunks.
11538  * @chunk_count: Number of chunks in @chunks array.
11539  * @mirror_ids:  Specified mirror ids to be verified.
11540  * @ids_nr:      Number of specified mirror ids.
11541  *
11542  * This function scans valid mirror ids that cover each chunk in @chunks
11543  * and filters specified mirror ids.
11544  *
11545  * Return: void.
11546  */
11547 static inline
11548 void filter_mirror_id(struct verify_chunk *chunks, int chunk_count,
11549                       __u16 *mirror_ids, int ids_nr)
11550 {
11551         int i;
11552         int j;
11553         int k;
11554         __u16 valid_id[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
11555         unsigned int valid_count = 0;
11556
11557         for (i = 0; i < chunk_count; i++) {
11558                 if (chunks[i].mirror_count == 0)
11559                         continue;
11560
11561                 valid_count = 0;
11562                 for (j = 0; j < ids_nr; j++) {
11563                         for (k = 0; k < chunks[i].mirror_count; k++) {
11564                                 if (chunks[i].mirror_id[k] == mirror_ids[j]) {
11565                                         valid_id[valid_count] = mirror_ids[j];
11566                                         valid_count++;
11567                                         break;
11568                                 }
11569                         }
11570                 }
11571
11572                 memcpy(chunks[i].mirror_id, valid_id,
11573                        sizeof(__u16) * valid_count);
11574                 chunks[i].mirror_count = valid_count;
11575         }
11576 }
11577
11578 /**
11579  * lfs_mirror_prepare_chunk() - Find mirror chunks to be verified.
11580  * @layout:      Mirror component list.
11581  * @chunks:      Array of chunks.
11582  * @chunks_size: Array size of @chunks.
11583  *
11584  * This function scans the components in @layout from offset 0 to LUSTRE_EOF
11585  * to find out chunk segments and store them in @chunks array.
11586  *
11587  * The @mirror_id array in each element of @chunks will store the valid
11588  * mirror ids that cover the chunk. If a mirror component covering the
11589  * chunk has LCME_FL_STALE or LCME_FL_OFFLINE flag, then the mirror id
11590  * will not be stored into the @mirror_id array, and the chunk for that
11591  * mirror will not be verified.
11592  *
11593  * The @mirror_count in each element of @chunks will store the number of
11594  * mirror ids in @mirror_id array. If @mirror_count is 0, it indicates the
11595  * chunk is invalid in all of the mirrors. And if @mirror_count is 1, it
11596  * indicates the chunk is valid in only one mirror. In both cases, the
11597  * chunk will not be verified.
11598  *
11599  * Here is an example:
11600  *
11601  *  0      1M     2M     3M     4M           EOF
11602  *  +------+-------------+--------------------+
11603  *  |      |             |      S             |       mirror1
11604  *  +------+------+------+------+-------------+
11605  *  |             |   S  |   S  |             |       mirror2
11606  *  +-------------+------+------+-------------+
11607  *
11608  * prepared @chunks array will contain 5 elements:
11609  * (([0, 1M), [1, 2], 2),
11610  *  ([1M, 2M), [1, 2], 2),
11611  *  ([2M, 3M), [1], 1),
11612  *  ([3M, 4M], [], 0),
11613  *  ([4M, EOF), [2], 1))
11614  *
11615  * Return: the actual array size of @chunks on success
11616  *         or a negative error code on failure.
11617  */
11618 static inline
11619 int lfs_mirror_prepare_chunk(struct llapi_layout *layout,
11620                              struct verify_chunk *chunks,
11621                              size_t chunks_size)
11622 {
11623         uint64_t start;
11624         uint64_t end;
11625         uint32_t mirror_id;
11626         uint32_t flags;
11627         int idx = 0;
11628         int i = 0;
11629         int rc = 0;
11630
11631         memset(chunks, 0, sizeof(*chunks) * chunks_size);
11632
11633         while (1) {
11634                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
11635                 if (rc < 0) {
11636                         fprintf(stderr,
11637                                 "%s: move to the first layout component: %s.\n",
11638                                 progname, strerror(errno));
11639                         goto error;
11640                 }
11641
11642                 i = 0;
11643                 rc = 0;
11644                 chunks[idx].chunk.e_end = LUSTRE_EOF;
11645                 while (rc == 0) {
11646                         rc = llapi_layout_comp_extent_get(layout, &start, &end);
11647                         if (rc < 0) {
11648                                 fprintf(stderr,
11649                                         "%s: llapi_layout_comp_extent_get failed: %s.\n",
11650                                         progname, strerror(errno));
11651                                 goto error;
11652                         }
11653
11654                         if (start > chunks[idx].chunk.e_start ||
11655                             end <= chunks[idx].chunk.e_start)
11656                                 goto next;
11657
11658                         if (end < chunks[idx].chunk.e_end)
11659                                 chunks[idx].chunk.e_end = end;
11660
11661                         rc = llapi_layout_comp_flags_get(layout, &flags);
11662                         if (rc < 0) {
11663                                 fprintf(stderr,
11664                                         "%s: llapi_layout_comp_flags_get failed: %s.\n",
11665                                         progname, strerror(errno));
11666                                 goto error;
11667                         }
11668
11669                         if (flags & LCME_FL_STALE || flags & LCME_FL_OFFLINE)
11670                                 goto next;
11671
11672                         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
11673                         if (rc < 0) {
11674                                 fprintf(stderr,
11675                                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
11676                                         progname, strerror(errno));
11677                                 goto error;
11678                         }
11679
11680                         chunks[idx].mirror_id[i] = mirror_id;
11681                         i++;
11682                         if (i >= ARRAY_SIZE(chunks[idx].mirror_id)) {
11683                                 fprintf(stderr,
11684                                         "%s: mirror_id array is too small.\n",
11685                                         progname);
11686                                 rc = -EINVAL;
11687                                 goto error;
11688                         }
11689
11690 next:
11691                         rc = llapi_layout_comp_use(layout,
11692                                                    LLAPI_LAYOUT_COMP_USE_NEXT);
11693                         if (rc < 0) {
11694                                 fprintf(stderr,
11695                                         "%s: move to the next layout component: %s.\n",
11696                                         progname, strerror(errno));
11697                                 goto error;
11698                         }
11699                 } /* loop through all components */
11700
11701                 chunks[idx].mirror_count = i;
11702
11703                 if (chunks[idx].chunk.e_end == LUSTRE_EOF)
11704                         break;
11705
11706                 idx++;
11707                 if (idx >= chunks_size) {
11708                         fprintf(stderr, "%s: chunks array is too small.\n",
11709                                 progname);
11710                         rc = -EINVAL;
11711                         goto error;
11712                 }
11713
11714                 chunks[idx].chunk.e_start = chunks[idx - 1].chunk.e_end;
11715         }
11716
11717 error:
11718         return rc < 0 ? rc : idx + 1;
11719 }
11720
11721 /**
11722  * lfs_mirror_verify_chunk() - Verify a chunk.
11723  * @fd:        File descriptor of the mirrored file.
11724  * @file_size: Size of the mirrored file.
11725  * @chunk:     A chunk and its corresponding valid mirror ids.
11726  * @verbose:   Verbose mode.
11727  *
11728  * This function verifies a @chunk contains exactly the same data
11729  * ammong the mirrors that cover it.
11730  *
11731  * If @verbose is specified, then the function will print where the
11732  * differences are if the data do not match. Otherwise, it will
11733  * just return an error in that case.
11734  *
11735  * Return: 0 on success or a negative error code on failure.
11736  */
11737 static inline
11738 int lfs_mirror_verify_chunk(int fd, size_t file_size,
11739                             struct verify_chunk *chunk, int verbose)
11740 {
11741         const size_t buflen = 4 * 1024 * 1024; /* 4M */
11742         void *buf;
11743         size_t page_size = sysconf(_SC_PAGESIZE);
11744         ssize_t bytes_read;
11745         ssize_t bytes_done;
11746         size_t count;
11747         off_t pos;
11748         unsigned long crc;
11749         unsigned long crc_array[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
11750         int i;
11751         int rc = 0;
11752
11753         if (file_size == 0)
11754                 return 0;
11755
11756         rc = posix_memalign(&buf, page_size, buflen);
11757         if (rc) /* error code is returned directly */
11758                 return -rc;
11759
11760         if (verbose > 1) {
11761                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
11762                         PEXT(&chunk->chunk));
11763                 for (i = 0; i < chunk->mirror_count; i++)
11764                         fprintf(stdout, " %u", chunk->mirror_id[i]);
11765                 fprintf(stdout, "\n");
11766         }
11767
11768         bytes_done = 0;
11769         count = MIN(chunk->chunk.e_end, file_size) - chunk->chunk.e_start;
11770         pos = chunk->chunk.e_start;
11771         while (bytes_done < count) {
11772                 /* compute initial CRC-32 checksum */
11773                 crc = crc32(0L, Z_NULL, 0);
11774                 memset(crc_array, 0, sizeof(crc_array));
11775
11776                 bytes_read = 0;
11777                 for (i = 0; i < chunk->mirror_count; i++) {
11778                         bytes_read = llapi_mirror_read(fd, chunk->mirror_id[i],
11779                                                        buf, buflen, pos);
11780                         if (bytes_read < 0) {
11781                                 rc = bytes_read;
11782                                 fprintf(stderr,
11783                                         "%s: failed to read data from mirror %u: %s.\n",
11784                                         progname, chunk->mirror_id[i],
11785                                         strerror(-rc));
11786                                 goto error;
11787                         }
11788
11789                         /* compute new CRC-32 checksum */
11790                         crc_array[i] = crc32(crc, buf, bytes_read);
11791                 }
11792
11793                 if (verbose)
11794                         print_checksums(chunk, crc_array);
11795
11796                 /* compare CRC-32 checksum values */
11797                 for (i = 1; i < chunk->mirror_count; i++) {
11798                         if (crc_array[i] != crc_array[0]) {
11799                                 rc = -EINVAL;
11800
11801                                 fprintf(stderr,
11802                                         "%s: chunk "DEXT" has different checksum value on mirror %u and mirror %u.\n",
11803                                         progname, PEXT(&chunk->chunk),
11804                                         chunk->mirror_id[0],
11805                                         chunk->mirror_id[i]);
11806                         }
11807                 }
11808
11809                 pos += bytes_read;
11810                 bytes_done += bytes_read;
11811         }
11812
11813         if (verbose > 1 && rc == 0) {
11814                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
11815                         PEXT(&chunk->chunk));
11816                 for (i = 0; i < chunk->mirror_count; i++)
11817                         fprintf(stdout, " %u", chunk->mirror_id[i]);
11818                 fprintf(stdout, " PASS\n\n");
11819         }
11820
11821 error:
11822         free(buf);
11823         return rc;
11824 }
11825
11826 /**
11827  * lfs_mirror_verify_file() - Verify a mirrored file.
11828  * @fname:      Mirrored file name.
11829  * @mirror_ids: Specified mirror ids to be verified.
11830  * @ids_nr:     Number of specified mirror ids.
11831  * @verbose:    Verbose mode.
11832  *
11833  * This function verifies that each SYNC mirror of a mirrored file
11834  * specified by @fname contains exactly the same data.
11835  *
11836  * If @mirror_ids is specified, then the function will verify the
11837  * mirrors specified by @mirror_ids contain exactly the same data.
11838  *
11839  * If @verbose is specified, then the function will print where the
11840  * differences are if the data do not match. Otherwise, it will
11841  * just return an error in that case.
11842  *
11843  * Return: 0 on success or a negative error code on failure.
11844  */
11845 static inline
11846 int lfs_mirror_verify_file(const char *fname, __u16 *mirror_ids, int ids_nr,
11847                            int verbose)
11848 {
11849         struct verify_chunk chunks_array[1024] = { };
11850         struct llapi_layout *layout = NULL;
11851         struct stat stbuf;
11852         uint32_t flr_state;
11853         int fd;
11854         int chunk_count = 0;
11855         int idx = 0;
11856         int rc = 0;
11857         int rc1 = 0;
11858         int rc2 = 0;
11859
11860         if (stat(fname, &stbuf) < 0) {
11861                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
11862                         progname, fname, strerror(errno));
11863                 rc = -errno;
11864                 goto error;
11865         }
11866
11867         if (!S_ISREG(stbuf.st_mode)) {
11868                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
11869                         progname, fname);
11870                 rc = -EINVAL;
11871                 goto error;
11872         }
11873
11874         if (stbuf.st_size == 0) {
11875                 if (verbose)
11876                         fprintf(stdout, "%s: '%s' file size is 0.\n",
11877                                 progname, fname);
11878                 rc = 0;
11879                 goto error;
11880         }
11881
11882         fd = open(fname, O_DIRECT | O_RDONLY);
11883         if (fd < 0) {
11884                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
11885                         progname, fname, strerror(errno));
11886                 rc = -errno;
11887                 goto error;
11888         }
11889
11890         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
11891         if (rc < 0) {
11892                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
11893                         progname, fname, strerror(errno));
11894                 goto close_fd;
11895         }
11896
11897         layout = llapi_layout_get_by_fd(fd, 0);
11898         if (!layout) {
11899                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
11900                         progname, fname, strerror(errno));
11901                 rc = -errno;
11902                 llapi_lease_release(fd);
11903                 goto close_fd;
11904         }
11905
11906         rc = llapi_layout_flags_get(layout, &flr_state);
11907         if (rc < 0) {
11908                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
11909                         progname, fname, strerror(errno));
11910                 rc = -errno;
11911                 goto free_layout;
11912         }
11913
11914         flr_state &= LCM_FL_FLR_MASK;
11915         switch (flr_state) {
11916         case LCM_FL_NONE:
11917                 rc = -EINVAL;
11918                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
11919                         progname, fname, llapi_layout_flags_string(flr_state));
11920                 goto free_layout;
11921         default:
11922                 break;
11923         }
11924
11925         /* find out mirror chunks to be verified */
11926         chunk_count = lfs_mirror_prepare_chunk(layout, chunks_array,
11927                                                ARRAY_SIZE(chunks_array));
11928         if (chunk_count < 0) {
11929                 rc = chunk_count;
11930                 goto free_layout;
11931         }
11932
11933         if (ids_nr > 0)
11934                 /* filter specified mirror ids */
11935                 filter_mirror_id(chunks_array, chunk_count, mirror_ids, ids_nr);
11936
11937         if (verbose > 2)
11938                 print_chunks(fname, chunks_array, chunk_count);
11939
11940         for (idx = 0; idx < chunk_count; idx++) {
11941                 if (chunks_array[idx].chunk.e_start >= stbuf.st_size) {
11942                         if (verbose)
11943                                 fprintf(stdout,
11944                                         "%s: '%s' chunk "DEXT" exceeds file size %#llx: skipped\n",
11945                                         progname, fname,
11946                                         PEXT(&chunks_array[idx].chunk),
11947                                         (unsigned long long)stbuf.st_size);
11948                         break;
11949                 }
11950
11951                 if (chunks_array[idx].mirror_count == 0) {
11952                         fprintf(stderr,
11953                                 "%s: '%s' chunk "DEXT" is invalid in all of the mirrors: ",
11954                                 progname, fname,
11955                                 PEXT(&chunks_array[idx].chunk));
11956                         if (verbose) {
11957                                 fprintf(stderr, "skipped\n");
11958                                 continue;
11959                         }
11960                         rc = -EINVAL;
11961                         fprintf(stderr, "failed\n");
11962                         goto free_layout;
11963                 }
11964
11965                 if (chunks_array[idx].mirror_count == 1) {
11966                         if (verbose)
11967                                 fprintf(stdout,
11968                                         "%s: '%s' chunk "DEXT" is only valid in mirror %u: skipped\n",
11969                                         progname, fname,
11970                                         PEXT(&chunks_array[idx].chunk),
11971                                         chunks_array[idx].mirror_id[0]);
11972                         continue;
11973                 }
11974
11975                 rc = llapi_lease_check(fd);
11976                 if (rc != LL_LEASE_RDLCK) {
11977                         fprintf(stderr, "%s: '%s' lost lease lock.\n",
11978                                 progname, fname);
11979                         goto free_layout;
11980                 }
11981
11982                 /* verify one chunk */
11983                 rc1 = lfs_mirror_verify_chunk(fd, stbuf.st_size,
11984                                               &chunks_array[idx], verbose);
11985                 if (rc1 < 0) {
11986                         rc2 = rc1;
11987                         if (!verbose) {
11988                                 rc = rc1;
11989                                 goto free_layout;
11990                         }
11991                 }
11992         }
11993
11994         if (rc2 < 0)
11995                 rc = rc2;
11996
11997 free_layout:
11998         llapi_layout_free(layout);
11999         llapi_lease_release(fd);
12000 close_fd:
12001         close(fd);
12002 error:
12003         return rc;
12004 }
12005
12006 /**
12007  * lfs_mirror_verify() - Parse and execute lfs mirror verify command.
12008  * @argc: The count of lfs mirror verify command line arguments.
12009  * @argv: Array of strings for lfs mirror verify command line arguments.
12010  *
12011  * This function parses lfs mirror verify command and verifies the
12012  * specified mirrored file(s).
12013  *
12014  * Return: 0 on success or a negative error code on failure.
12015  */
12016 static inline int lfs_mirror_verify(int argc, char **argv)
12017 {
12018         __u16 mirror_ids[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
12019         int ids_nr = 0;
12020         int c;
12021         int verbose = 0;
12022         int rc = 0;
12023         int rc1 = 0;
12024         char cmd[PATH_MAX];
12025
12026         struct option long_opts[] = {
12027         { .val = 'h',   .name = "help",         .has_arg = no_argument },
12028         { .val = 'o',   .name = "only",         .has_arg = required_argument },
12029         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
12030         { .name = NULL } };
12031
12032         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
12033         progname = cmd;
12034         while ((c = getopt_long(argc, argv, "ho:v", long_opts, NULL)) >= 0) {
12035                 switch (c) {
12036                 case 'o':
12037                         rc = parse_mirror_ids(mirror_ids,
12038                                               ARRAY_SIZE(mirror_ids),
12039                                               optarg);
12040                         if (rc < 0) {
12041                                 fprintf(stderr,
12042                                         "%s: bad mirror ids '%s'.\n",
12043                                         progname, optarg);
12044                                 goto error;
12045                         }
12046                         ids_nr = rc;
12047                         if (ids_nr < 2) {
12048                                 fprintf(stderr,
12049                                         "%s: at least 2 mirror ids needed with '--only' option.\n",
12050                                         progname);
12051                                 rc = CMD_HELP;
12052                                 goto error;
12053                         }
12054                         break;
12055                 case 'v':
12056                         verbose++;
12057                         break;
12058                 default:
12059                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12060                                 progname, argv[optind - 1]);
12061                         /* fallthrough */
12062                 case 'h':
12063                         rc = CMD_HELP;
12064                         goto error;
12065                 }
12066         }
12067
12068         if (argc == optind) {
12069                 fprintf(stderr, "%s: no file name given.\n", progname);
12070                 rc = CMD_HELP;
12071                 goto error;
12072         }
12073
12074         if (ids_nr > 0 && argc > optind + 1) {
12075                 fprintf(stderr,
12076                         "%s: '--only' cannot be used upon multiple files.\n",
12077                         progname);
12078                 rc = CMD_HELP;
12079                 goto error;
12080         }
12081
12082         if (ids_nr > 0) {
12083                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
12084                 if (rc < 0)
12085                         goto error;
12086         }
12087
12088         rc = 0;
12089         for (; optind < argc; optind++) {
12090                 rc1 = lfs_mirror_verify_file(argv[optind], mirror_ids, ids_nr,
12091                                              verbose);
12092                 if (rc1 < 0)
12093                         rc = rc1;
12094         }
12095 error:
12096         return rc;
12097 }
12098
12099 /**
12100  * lfs_mirror() - Parse and execute lfs mirror commands.
12101  * @argc: The count of lfs mirror command line arguments.
12102  * @argv: Array of strings for lfs mirror command line arguments.
12103  *
12104  * This function parses lfs mirror commands and performs the
12105  * corresponding functions specified in mirror_cmdlist[].
12106  *
12107  * Return: 0 on success or an error code on failure.
12108  */
12109 static int lfs_mirror(int argc, char **argv)
12110 {
12111         char cmd[PATH_MAX];
12112         int rc = 0;
12113
12114         setlinebuf(stdout);
12115
12116         Parser_init("lfs-mirror > ", mirror_cmdlist);
12117
12118         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
12119         progname = cmd;
12120         program_invocation_short_name = cmd;
12121         if (argc > 1)
12122                 rc = Parser_execarg(argc - 1, argv + 1, mirror_cmdlist);
12123         else
12124                 rc = Parser_commands();
12125
12126         return rc < 0 ? -rc : rc;
12127 }
12128
12129 static void lustre_som_swab(struct lustre_som_attrs *attrs)
12130 {
12131 #if __BYTE_ORDER == __BIG_ENDIAN
12132         __swab16s(&attrs->lsa_valid);
12133         __swab64s(&attrs->lsa_size);
12134         __swab64s(&attrs->lsa_blocks);
12135 #endif
12136 }
12137
12138 enum lfs_som_type {
12139         LFS_SOM_SIZE = 0x1,
12140         LFS_SOM_BLOCKS = 0x2,
12141         LFS_SOM_FLAGS = 0x4,
12142         LFS_SOM_ATTR_ALL = LFS_SOM_SIZE | LFS_SOM_BLOCKS |
12143                            LFS_SOM_FLAGS,
12144 };
12145
12146 static int lfs_getsom(int argc, char **argv)
12147 {
12148         const char *path;
12149         struct lustre_som_attrs *attrs;
12150         char buf[sizeof(*attrs) + 64];
12151         enum lfs_som_type type = LFS_SOM_ATTR_ALL;
12152         int rc = 0, c;
12153
12154         while ((c = getopt(argc, argv, "bfhs")) != -1) {
12155                 switch (c) {
12156                 case 'b':
12157                         type = LFS_SOM_BLOCKS;
12158                         break;
12159                 case 'f':
12160                         type = LFS_SOM_FLAGS;
12161                         break;
12162                 case 's':
12163                         type = LFS_SOM_SIZE;
12164                         break;
12165                 default:
12166                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12167                                 progname, argv[optind - 1]);
12168                         /* fallthrough */
12169                 case 'h':
12170                         return CMD_HELP;
12171                 }
12172         }
12173
12174         argc -= optind;
12175         argv += optind;
12176
12177         if (argc != 1) {
12178                 fprintf(stderr, "%s: %s\n",
12179                         progname, argc == 0 ? "miss file target" :
12180                         "input more than 2 files");
12181                 return CMD_HELP;
12182         }
12183
12184         path = argv[0];
12185         attrs = (void *)buf;
12186         rc = lgetxattr(path, "trusted.som", attrs, sizeof(buf));
12187         if (rc < 0) {
12188                 rc = -errno;
12189                 fprintf(stderr, "%s failed to get som xattr: %s (%d)\n",
12190                         argv[0], strerror(errno), errno);
12191                 return rc;
12192         }
12193
12194         lustre_som_swab(attrs);
12195
12196         switch (type) {
12197         case LFS_SOM_ATTR_ALL:
12198                 printf("file: %s size: %llu blocks: %llu flags: %x\n",
12199                        path, (unsigned long long)attrs->lsa_size,
12200                        (unsigned long long)attrs->lsa_blocks,
12201                        attrs->lsa_valid);
12202                 break;
12203         case LFS_SOM_SIZE:
12204                 printf("%llu\n", (unsigned long long)attrs->lsa_size);
12205                 break;
12206         case LFS_SOM_BLOCKS:
12207                 printf("%llu\n", (unsigned long long)attrs->lsa_blocks);
12208                 break;
12209         case LFS_SOM_FLAGS:
12210                 printf("%x\n", attrs->lsa_valid);
12211                 break;
12212         default:
12213                 fprintf(stderr, "%s: unknown option\n", progname);
12214                 return CMD_HELP;
12215         }
12216
12217         return 0;
12218 }
12219
12220 /**
12221  * lfs_mirror_list_commands() - List lfs mirror commands.
12222  * @argc: The count of command line arguments.
12223  * @argv: Array of strings for command line arguments.
12224  *
12225  * This function lists lfs mirror commands defined in mirror_cmdlist[].
12226  *
12227  * Return: 0 on success.
12228  */
12229 static int lfs_mirror_list_commands(int argc, char **argv)
12230 {
12231         char buffer[81] = "";
12232
12233         Parser_list_commands(mirror_cmdlist, buffer, sizeof(buffer),
12234                              NULL, 0, 4);
12235
12236         return 0;
12237 }
12238
12239 static int lfs_pcc_attach(int argc, char **argv)
12240 {
12241         struct option long_opts[] = {
12242         { .val = 'h',   .name = "help", .has_arg = no_argument },
12243         { .val = 'i',   .name = "id",   .has_arg = required_argument },
12244         { .name = NULL } };
12245         int c;
12246         int rc = 0;
12247         __u32 archive_id = 0;
12248         const char *path;
12249         char *end;
12250         char fullpath[PATH_MAX];
12251         enum lu_pcc_type type = LU_PCC_READWRITE;
12252
12253         optind = 0;
12254         while ((c = getopt_long(argc, argv, "hi:",
12255                                 long_opts, NULL)) != -1) {
12256                 switch (c) {
12257                 case 'i':
12258                         errno = 0;
12259                         archive_id = strtoul(optarg, &end, 0);
12260                         if (errno != 0 || *end != '\0' ||
12261                             archive_id == 0 || archive_id > UINT32_MAX) {
12262                                 fprintf(stderr,
12263                                         "error: %s: bad archive ID '%s'\n",
12264                                         progname, optarg);
12265                                 return CMD_HELP;
12266                         }
12267                         break;
12268                 default:
12269                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12270                                 progname, argv[optind - 1]);
12271                         /* fallthrough */
12272                 case 'h':
12273                         return CMD_HELP;
12274                 }
12275         }
12276
12277         if (archive_id == 0) {
12278                 fprintf(stderr, "%s: must specify attach ID\n", argv[0]);
12279                 return CMD_HELP;
12280         }
12281
12282         if (argc <= optind) {
12283                 fprintf(stderr, "%s: must specify one or more file names\n",
12284                         argv[0]);
12285                 return CMD_HELP;
12286         }
12287
12288         while (optind < argc) {
12289                 int rc2;
12290
12291                 path = argv[optind++];
12292                 if (!realpath(path, fullpath)) {
12293                         fprintf(stderr, "%s: could not find path '%s': %s\n",
12294                                 argv[0], path, strerror(errno));
12295                         if (rc == 0)
12296                                 rc = -EINVAL;
12297                         continue;
12298                 }
12299
12300                 rc2 = llapi_pcc_attach(fullpath, archive_id, type);
12301                 if (rc2 < 0) {
12302                         fprintf(stderr,
12303                                 "%s: cannot attach '%s' to PCC with archive ID '%u': %s\n",
12304                                 argv[0], path, archive_id, strerror(-rc2));
12305                         if (rc == 0)
12306                                 rc = rc2;
12307                 }
12308         }
12309         return rc;
12310 }
12311
12312 static int lfs_pcc_attach_fid(int argc, char **argv)
12313 {
12314         struct option long_opts[] = {
12315         { .val = 'h',   .name = "help", .has_arg = no_argument },
12316         { .val = 'i',   .name = "id",   .has_arg = required_argument },
12317         { .val = 'm',   .name = "mnt",  .has_arg = required_argument },
12318         { .name = NULL } };
12319         int c;
12320         int rc = 0;
12321         __u32 archive_id = 0;
12322         char *end;
12323         const char *mntpath = NULL;
12324         const char *fidstr;
12325         enum lu_pcc_type type = LU_PCC_READWRITE;
12326
12327         optind = 0;
12328         while ((c = getopt_long(argc, argv, "hi:m:",
12329                                 long_opts, NULL)) != -1) {
12330                 switch (c) {
12331                 case 'i':
12332                         errno = 0;
12333                         archive_id = strtoul(optarg, &end, 0);
12334                         if (errno != 0 || *end != '\0' ||
12335                             archive_id > UINT32_MAX) {
12336                                 fprintf(stderr,
12337                                         "error: %s: bad archive ID '%s'\n",
12338                                         argv[0], optarg);
12339                                 return CMD_HELP;
12340                         }
12341                         break;
12342                 case 'm':
12343                         mntpath = optarg;
12344                         break;
12345                 default:
12346                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12347                                 progname, argv[optind - 1]);
12348                         /* fallthrough */
12349                 case 'h':
12350                         return CMD_HELP;
12351                 }
12352         }
12353
12354         if (archive_id == 0) {
12355                 fprintf(stderr, "%s: must specify an archive ID\n", argv[0]);
12356                 return CMD_HELP;
12357         }
12358
12359         if (!mntpath) {
12360                 fprintf(stderr, "%s: must specify Lustre mount point\n",
12361                         argv[0]);
12362                 return CMD_HELP;
12363         }
12364
12365         if (argc <= optind) {
12366                 fprintf(stderr, "%s: must specify one or more fids\n", argv[0]);
12367                 return CMD_HELP;
12368         }
12369
12370         while (optind < argc) {
12371                 int rc2;
12372
12373                 fidstr = argv[optind++];
12374
12375                 rc2 = llapi_pcc_attach_fid_str(mntpath, fidstr,
12376                                                archive_id, type);
12377                 if (rc2 < 0) {
12378                         fprintf(stderr,
12379                                 "%s: cannot attach '%s' on '%s' to PCC with archive ID '%u': %s\n",
12380                                 argv[0], fidstr, mntpath, archive_id,
12381                                 strerror(rc2));
12382                 }
12383                 if (rc == 0 && rc2 < 0)
12384                         rc = rc2;
12385         }
12386         return rc;
12387 }
12388
12389 static int lfs_pcc_detach(int argc, char **argv)
12390 {
12391         struct option long_opts[] = {
12392         { .val = 'h',   .name = "help", .has_arg = no_argument },
12393         { .val = 'k',   .name = "keep", .has_arg = no_argument },
12394         { .name = NULL } };
12395         int c;
12396         int rc = 0;
12397         const char *path;
12398         char fullpath[PATH_MAX];
12399         __u32 detach_opt = PCC_DETACH_OPT_UNCACHE;
12400
12401         optind = 0;
12402         while ((c = getopt_long(argc, argv, "hk",
12403                                 long_opts, NULL)) != -1) {
12404                 switch (c) {
12405                 case 'k':
12406                         detach_opt = PCC_DETACH_OPT_NONE;
12407                         break;
12408                 default:
12409                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12410                                 progname, argv[optind - 1]);
12411                         /* fallthrough */
12412                 case 'h':
12413                         return CMD_HELP;
12414                 }
12415         }
12416
12417         while (optind < argc) {
12418                 int rc2;
12419
12420                 path = argv[optind++];
12421                 if (!realpath(path, fullpath)) {
12422                         fprintf(stderr, "%s: could not find path '%s': %s\n",
12423                                 argv[0], path, strerror(errno));
12424                         if (rc == 0)
12425                                 rc = -EINVAL;
12426                         continue;
12427                 }
12428
12429                 rc2 = llapi_pcc_detach_file(fullpath, detach_opt);
12430                 if (rc2 < 0) {
12431                         rc2 = -errno;
12432                         fprintf(stderr,
12433                                 "%s: cannot detach '%s' from PCC: %s\n",
12434                                 argv[0], path, strerror(errno));
12435                         if (rc == 0)
12436                                 rc = rc2;
12437                 }
12438         }
12439         return rc;
12440 }
12441
12442 static int lfs_pcc_detach_fid(int argc, char **argv)
12443 {
12444         struct option long_opts[] = {
12445         { .val = 'h',   .name = "help", .has_arg = no_argument },
12446         { .val = 'k',   .name = "keep", .has_arg = no_argument },
12447         { .name = NULL } };
12448         int c;
12449         int rc = 0;
12450         const char *fid;
12451         const char *mntpath;
12452         __u32 detach_opt = PCC_DETACH_OPT_UNCACHE;
12453
12454         optind = 0;
12455         while ((c = getopt_long(argc, argv, "hk",
12456                                 long_opts, NULL)) != -1) {
12457                 switch (c) {
12458                 case 'k':
12459                         detach_opt = PCC_DETACH_OPT_NONE;
12460                         break;
12461                 default:
12462                         fprintf(stderr, "%s: unrecognized option '%s'\n",
12463                                 progname, argv[optind - 1]);
12464                         /* fallthrough */
12465                 case 'h':
12466                         return CMD_HELP;
12467                 }
12468         }
12469
12470         mntpath = argv[optind++];
12471
12472         while (optind < argc) {
12473                 int rc2;
12474
12475                 fid = argv[optind++];
12476
12477                 rc2 = llapi_pcc_detach_fid_str(mntpath, fid, detach_opt);
12478                 if (rc2 < 0) {
12479                         fprintf(stderr,
12480                                 "%s: cannot detach '%s' on '%s' from PCC: %s\n",
12481                                 argv[0], fid, mntpath, strerror(-rc2));
12482                         if (rc == 0)
12483                                 rc = rc2;
12484                 }
12485         }
12486         return rc;
12487 }
12488
12489 static int lfs_pcc_state(int argc, char **argv)
12490 {
12491         int rc = 0;
12492         const char *path;
12493         char fullpath[PATH_MAX];
12494         struct lu_pcc_state state;
12495
12496         optind = 1;
12497
12498         if (argc <= 1) {
12499                 fprintf(stderr, "%s: must specify one or more file names\n",
12500                         progname);
12501                 return CMD_HELP;
12502         }
12503
12504         while (optind < argc) {
12505                 int rc2;
12506
12507                 path = argv[optind++];
12508                 if (!realpath(path, fullpath)) {
12509                         fprintf(stderr, "%s: could not find path '%s': %s\n",
12510                                 argv[0], path, strerror(errno));
12511                         if (rc == 0)
12512                                 rc = -EINVAL;
12513                         continue;
12514                 }
12515
12516                 rc2 = llapi_pcc_state_get(fullpath, &state);
12517                 if (rc2 < 0) {
12518                         if (rc == 0)
12519                                 rc = rc2;
12520                         fprintf(stderr,
12521                                 "%s: cannot get PCC state of '%s': %s\n",
12522                                 argv[0], path, strerror(-rc2));
12523                         continue;
12524                 }
12525
12526                 printf("file: %s", path);
12527                 printf(", type: %s", pcc_type2string(state.pccs_type));
12528                 if (state.pccs_type == LU_PCC_NONE &&
12529                     state.pccs_open_count == 0) {
12530                         printf("\n");
12531                         continue;
12532                 }
12533
12534                 printf(", PCC file: %s", state.pccs_path);
12535                 printf(", user number: %u", state.pccs_open_count);
12536                 printf(", flags: %x", state.pccs_flags);
12537                 printf("\n");
12538         }
12539         return rc;
12540 }
12541
12542 /**
12543  * lfs_pcc_list_commands() - List lfs pcc commands.
12544  * @argc: The count of command line arguments.
12545  * @argv: Array of strings for command line arguments.
12546  *
12547  * This function lists lfs pcc commands defined in pcc_cmdlist[].
12548  *
12549  * Return: 0 on success.
12550  */
12551 static int lfs_pcc_list_commands(int argc, char **argv)
12552 {
12553         char buffer[81] = "";
12554
12555         Parser_list_commands(pcc_cmdlist, buffer, sizeof(buffer),
12556                              NULL, 0, 4);
12557
12558         return 0;
12559 }
12560
12561 /**
12562  * lfs_pcc() - Parse and execute lfs pcc commands.
12563  * @argc: The count of lfs pcc command line arguments.
12564  * @argv: Array of strings for lfs pcc command line arguments.
12565  *
12566  * This function parses lfs pcc commands and performs the
12567  * corresponding functions specified in pcc_cmdlist[].
12568  *
12569  * Return: 0 on success or an error code on failure.
12570  */
12571 static int lfs_pcc(int argc, char **argv)
12572 {
12573         char cmd[PATH_MAX];
12574         int rc = 0;
12575
12576         setlinebuf(stdout);
12577
12578         Parser_init("lfs-pcc > ", pcc_cmdlist);
12579
12580         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
12581         progname = cmd;
12582         program_invocation_short_name = cmd;
12583         if (argc > 1)
12584                 rc = Parser_execarg(argc - 1, argv + 1, pcc_cmdlist);
12585         else
12586                 rc = Parser_commands();
12587
12588         return rc < 0 ? -rc : rc;
12589 }
12590
12591 static int lfs_list_commands(int argc, char **argv)
12592 {
12593         char buffer[81] = ""; /* 80 printable chars + terminating NUL */
12594
12595         Parser_list_commands(cmdlist, buffer, sizeof(buffer), NULL, 0, 4);
12596
12597         return 0;
12598 }
12599
12600 int main(int argc, char **argv)
12601 {
12602         int rc;
12603
12604         /* Ensure that liblustreapi constructor has run */
12605         if (!llapi_liblustreapi_initialized())
12606                 fprintf(stderr, "liblustreapi was not properly initialized\n");
12607
12608         setlinebuf(stdout);
12609         opterr = 0;
12610
12611         Parser_init("lfs > ", cmdlist);
12612
12613         progname = program_invocation_short_name; /* Used in error messages */
12614         if (argc > 1) {
12615                 llapi_set_command_name(argv[1]);
12616                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
12617                 llapi_clear_command_name();
12618         } else {
12619                 rc = Parser_commands();
12620         }
12621
12622         return rc < 0 ? -rc : rc;
12623 }
12624
12625 #ifdef _LUSTRE_IDL_H_
12626 /* Everything we need here should be included by lustreapi.h. */
12627 # error "lfs should not depend on lustre_idl.h"
12628 #endif /* _LUSTRE_IDL_H_ */