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