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