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