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