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