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