Whamcloud - gitweb
LU-13845 utils: Quota id 0xFFFFFFFF is invalid
[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.\n",
4045                                         progname, template ?: fname);
4046                                 goto error;
4047                         }
4048                 }
4049
4050                 if (migrate_mdt_mode) {
4051                         result = llapi_migrate_mdt(fname, &migrate_mdt_param);
4052                 } else if (migrate_mode) {
4053                         result = lfs_migrate(fname, migration_flags, param,
4054                                              layout);
4055                 } else if (comp_set != 0) {
4056                         result = lfs_component_set(fname, comp_id,
4057                                                    lsa.lsa_comp_flags,
4058                                                    lsa.lsa_comp_neg_flags);
4059                 } else if (comp_del != 0) {
4060                         result = lfs_component_del(fname, comp_id,
4061                                                    lsa.lsa_comp_flags,
4062                                                    lsa.lsa_comp_neg_flags);
4063                 } else if (comp_add != 0) {
4064                         result = lfs_component_add(fname, layout);
4065                 } else if (opc == SO_MIRROR_CREATE) {
4066                         result = mirror_create(fname, mirror_list);
4067                 } else if (opc == SO_MIRROR_EXTEND) {
4068                         result = mirror_extend(fname, mirror_list,
4069                                                mirror_flags);
4070                 } else if (opc == SO_MIRROR_SPLIT || opc == SO_MIRROR_DELETE) {
4071                         if (!mirror_id && !comp_id && !lsa.lsa_pool_name) {
4072                                 fprintf(stderr,
4073                                         "%s: no mirror specified to delete from '%s'\n",
4074                                         progname, fname);
4075                                 goto usage_error;
4076                         }
4077                         if (lsa.lsa_pool_name)
4078                                 mirror_flags |= MF_COMP_POOL;
4079                         else if (mirror_id != 0)
4080                                 comp_id = mirror_id;
4081                         else
4082                                 mirror_flags |= MF_COMP_ID;
4083                         result = mirror_split(fname, comp_id, lsa.lsa_pool_name,
4084                                               mirror_flags,
4085                                               has_m_file ? mirror_list->m_file :
4086                                               NULL);
4087                 } else if (layout) {
4088                         result = lfs_component_create(fname, O_CREAT | O_WRONLY,
4089                                                       mode, layout);
4090                         if (result >= 0) {
4091                                 close(result);
4092                                 result = 0;
4093                         }
4094                 } else if (foreign_mode) {
4095                         result = llapi_file_create_foreign(fname, mode, type,
4096                                                            flags, xattr);
4097                         if (result >= 0) {
4098                                 close(result);
4099                                 result = 0;
4100                         }
4101                 } else {
4102                         result = llapi_file_open_param(fname,
4103                                                        O_CREAT | O_WRONLY,
4104                                                        mode, param);
4105                         if (result >= 0) {
4106                                 close(result);
4107                                 result = 0;
4108                         }
4109                 }
4110                 if (result) {
4111                         /* Save the first error encountered. */
4112                         if (result2 == 0)
4113                                 result2 = result;
4114                         continue;
4115                 }
4116         }
4117
4118         if (mode_opt)
4119                 umask(previous_umask);
4120
4121         free(param);
4122         free(migrate_mdt_param.fp_lmv_md);
4123         llapi_layout_free(layout);
4124         lfs_mirror_list_free(mirror_list);
4125         return result2;
4126 usage_error:
4127         result = CMD_HELP;
4128 error:
4129         llapi_layout_free(layout);
4130         lfs_mirror_list_free(mirror_list);
4131         return result;
4132 }
4133
4134 static int lfs_poollist(int argc, char **argv)
4135 {
4136         if (argc != 2)
4137                 return CMD_HELP;
4138
4139         return llapi_poollist(argv[1]);
4140 }
4141
4142 #define FP_DEFAULT_TIME_MARGIN (24 * 60 * 60)
4143 static time_t set_time(struct find_param *param, time_t *time, time_t *set,
4144                        char *str)
4145 {
4146         long long t = 0;
4147         int sign = 0;
4148         char *endptr = "AD";
4149         char *timebuf;
4150
4151         if (str[0] == '+')
4152                 sign = 1;
4153         else if (str[0] == '-')
4154                 sign = -1;
4155
4156         if (sign)
4157                 str++;
4158
4159         for (timebuf = str; *endptr && *(endptr + 1); timebuf = endptr + 1) {
4160                 long long val = strtoll(timebuf, &endptr, 0);
4161                 int unit = 1;
4162
4163                 switch (*endptr) {
4164                 case  'y':
4165                         unit *= 52; /* 52 weeks + 1 day below */
4166                 case  'w':      /* fallthrough */
4167                         unit *= 7;
4168                         if (param->fp_time_margin == FP_DEFAULT_TIME_MARGIN)
4169                                 param->fp_time_margin *= (1 + unit / 52);
4170                         unit += (*endptr == 'y'); /* +1 day for 365 days/year */
4171                 case '\0': /* days are default unit if none used */
4172                 case  'd':      /* fallthrough */
4173                         unit *= 24;
4174                 case  'h':      /* fallthrough */
4175                         unit *= 60;
4176                 case  'm':      /* fallthrough */
4177                         unit *= 60;
4178                 case  's':      /* fallthrough */
4179                         break;
4180                         /* don't need to multiply by 1 for seconds */
4181                 default:
4182                         fprintf(stderr,
4183                                 "%s find: bad time string '%s': %s\n",
4184                                 progname, timebuf, strerror(EINVAL));
4185                         return LONG_MAX;
4186                 }
4187
4188                 if (param->fp_time_margin == 0 ||
4189                     (*endptr && unit < param->fp_time_margin))
4190                         param->fp_time_margin = unit;
4191
4192                 t += val * unit;
4193         }
4194         if (*time < t) {
4195                 if (sign != 0)
4196                         str--;
4197                 fprintf(stderr, "%s find: bad time '%s': too large\n",
4198                         progname, str);
4199                 return LONG_MAX;
4200         }
4201
4202         *set = *time - t;
4203
4204         return sign;
4205 }
4206
4207 static int str2quotaid(__u32 *id, const char *arg)
4208 {
4209         unsigned long int projid_tmp = 0;
4210         char *endptr = NULL;
4211
4212         projid_tmp = strtoul(arg, &endptr, 10);
4213         if (*endptr != '\0')
4214                 return -EINVAL;
4215         if (projid_tmp >= UINT32_MAX)
4216                 return -ERANGE;
4217
4218         *id = projid_tmp;
4219         return 0;
4220 }
4221
4222 static int name2uid(unsigned int *id, const char *name)
4223 {
4224         struct passwd *passwd;
4225
4226         passwd = getpwnam(name);
4227         if (!passwd)
4228                 return -ENOENT;
4229         *id = passwd->pw_uid;
4230
4231         return 0;
4232 }
4233
4234 static int name2gid(unsigned int *id, const char *name)
4235 {
4236         struct group *group;
4237
4238         group = getgrnam(name);
4239         if (!group)
4240                 return -ENOENT;
4241         *id = group->gr_gid;
4242
4243         return 0;
4244 }
4245
4246 static inline int name2projid(unsigned int *id, const char *name)
4247 {
4248         return -ENOTSUP;
4249 }
4250
4251 static int uid2name(char **name, unsigned int id)
4252 {
4253         struct passwd *passwd;
4254
4255         passwd = getpwuid(id);
4256         if (!passwd)
4257                 return -ENOENT;
4258         *name = passwd->pw_name;
4259
4260         return 0;
4261 }
4262
4263 static inline int gid2name(char **name, unsigned int id)
4264 {
4265         struct group *group;
4266
4267         group = getgrgid(id);
4268         if (!group)
4269                 return -ENOENT;
4270         *name = group->gr_name;
4271
4272         return 0;
4273 }
4274
4275 static int name2layout(__u32 *layout, char *name)
4276 {
4277         char *ptr, *layout_name;
4278
4279         *layout = 0;
4280         for (ptr = name; ; ptr = NULL) {
4281                 layout_name = strtok(ptr, ",");
4282                 if (!layout_name)
4283                         break;
4284                 if (strcmp(layout_name, "released") == 0)
4285                         *layout |= LOV_PATTERN_F_RELEASED;
4286                 else if (strcmp(layout_name, "raid0") == 0)
4287                         *layout |= LOV_PATTERN_RAID0;
4288                 else if (strcmp(layout_name, "mdt") == 0)
4289                         *layout |= LOV_PATTERN_MDT;
4290                 else if (strcmp(layout_name, "overstriping") == 0)
4291                         *layout |= LOV_PATTERN_OVERSTRIPING;
4292                 else
4293                         return -1;
4294         }
4295         return 0;
4296 }
4297
4298 static int lfs_find(int argc, char **argv)
4299 {
4300         int c, rc;
4301         int ret = 0;
4302         time_t t;
4303         struct find_param param = {
4304                 .fp_max_depth = -1,
4305                 .fp_quiet = 1,
4306                 .fp_time_margin = FP_DEFAULT_TIME_MARGIN,
4307         };
4308         struct option long_opts[] = {
4309         { .val = 'A',   .name = "atime",        .has_arg = required_argument },
4310         { .val = 'b',   .name = "blocks",       .has_arg = required_argument },
4311         { .val = 'B',   .name = "btime",        .has_arg = required_argument },
4312         { .val = 'B',   .name = "Btime",        .has_arg = required_argument },
4313         { .val = LFS_COMP_COUNT_OPT,
4314                         .name = "comp-count",   .has_arg = required_argument },
4315         { .val = LFS_COMP_COUNT_OPT,
4316                         .name = "component-count",
4317                                                 .has_arg = required_argument },
4318         { .val = LFS_COMP_FLAGS_OPT,
4319                         .name = "comp-flags",   .has_arg = required_argument },
4320         { .val = LFS_COMP_FLAGS_OPT,
4321                         .name = "component-flags",
4322                                                 .has_arg = required_argument },
4323         { .val = LFS_COMP_START_OPT,
4324                         .name = "comp-start",   .has_arg = required_argument },
4325         { .val = LFS_COMP_START_OPT,
4326                         .name = "component-start",
4327                                                 .has_arg = required_argument },
4328         { .val = LFS_MIRROR_STATE_OPT,
4329                         .name = "mirror-state", .has_arg = required_argument },
4330         { .val = LFS_LAYOUT_FOREIGN_OPT,
4331                         .name = "foreign",      .has_arg = optional_argument},
4332         { .val = LFS_NEWERXY_OPT,
4333                         .name = "newer",        .has_arg = required_argument},
4334         { .val = LFS_NEWERXY_OPT,
4335                         .name = "neweraa",      .has_arg = required_argument},
4336         { .val = LFS_NEWERXY_OPT,
4337                         .name = "neweram",      .has_arg = required_argument},
4338         { .val = LFS_NEWERXY_OPT,
4339                         .name = "newerac",      .has_arg = required_argument},
4340         { .val = LFS_NEWERXY_OPT,
4341                         .name = "newerab",      .has_arg = required_argument},
4342         { .val = LFS_NEWERXY_OPT,
4343                         .name = "newerma",      .has_arg = required_argument},
4344         { .val = LFS_NEWERXY_OPT,
4345                         .name = "newermm",      .has_arg = required_argument},
4346         { .val = LFS_NEWERXY_OPT,
4347                         .name = "newermc",      .has_arg = required_argument},
4348         { .val = LFS_NEWERXY_OPT,
4349                         .name = "newermb",      .has_arg = required_argument},
4350         { .val = LFS_NEWERXY_OPT,
4351                         .name = "newerca",      .has_arg = required_argument},
4352         { .val = LFS_NEWERXY_OPT,
4353                         .name = "newercm",      .has_arg = required_argument},
4354         { .val = LFS_NEWERXY_OPT,
4355                         .name = "newercc",      .has_arg = required_argument},
4356         { .val = LFS_NEWERXY_OPT,
4357                         .name = "newercb",      .has_arg = required_argument},
4358         { .val = LFS_NEWERXY_OPT,
4359                         .name = "newerba",      .has_arg = required_argument},
4360         { .val = LFS_NEWERXY_OPT,
4361                         .name = "newerbm",      .has_arg = required_argument},
4362         { .val = LFS_NEWERXY_OPT,
4363                         .name = "newerbc",      .has_arg = required_argument},
4364         { .val = LFS_NEWERXY_OPT,
4365                         .name = "newerbb",      .has_arg = required_argument},
4366         { .val = LFS_NEWERXY_OPT,
4367                         .name = "newerBa",      .has_arg = required_argument},
4368         { .val = LFS_NEWERXY_OPT,
4369                         .name = "newerBm",      .has_arg = required_argument},
4370         { .val = LFS_NEWERXY_OPT,
4371                         .name = "newerBc",      .has_arg = required_argument},
4372         { .val = LFS_NEWERXY_OPT,
4373                         .name = "newerBB",      .has_arg = required_argument},
4374         { .val = LFS_NEWERXY_OPT,
4375                         .name = "newerat",      .has_arg = required_argument},
4376         { .val = LFS_NEWERXY_OPT,
4377                         .name = "newermt",      .has_arg = required_argument},
4378         { .val = LFS_NEWERXY_OPT,
4379                         .name = "newerct",      .has_arg = required_argument},
4380         { .val = LFS_NEWERXY_OPT,
4381                         .name = "newerbt",      .has_arg = required_argument},
4382         { .val = LFS_NEWERXY_OPT,
4383                         .name = "newerBt",      .has_arg = required_argument},
4384         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument },
4385         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument },
4386         { .val = 'C',   .name = "ctime",        .has_arg = required_argument },
4387 /* getstripe { .val = 'd', .name = "directory", .has_arg = no_argument }, */
4388         { .val = 'D',   .name = "maxdepth",     .has_arg = required_argument },
4389         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument },
4390         { .val = 'E',   .name = "component-end",
4391                                                 .has_arg = required_argument },
4392 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
4393         { .val = LFS_LAYOUT_FOREIGN_OPT,
4394                         .name = "foreign",      .has_arg = optional_argument},
4395         { .val = 'g',   .name = "gid",          .has_arg = required_argument },
4396         { .val = 'G',   .name = "group",        .has_arg = required_argument },
4397         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
4398         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument },
4399         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument },
4400 /* getstripe { .val = 'I', .name = "comp-id",   .has_arg = required_argument }*/
4401         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
4402         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
4403         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
4404         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
4405         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument },
4406         { .val = 'M',   .name = "mtime",        .has_arg = required_argument },
4407         { .val = 'n',   .name = "name",         .has_arg = required_argument },
4408         { .val = 'N',   .name = "mirror-count", .has_arg = required_argument },
4409 /* find { .val = 'o'    .name = "or", .has_arg = no_argument }, like find(1) */
4410         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
4411         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
4412         /* no short option for pool yet, can be 'p' after 2.18 */
4413         { .val = LFS_POOL_OPT,
4414                         .name = "pool",         .has_arg = required_argument },
4415         { .val = '0',   .name = "print0",       .has_arg = no_argument },
4416         { .val = 'P',   .name = "print",        .has_arg = no_argument },
4417         { .val = LFS_PROJID_OPT,
4418                         .name = "projid",       .has_arg = required_argument },
4419 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
4420 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
4421 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
4422         { .val = 's',   .name = "size",         .has_arg = required_argument },
4423         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
4424         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
4425         { .val = 't',   .name = "type",         .has_arg = required_argument },
4426         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
4427         { .val = 'u',   .name = "uid",          .has_arg = required_argument },
4428         { .val = 'U',   .name = "user",         .has_arg = required_argument },
4429         { .val = 'z',   .name = "extension-size",
4430                                                 .has_arg = required_argument },
4431         { .val = 'z',   .name = "ext-size",     .has_arg = required_argument },
4432 /* getstripe { .val = 'v', .name = "verbose",   .has_arg = no_argument }, */
4433 /* getstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
4434         { .name = NULL } };
4435         int optidx = 0;
4436         int pathstart = -1;
4437         int pathend = -1;
4438         int pathbad = -1;
4439         int neg_opt = 0;
4440         time_t *xtime;
4441         int *xsign;
4442         int isoption;
4443         char *endptr;
4444
4445         time(&t);
4446
4447         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
4448         while ((c = getopt_long_only(argc, argv,
4449                 "-0A:b:B:c:C:D:E:g:G:H:i:L:m:M:n:N:O:Ppqrs:S:t:T:u:U:vz:",
4450                 long_opts, &optidx)) >= 0) {
4451                 xtime = NULL;
4452                 xsign = NULL;
4453                 if (neg_opt)
4454                         --neg_opt;
4455                 /* '!' is part of option */
4456                 /*
4457                  * when getopt_long_only() finds a string which is not
4458                  * an option nor a known option argument it returns 1
4459                  * in that case if we already have found pathstart and pathend
4460                  * (i.e. we have the list of pathnames),
4461                  * the only supported value is "!"
4462                  */
4463                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
4464                 if (!isoption && pathend != -1) {
4465                         fprintf(stderr,
4466                                 "err: %s: filename|dirname must either precede options or follow options\n",
4467                                 argv[0]);
4468                         ret = CMD_HELP;
4469                         goto err;
4470                 }
4471                 if (!isoption && pathstart == -1)
4472                         pathstart = optind - 1;
4473                 if (isoption && pathstart != -1 && pathend == -1)
4474                         pathend = optind - 2;
4475                 switch (c) {
4476                 case 0:
4477                         /* Long options. */
4478                         break;
4479                 case 1:
4480                         /*
4481                          * unknown; opt is "!" or path component,
4482                          * checking done above.
4483                          */
4484                         if (strcmp(optarg, "!") == 0)
4485                                 neg_opt = 2;
4486                         break;
4487                 case 'A':
4488                         xtime = &param.fp_atime;
4489                         xsign = &param.fp_asign;
4490                         param.fp_exclude_atime = !!neg_opt;
4491                         /* no break, this falls through to 'B' for btime */
4492                 case 'B':
4493                         if (c == 'B') {
4494                                 xtime = &param.fp_btime;
4495                                 xsign = &param.fp_bsign;
4496                                 param.fp_exclude_btime = !!neg_opt;
4497                         }
4498                         /* no break, this falls through to 'C' for ctime */
4499                 case 'C':
4500                         if (c == 'C') {
4501                                 xtime = &param.fp_ctime;
4502                                 xsign = &param.fp_csign;
4503                                 param.fp_exclude_ctime = !!neg_opt;
4504                         }
4505                         /* no break, this falls through to 'M' for mtime */
4506                 case 'M':
4507                         if (c == 'M') {
4508                                 xtime = &param.fp_mtime;
4509                                 xsign = &param.fp_msign;
4510                                 param.fp_exclude_mtime = !!neg_opt;
4511                         }
4512                         rc = set_time(&param, &t, xtime, optarg);
4513                         if (rc == LONG_MAX) {
4514                                 ret = -1;
4515                                 goto err;
4516                         }
4517                         if (rc)
4518                                 *xsign = rc;
4519                         break;
4520                 case 'b':
4521                         if (optarg[0] == '+') {
4522                                 param.fp_blocks_sign = -1;
4523                                 optarg++;
4524                         } else if (optarg[0] == '-') {
4525                                 param.fp_blocks_sign =  1;
4526                                 optarg++;
4527                         }
4528
4529                         param.fp_blocks_units = 1024;
4530                         ret = llapi_parse_size(optarg, &param.fp_blocks,
4531                                                &param.fp_blocks_units, 0);
4532                         if (ret) {
4533                                 fprintf(stderr, "error: bad blocks '%s'\n",
4534                                         optarg);
4535                                 goto err;
4536                         }
4537                         param.fp_check_blocks = 1;
4538                         param.fp_exclude_blocks = !!neg_opt;
4539                         break;
4540                 case LFS_COMP_COUNT_OPT:
4541                         if (optarg[0] == '+') {
4542                                 param.fp_comp_count_sign = -1;
4543                                 optarg++;
4544                         } else if (optarg[0] == '-') {
4545                                 param.fp_comp_count_sign =  1;
4546                                 optarg++;
4547                         }
4548
4549                         param.fp_comp_count = strtoul(optarg, &endptr, 0);
4550                         if (*endptr != '\0') {
4551                                 fprintf(stderr,
4552                                         "error: bad component count '%s'\n",
4553                                         optarg);
4554                                 goto err;
4555                         }
4556                         param.fp_check_comp_count = 1;
4557                         param.fp_exclude_comp_count = !!neg_opt;
4558                         break;
4559                 case LFS_COMP_FLAGS_OPT:
4560                         rc = comp_str2flags(optarg, &param.fp_comp_flags,
4561                                             &param.fp_comp_neg_flags);
4562                         if (rc) {
4563                                 fprintf(stderr,
4564                                         "error: bad component flags '%s'\n",
4565                                         optarg);
4566                                 goto err;
4567                         }
4568                         param.fp_check_comp_flags = 1;
4569                         if (neg_opt) {
4570                                 __u32 flags = param.fp_comp_neg_flags;
4571
4572                                 param.fp_comp_neg_flags = param.fp_comp_flags;
4573                                 param.fp_comp_flags = flags;
4574                         }
4575                         break;
4576                 case LFS_COMP_START_OPT:
4577                         if (optarg[0] == '+') {
4578                                 param.fp_comp_start_sign = -1;
4579                                 optarg++;
4580                         } else if (optarg[0] == '-') {
4581                                 param.fp_comp_start_sign =  1;
4582                                 optarg++;
4583                         }
4584
4585                         rc = llapi_parse_size(optarg, &param.fp_comp_start,
4586                                               &param.fp_comp_start_units, 0);
4587                         if (rc) {
4588                                 fprintf(stderr,
4589                                         "error: bad component start '%s'\n",
4590                                         optarg);
4591                                 goto err;
4592                         }
4593                         param.fp_check_comp_start = 1;
4594                         param.fp_exclude_comp_start = !!neg_opt;
4595                         break;
4596                 case LFS_MIRROR_STATE_OPT:
4597                         rc = mirror_str2state(optarg, &param.fp_mirror_state,
4598                                               &param.fp_mirror_neg_state);
4599                         if (rc) {
4600                                 fprintf(stderr,
4601                                         "error: bad mirrored file state '%s'\n",
4602                                         optarg);
4603                                 goto err;
4604                         }
4605                         param.fp_check_mirror_state = 1;
4606                         if (neg_opt) {
4607                                 __u16 state = param.fp_mirror_neg_state;
4608
4609                                 param.fp_mirror_neg_state =
4610                                         param.fp_mirror_state;
4611                                 param.fp_mirror_state = state;
4612                         }
4613                         break;
4614                 case 'c':
4615                         if (optarg[0] == '+') {
4616                                 param.fp_stripe_count_sign = -1;
4617                                 optarg++;
4618                         } else if (optarg[0] == '-') {
4619                                 param.fp_stripe_count_sign =  1;
4620                                 optarg++;
4621                         }
4622
4623                         param.fp_stripe_count = strtoul(optarg, &endptr, 0);
4624                         if (*endptr != '\0') {
4625                                 fprintf(stderr,
4626                                         "error: bad stripe_count '%s'\n",
4627                                         optarg);
4628                                 ret = -1;
4629                                 goto err;
4630                         }
4631                         param.fp_check_stripe_count = 1;
4632                         param.fp_exclude_stripe_count = !!neg_opt;
4633                         break;
4634                 case 'D':
4635                         param.fp_max_depth = strtol(optarg, 0, 0);
4636                         break;
4637                 case 'E':
4638                         if (optarg[0] == '+') {
4639                                 param.fp_comp_end_sign = -1;
4640                                 optarg++;
4641                         } else if (optarg[0] == '-') {
4642                                 param.fp_comp_end_sign =  1;
4643                                 optarg++;
4644                         }
4645
4646                         if (arg_is_eof(optarg)) {
4647                                 param.fp_comp_end = LUSTRE_EOF;
4648                                 param.fp_comp_end_units = 1;
4649                                 rc = 0;
4650                         } else {
4651                                 rc = llapi_parse_size(optarg,
4652                                                 &param.fp_comp_end,
4653                                                 &param.fp_comp_end_units, 0);
4654                         }
4655                         if (rc) {
4656                                 fprintf(stderr,
4657                                         "error: bad component end '%s'\n",
4658                                         optarg);
4659                                 goto err;
4660                         }
4661                         param.fp_check_comp_end = 1;
4662                         param.fp_exclude_comp_end = !!neg_opt;
4663                         break;
4664                 case LFS_LAYOUT_FOREIGN_OPT: {
4665                         /* all types by default */
4666                         uint32_t type = LU_FOREIGN_TYPE_UNKNOWN;
4667
4668                         if (optarg) {
4669                                 /* check pure numeric */
4670                                 type = strtoul(optarg, &endptr, 0);
4671                                 if (*endptr) {
4672                                         /* check name */
4673                                         type = check_foreign_type_name(optarg);
4674                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
4675                                                 fprintf(stderr,
4676                                                         "%s %s: unknown foreign type '%s'\n",
4677                                                         progname, argv[0],
4678                                                         optarg);
4679                                                 return CMD_HELP;
4680                                         }
4681                                 }
4682                         }
4683                         param.fp_foreign_type = type;
4684                         param.fp_check_foreign = 1;
4685                         param.fp_exclude_foreign = !!neg_opt;
4686                         break;
4687                 }
4688                 case LFS_NEWERXY_OPT: {
4689                         char x = 'm';
4690                         char y = 'm';
4691                         int xidx;
4692                         int negidx;
4693                         time_t *newery;
4694                         time_t ref = time(NULL);
4695
4696                         /* no need to check bad options, they won't get here */
4697                         if (strlen(long_opts[optidx].name) == 7) {
4698                                 x = long_opts[optidx].name[5];
4699                                 y = long_opts[optidx].name[6];
4700                         }
4701
4702                         if (y == 't') {
4703                                 static const char *const fmts[] = {
4704                                         "%Y-%m-%d %H:%M:%S",
4705                                         "%Y-%m-%d %H:%M",
4706                                         "%Y-%m-%d",
4707                                         "%H:%M:%S", /* sometime today */
4708                                         "%H:%M",
4709                                         "@%s",
4710                                         "%s",
4711                                         NULL };
4712                                 struct tm tm;
4713                                 bool found = false;
4714                                 int i;
4715
4716                                 for (i = 0; fmts[i] != NULL; i++) {
4717                                         char *ptr;
4718
4719                                         /* Init for times relative to today */
4720                                         if (strncmp(fmts[i], "%H", 2) == 0)
4721                                                 localtime_r(&ref, &tm);
4722                                         else
4723                                                 memset(&tm, 0, sizeof(tm));
4724                                         ptr = strptime(optarg, fmts[i], &tm);
4725                                         /* Skip spaces */
4726                                         while (ptr && isspace(*ptr))
4727                                                 ptr++;
4728                                         if (ptr == optarg + strlen(optarg)) {
4729                                                 found = true;
4730                                                 break;
4731                                         }
4732                                 }
4733
4734                                 if (!found) {
4735                                         fprintf(stderr,
4736                                                 "%s: invalid time '%s'\n",
4737                                                 progname, optarg);
4738                                         fprintf(stderr,
4739                                                 "supported formats are:\n  ");
4740                                         for (i = 0; fmts[i] != NULL; i++)
4741                                                 fprintf(stderr, "'%s', ",
4742                                                         fmts[i]);
4743                                         fprintf(stderr, "\n");
4744                                         ret = -EINVAL;
4745                                         goto err;
4746                                 }
4747
4748                                 ref = mktime(&tm);
4749                         } else if (y == 'b' || y == 'B') {
4750                                 lstatx_t stx;
4751
4752                                 rc = llapi_get_lum_file(optarg, NULL, &stx,
4753                                                         NULL, 0);
4754                                 if (rc || !(stx.stx_mask & STATX_BTIME)) {
4755                                         if (!(stx.stx_mask & STATX_BTIME))
4756                                                 ret = -EOPNOTSUPP;
4757                                         else
4758                                                 ret = -errno;
4759                                         fprintf(stderr,
4760                                                 "%s: get btime failed '%s': %s\n",
4761                                                 progname, optarg,
4762                                                 strerror(-ret));
4763                                         goto err;
4764                                 }
4765
4766                                 ref = stx.stx_btime.tv_sec;
4767                         } else {
4768                                 struct stat statbuf;
4769
4770                                 if (stat(optarg, &statbuf) < 0) {
4771                                         fprintf(stderr,
4772                                                 "%s: cannot stat file '%s': %s\n",
4773                                                 progname, optarg,
4774                                                 strerror(errno));
4775                                         ret = -errno;
4776                                         goto err;
4777                                 }
4778
4779                                 switch (y) {
4780                                 case 'a':
4781                                         ref = statbuf.st_atime;
4782                                         break;
4783                                 case 'm':
4784                                         ref = statbuf.st_mtime;
4785                                         break;
4786                                 case 'c':
4787                                         ref = statbuf.st_ctime;
4788                                         break;
4789                                 default:
4790                                         fprintf(stderr,
4791                                                 "%s: invalid Y argument: '%c'\n",
4792                                                 progname, x);
4793                                         ret = -EINVAL;
4794                                         goto err;
4795                                 }
4796                         }
4797
4798                         switch (x) {
4799                         case 'a':
4800                                 xidx = NEWERXY_ATIME;
4801                                 break;
4802                         case 'm':
4803                                 xidx = NEWERXY_MTIME;
4804                                 break;
4805                         case 'c':
4806                                 xidx = NEWERXY_CTIME;
4807                                 break;
4808                         case 'b':
4809                         case 'B':
4810                                 xidx = NEWERXY_BTIME;
4811                                 break;
4812                         default:
4813                                 fprintf(stderr,
4814                                         "%s: invalid X argument: '%c'\n",
4815                                         progname, x);
4816                                 ret = -EINVAL;
4817                                 goto err;
4818                         }
4819
4820                         negidx = !!neg_opt;
4821                         newery = &param.fp_newery[xidx][negidx];
4822
4823                         if (*newery == 0) {
4824                                 *newery = ref;
4825                         } else {
4826                                 if (negidx)
4827                                         *newery = *newery > ref ? ref : *newery;
4828                                 else
4829                                         *newery = *newery > ref ? *newery : ref;
4830                         }
4831                         param.fp_newerxy = 1;
4832                         break;
4833                 }
4834                 case 'g':
4835                 case 'G':
4836                         rc = name2gid(&param.fp_gid, optarg);
4837                         if (rc) {
4838                                 if (str2quotaid(&param.fp_gid, optarg)) {
4839                                         fprintf(stderr,
4840                                                 "Group/GID: %s cannot be found.\n",
4841                                                 optarg);
4842                                         ret = -1;
4843                                         goto err;
4844                                 }
4845                         }
4846                         param.fp_exclude_gid = !!neg_opt;
4847                         param.fp_check_gid = 1;
4848                         break;
4849                 case 'H':
4850                         param.fp_hash_type = check_hashtype(optarg);
4851                         if (param.fp_hash_type == 0) {
4852                                 fprintf(stderr, "error: bad hash_type '%s'\n",
4853                                         optarg);
4854                                 ret = -1;
4855                                 goto err;
4856                         }
4857                         param.fp_check_hash_type = 1;
4858                         param.fp_exclude_hash_type = !!neg_opt;
4859                         break;
4860                 case 'l':
4861                         param.fp_lazy = 1;
4862                         break;
4863                 case 'L':
4864                         ret = name2layout(&param.fp_layout, optarg);
4865                         if (ret)
4866                                 goto err;
4867                         param.fp_exclude_layout = !!neg_opt;
4868                         param.fp_check_layout = 1;
4869                         break;
4870                 case 'u':
4871                 case 'U':
4872                         rc = name2uid(&param.fp_uid, optarg);
4873                         if (rc) {
4874                                 if (str2quotaid(&param.fp_uid, optarg)) {
4875                                         fprintf(stderr,
4876                                                 "User/UID: %s cannot be found.\n",
4877                                                 optarg);
4878                                         ret = -1;
4879                                         goto err;
4880                                 }
4881                         }
4882                         param.fp_exclude_uid = !!neg_opt;
4883                         param.fp_check_uid = 1;
4884                         break;
4885                 case 'n':
4886                         param.fp_pattern = (char *)optarg;
4887                         param.fp_exclude_pattern = !!neg_opt;
4888                         break;
4889                 case 'N':
4890                         if (optarg[0] == '+') {
4891                                 param.fp_mirror_count_sign = -1;
4892                                 optarg++;
4893                         } else if (optarg[0] == '-') {
4894                                 param.fp_mirror_count_sign =  1;
4895                                 optarg++;
4896                         }
4897
4898                         param.fp_mirror_count = strtoul(optarg, &endptr, 0);
4899                         if (*endptr != '\0') {
4900                                 fprintf(stderr,
4901                                         "error: bad mirror count '%s'\n",
4902                                         optarg);
4903                                 goto err;
4904                         }
4905                         param.fp_check_mirror_count = 1;
4906                         param.fp_exclude_mirror_count = !!neg_opt;
4907                         break;
4908                 case 'm':
4909                 case 'i':
4910                 case 'O': {
4911                         char *buf, *token, *next, *p;
4912                         int len = 1;
4913                         void *tmp;
4914
4915                         buf = strdup(optarg);
4916                         if (!buf) {
4917                                 ret = -ENOMEM;
4918                                 goto err;
4919                         }
4920
4921                         param.fp_exclude_obd = !!neg_opt;
4922
4923                         token = buf;
4924                         while (token && *token) {
4925                                 token = strchr(token, ',');
4926                                 if (token) {
4927                                         len++;
4928                                         token++;
4929                                 }
4930                         }
4931                         if (c == 'm') {
4932                                 param.fp_exclude_mdt = !!neg_opt;
4933                                 param.fp_num_alloc_mdts += len;
4934                                 tmp = realloc(param.fp_mdt_uuid,
4935                                               param.fp_num_alloc_mdts *
4936                                               sizeof(*param.fp_mdt_uuid));
4937                                 if (!tmp) {
4938                                         ret = -ENOMEM;
4939                                         goto err_free;
4940                                 }
4941
4942                                 param.fp_mdt_uuid = tmp;
4943                         } else {
4944                                 param.fp_exclude_obd = !!neg_opt;
4945                                 param.fp_num_alloc_obds += len;
4946                                 tmp = realloc(param.fp_obd_uuid,
4947                                               param.fp_num_alloc_obds *
4948                                               sizeof(*param.fp_obd_uuid));
4949                                 if (!tmp) {
4950                                         ret = -ENOMEM;
4951                                         goto err_free;
4952                                 }
4953
4954                                 param.fp_obd_uuid = tmp;
4955                         }
4956                         for (token = buf; token && *token; token = next) {
4957                                 struct obd_uuid *puuid;
4958
4959                                 if (c == 'm') {
4960                                         puuid =
4961                                         &param.fp_mdt_uuid[param.fp_num_mdts++];
4962                                 } else {
4963                                         puuid =
4964                                         &param.fp_obd_uuid[param.fp_num_obds++];
4965                                 }
4966                                 p = strchr(token, ',');
4967                                 next = 0;
4968                                 if (p) {
4969                                         *p = 0;
4970                                         next = p+1;
4971                                 }
4972
4973                                 if (strlen(token) > sizeof(puuid->uuid) - 1) {
4974                                         ret = -E2BIG;
4975                                         goto err_free;
4976                                 }
4977
4978                                 strncpy(puuid->uuid, token,
4979                                         sizeof(puuid->uuid));
4980                         }
4981 err_free:
4982                         if (buf)
4983                                 free(buf);
4984                         break;
4985                 }
4986 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 18, 53, 0)
4987                 case 'p':
4988 #endif
4989                 case LFS_POOL_OPT:
4990                         if (strlen(optarg) > LOV_MAXPOOLNAME) {
4991                                 fprintf(stderr,
4992                                         "Pool name %s is too long (max %d)\n",
4993                                         optarg, LOV_MAXPOOLNAME);
4994                                 ret = -1;
4995                                 goto err;
4996                         }
4997                         /*
4998                          * We do check for empty pool because empty pool
4999                          * is used to find V1 LOV attributes
5000                          */
5001                         strncpy(param.fp_poolname, optarg, LOV_MAXPOOLNAME);
5002                         param.fp_poolname[LOV_MAXPOOLNAME] = '\0';
5003                         param.fp_exclude_pool = !!neg_opt;
5004                         param.fp_check_pool = 1;
5005                         break;
5006 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 14, 53, 0)
5007                 case 'p': /* want this for --pool, to match getstripe/find */
5008                         fprintf(stderr,
5009                                 "warning: -p deprecated, use --print0 or -0\n");
5010 #endif
5011                 case '0':
5012                         param.fp_zero_end = 1;
5013                         break;
5014                 case 'P': /* we always print, this option is a no-op */
5015                         break;
5016                 case LFS_PROJID_OPT:
5017                         rc = name2projid(&param.fp_projid, optarg);
5018                         if (rc) {
5019                                 if (str2quotaid(&param.fp_projid, optarg)) {
5020                                         fprintf(stderr,
5021                                                 "Invalid project ID: %s\n",
5022                                                 optarg);
5023                                         ret = -1;
5024                                         goto err;
5025                                 }
5026                         }
5027                         param.fp_exclude_projid = !!neg_opt;
5028                         param.fp_check_projid = 1;
5029                         break;
5030                 case 's':
5031                         if (optarg[0] == '+') {
5032                                 param.fp_size_sign = -1;
5033                                 optarg++;
5034                         } else if (optarg[0] == '-') {
5035                                 param.fp_size_sign =  1;
5036                                 optarg++;
5037                         }
5038
5039                         ret = llapi_parse_size(optarg, &param.fp_size,
5040                                                &param.fp_size_units, 0);
5041                         if (ret) {
5042                                 fprintf(stderr, "error: bad file size '%s'\n",
5043                                         optarg);
5044                                 goto err;
5045                         }
5046                         param.fp_check_size = 1;
5047                         param.fp_exclude_size = !!neg_opt;
5048                         break;
5049                 case 'S':
5050                         if (optarg[0] == '+') {
5051                                 param.fp_stripe_size_sign = -1;
5052                                 optarg++;
5053                         } else if (optarg[0] == '-') {
5054                                 param.fp_stripe_size_sign =  1;
5055                                 optarg++;
5056                         }
5057
5058                         ret = llapi_parse_size(optarg, &param.fp_stripe_size,
5059                                                &param.fp_stripe_size_units, 0);
5060                         if (ret) {
5061                                 fprintf(stderr, "error: bad stripe_size '%s'\n",
5062                                         optarg);
5063                                 goto err;
5064                         }
5065                         param.fp_check_stripe_size = 1;
5066                         param.fp_exclude_stripe_size = !!neg_opt;
5067                         break;
5068                 case 't':
5069                         param.fp_exclude_type = !!neg_opt;
5070                         switch (optarg[0]) {
5071                         case 'b':
5072                                 param.fp_type = S_IFBLK;
5073                                 break;
5074                         case 'c':
5075                                 param.fp_type = S_IFCHR;
5076                                 break;
5077                         case 'd':
5078                                 param.fp_type = S_IFDIR;
5079                                 break;
5080                         case 'f':
5081                                 param.fp_type = S_IFREG;
5082                                 break;
5083                         case 'l':
5084                                 param.fp_type = S_IFLNK;
5085                                 break;
5086                         case 'p':
5087                                 param.fp_type = S_IFIFO;
5088                                 break;
5089                         case 's':
5090                                 param.fp_type = S_IFSOCK;
5091                                 break;
5092                         default:
5093                                 fprintf(stderr, "error: %s: bad type '%s'\n",
5094                                         argv[0], optarg);
5095                                 ret = CMD_HELP;
5096                                 goto err;
5097                         };
5098                         break;
5099                 case 'T':
5100                         if (optarg[0] == '+') {
5101                                 param.fp_mdt_count_sign = -1;
5102                                 optarg++;
5103                         } else if (optarg[0] == '-') {
5104                                 param.fp_mdt_count_sign =  1;
5105                                 optarg++;
5106                         }
5107
5108                         param.fp_mdt_count = strtoul(optarg, &endptr, 0);
5109                         if (*endptr != '\0') {
5110                                 fprintf(stderr, "error: bad mdt_count '%s'\n",
5111                                         optarg);
5112                                 ret = -1;
5113                                 goto err;
5114                         }
5115                         param.fp_check_mdt_count = 1;
5116                         param.fp_exclude_mdt_count = !!neg_opt;
5117                         break;
5118                 case 'z':
5119                         if (optarg[0] == '+') {
5120                                 param.fp_ext_size_sign = -1;
5121                                 optarg++;
5122                         } else if (optarg[0] == '-') {
5123                                 param.fp_ext_size_sign =  1;
5124                                 optarg++;
5125                         }
5126
5127                         ret = llapi_parse_size(optarg, &param.fp_ext_size,
5128                                                &param.fp_ext_size_units, 0);
5129                         if (ret) {
5130                                 fprintf(stderr, "error: bad ext-size '%s'\n",
5131                                         optarg);
5132                                 goto err;
5133                         }
5134                         param.fp_ext_size /= SEL_UNIT_SIZE;
5135                         param.fp_ext_size_units /= SEL_UNIT_SIZE;
5136                         param.fp_check_ext_size = 1;
5137                         param.fp_exclude_ext_size = !!neg_opt;
5138                         break;
5139                 default:
5140                         ret = CMD_HELP;
5141                         goto err;
5142                 };
5143         }
5144
5145         if (pathstart == -1) {
5146                 fprintf(stderr, "error: %s: no filename|pathname\n",
5147                         argv[0]);
5148                 ret = CMD_HELP;
5149                 goto err;
5150         } else if (pathend == -1) {
5151                 /* no options */
5152                 pathend = argc;
5153         }
5154
5155         do {
5156                 rc = llapi_find(argv[pathstart], &param);
5157                 if (rc && !ret) {
5158                         ret = rc;
5159                         pathbad = pathstart;
5160                 }
5161         } while (++pathstart < pathend);
5162
5163         if (ret)
5164                 fprintf(stderr, "%s: failed for '%s': %s\n",
5165                         progname, argv[pathbad], strerror(-rc));
5166
5167 err:
5168         if (param.fp_obd_uuid && param.fp_num_alloc_obds)
5169                 free(param.fp_obd_uuid);
5170
5171         if (param.fp_mdt_uuid && param.fp_num_alloc_mdts)
5172                 free(param.fp_mdt_uuid);
5173
5174         return ret;
5175 }
5176
5177 static int lfs_getstripe_internal(int argc, char **argv,
5178                                   struct find_param *param)
5179 {
5180         struct option long_opts[] = {
5181 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
5182 /* find { .val = 'b',   .name = "blocks",       .has_arg = required_argument }*/
5183 /* find { .val = 'B',   .name = "btime",        .has_arg = required_argument }*/
5184 /* find { .val = 'B',   .name = "Btime",        .has_arg = required_argument }*/
5185         { .val = LFS_COMP_COUNT_OPT,
5186                         .name = "comp-count",   .has_arg = no_argument },
5187         { .val = LFS_COMP_COUNT_OPT,
5188                 .name = "component-count",      .has_arg = no_argument },
5189         { .val = LFS_COMP_FLAGS_OPT,
5190                         .name = "comp-flags",   .has_arg = optional_argument },
5191         { .val = LFS_COMP_FLAGS_OPT,
5192                 .name = "component-flags",      .has_arg = optional_argument },
5193         { .val = LFS_COMP_START_OPT,
5194                         .name = "comp-start",   .has_arg = optional_argument },
5195         { .val = LFS_COMP_START_OPT,
5196                 .name = "component-start",      .has_arg = optional_argument },
5197         { .val = LFS_MIRROR_INDEX_OPT,
5198                 .name = "mirror-index",         .has_arg = required_argument },
5199         { .val = LFS_MIRROR_ID_OPT,
5200                 .name = "mirror-id",            .has_arg = required_argument },
5201         { .val = 'c',   .name = "stripe-count", .has_arg = no_argument },
5202         { .val = 'c',   .name = "stripe_count", .has_arg = no_argument },
5203 /* find { .val = 'C',   .name = "ctime",        .has_arg = required_argument }*/
5204         { .val = 'd',   .name = "directory",    .has_arg = no_argument },
5205         { .val = 'D',   .name = "default",      .has_arg = no_argument },
5206         { .val = 'E',   .name = "comp-end",     .has_arg = optional_argument },
5207         { .val = 'E',   .name = "component-end", .has_arg = optional_argument },
5208         { .val = 'F',   .name = "fid",          .has_arg = no_argument },
5209         { .val = 'g',   .name = "generation",   .has_arg = no_argument },
5210 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
5211 /* dirstripe { .val = 'H', .name = "mdt-hash",  .has_arg = required_argument }*/
5212         { .val = 'i',   .name = "stripe-index", .has_arg = no_argument },
5213         { .val = 'i',   .name = "stripe_index", .has_arg = no_argument },
5214         { .val = 'I',   .name = "comp-id",      .has_arg = optional_argument },
5215         { .val = 'I',   .name = "component-id", .has_arg = optional_argument },
5216 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
5217         { .val = 'L',   .name = "layout",       .has_arg = no_argument },
5218         { .val = 'm',   .name = "mdt",          .has_arg = no_argument },
5219         { .val = 'm',   .name = "mdt-index",    .has_arg = no_argument },
5220         { .val = 'm',   .name = "mdt_index",    .has_arg = no_argument },
5221 /* find { .val = 'M',   .name = "mtime",        .has_arg = required_argument }*/
5222 /* find { .val = 'n',   .name = "name",         .has_arg = required_argument }*/
5223         { .val = 'N',   .name = "mirror-count", .has_arg = no_argument },
5224         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
5225         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
5226         { .val = 'p',   .name = "pool",         .has_arg = no_argument },
5227 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
5228         { .val = 'q',   .name = "quiet",        .has_arg = no_argument },
5229         { .val = 'r',   .name = "recursive",    .has_arg = no_argument },
5230         { .val = 'R',   .name = "raw",          .has_arg = no_argument },
5231         { .val = 'S',   .name = "stripe-size",  .has_arg = no_argument },
5232         { .val = 'S',   .name = "stripe_size",  .has_arg = no_argument },
5233 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
5234 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
5235 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
5236 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
5237         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
5238         { .val = 'y',   .name = "yaml",         .has_arg = no_argument },
5239         { .val = 'z',   .name = "extension-size", .has_arg = no_argument },
5240         { .val = 'z',   .name = "ext-size",     .has_arg = no_argument },
5241         { .name = NULL } };
5242         int c, rc;
5243         int neg_opt = 0;
5244         int pathstart = -1, pathend = -1;
5245         int isoption;
5246         char *end, *tmp;
5247
5248         while ((c = getopt_long(argc, argv,
5249                         "-cdDE::FghiI::LmMNoO:pqrRsSvyz",
5250                         long_opts, NULL)) != -1) {
5251                 if (neg_opt)
5252                         --neg_opt;
5253
5254                 /* '!' is part of option */
5255                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
5256                 if (!isoption && pathend != -1) {
5257                         fprintf(stderr,
5258                                 "error: %s: filename|dirname must either precede options or follow options\n",
5259                                 argv[0]);
5260                         return CMD_HELP;
5261                 }
5262                 if (!isoption && pathstart == -1)
5263                         pathstart = optind - 1;
5264                 if (isoption && pathstart != -1 && pathend == -1)
5265                         pathend = optind - 2;
5266
5267                 switch (c) {
5268                 case 1:
5269                         /* unknown: opt is "!" */
5270                         if (strcmp(optarg, "!") == 0)
5271                                 neg_opt = 2;
5272                         break;
5273                 case 'c':
5274                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
5275                                 param->fp_verbose |= VERBOSE_COUNT;
5276                                 param->fp_max_depth = 0;
5277                         }
5278                         break;
5279                 case LFS_COMP_COUNT_OPT:
5280                         param->fp_verbose |= VERBOSE_COMP_COUNT;
5281                         param->fp_max_depth = 0;
5282                         break;
5283                 case LFS_COMP_FLAGS_OPT:
5284                         if (optarg) {
5285                                 rc = comp_str2flags(optarg,
5286                                                     &param->fp_comp_flags,
5287                                                     &param->fp_comp_neg_flags);
5288                                 if (rc != 0) {
5289                                         fprintf(stderr,
5290                                                 "error: %s bad component flags '%s'.\n",
5291                                                 argv[0], optarg);
5292                                         return CMD_HELP;
5293                                 }
5294                                 param->fp_check_comp_flags = 1;
5295                         } else {
5296                                 param->fp_verbose |= VERBOSE_COMP_FLAGS;
5297                                 param->fp_max_depth = 0;
5298                         }
5299                         break;
5300                 case LFS_COMP_START_OPT:
5301                         if (optarg) {
5302                                 tmp = optarg;
5303                                 if (tmp[0] == '+') {
5304                                         param->fp_comp_start_sign = -1;
5305                                         tmp++;
5306                                 } else if (tmp[0] == '-') {
5307                                         param->fp_comp_start_sign = 1;
5308                                         tmp++;
5309                                 }
5310                                 rc = llapi_parse_size(tmp,
5311                                                 &param->fp_comp_start,
5312                                                 &param->fp_comp_start_units, 0);
5313                                 if (rc != 0) {
5314                                         fprintf(stderr,
5315                                                 "error: %s bad component start '%s'.\n",
5316                                                 argv[0], tmp);
5317                                         return CMD_HELP;
5318                                 }
5319                                 param->fp_check_comp_start = 1;
5320                         } else {
5321                                 param->fp_verbose |= VERBOSE_COMP_START;
5322                                 param->fp_max_depth = 0;
5323                         }
5324                         break;
5325                 case LFS_MIRROR_INDEX_OPT:
5326                         if (optarg[0] == '+') {
5327                                 param->fp_mirror_index_sign = -1;
5328                                 optarg++;
5329                         } else if (optarg[0] == '-') {
5330                                 param->fp_mirror_index_sign = 1;
5331                                 optarg++;
5332                         }
5333
5334                         param->fp_mirror_index = strtoul(optarg, &end, 0);
5335                         if (*end != '\0' || (param->fp_mirror_index == 0 &&
5336                             param->fp_mirror_index_sign == 0 && neg_opt == 0)) {
5337                                 fprintf(stderr,
5338                                         "%s %s: invalid mirror index '%s'\n",
5339                                         progname, argv[0], optarg);
5340                                 return CMD_HELP;
5341                         }
5342                         if (param->fp_mirror_id != 0) {
5343                                 fprintf(stderr,
5344                                         "%s %s: can't specify both mirror index and mirror ID\n",
5345                                         progname, argv[0]);
5346                                 return CMD_HELP;
5347                         }
5348                         param->fp_check_mirror_index = 1;
5349                         param->fp_exclude_mirror_index = !!neg_opt;
5350                         break;
5351                 case LFS_MIRROR_ID_OPT:
5352                         if (optarg[0] == '+') {
5353                                 param->fp_mirror_id_sign = -1;
5354                                 optarg++;
5355                         } else if (optarg[0] == '-') {
5356                                 param->fp_mirror_id_sign = 1;
5357                                 optarg++;
5358                         }
5359
5360                         param->fp_mirror_id = strtoul(optarg, &end, 0);
5361                         if (*end != '\0' || (param->fp_mirror_id == 0 &&
5362                             param->fp_mirror_id_sign == 0 && neg_opt == 0)) {
5363                                 fprintf(stderr,
5364                                         "%s %s: invalid mirror ID '%s'\n",
5365                                         progname, argv[0], optarg);
5366                                 return CMD_HELP;
5367                         }
5368                         if (param->fp_mirror_index != 0) {
5369                                 fprintf(stderr,
5370                                         "%s %s: can't specify both mirror index and mirror ID\n",
5371                                         progname, argv[0]);
5372                                 return CMD_HELP;
5373                         }
5374                         param->fp_check_mirror_id = 1;
5375                         param->fp_exclude_mirror_id = !!neg_opt;
5376                         break;
5377                 case 'd':
5378                         param->fp_max_depth = 0;
5379                         break;
5380                 case 'D':
5381                         param->fp_get_default_lmv = 1;
5382                         break;
5383                 case 'E':
5384                         if (optarg) {
5385                                 tmp = optarg;
5386                                 if (tmp[0] == '+') {
5387                                         param->fp_comp_end_sign = -1;
5388                                         tmp++;
5389                                 } else if (tmp[0] == '-') {
5390                                         param->fp_comp_end_sign = 1;
5391                                         tmp++;
5392                                 }
5393
5394                                 if (arg_is_eof(tmp)) {
5395                                         param->fp_comp_end = LUSTRE_EOF;
5396                                         param->fp_comp_end_units = 1;
5397                                         rc = 0;
5398                                 } else {
5399                                         rc = llapi_parse_size(tmp,
5400                                                 &param->fp_comp_end,
5401                                                 &param->fp_comp_end_units, 0);
5402                                 }
5403                                 if (rc != 0) {
5404                                         fprintf(stderr,
5405                                                 "error: %s bad component end '%s'.\n",
5406                                                 argv[0], tmp);
5407                                         return CMD_HELP;
5408                                 }
5409                                 param->fp_check_comp_end = 1;
5410                         } else {
5411                                 param->fp_verbose |= VERBOSE_COMP_END;
5412                                 param->fp_max_depth = 0;
5413                         }
5414                         break;
5415                 case 'F':
5416                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
5417                                 param->fp_verbose |= VERBOSE_DFID;
5418                                 param->fp_max_depth = 0;
5419                         }
5420                         break;
5421                 case 'g':
5422                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
5423                                 param->fp_verbose |= VERBOSE_GENERATION;
5424                                 param->fp_max_depth = 0;
5425                         }
5426                         break;
5427                 case 'i':
5428                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
5429                                 param->fp_verbose |= VERBOSE_STRIPE_OFFSET;
5430                                 param->fp_max_depth = 0;
5431                         }
5432                         break;
5433                 case 'I':
5434                         if (optarg) {
5435                                 param->fp_comp_id = strtoul(optarg, &end, 0);
5436                                 if (*end != '\0' || param->fp_comp_id == 0 ||
5437                                     param->fp_comp_id > LCME_ID_MAX) {
5438                                         fprintf(stderr,
5439                                                 "error: %s bad component id '%s'\n",
5440                                                 argv[0], optarg);
5441                                         return CMD_HELP;
5442                                 }
5443                                 param->fp_check_comp_id = 1;
5444                         } else {
5445                                 param->fp_max_depth = 0;
5446                                 param->fp_verbose |= VERBOSE_COMP_ID;
5447                         }
5448                         break;
5449                 case 'L':
5450                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
5451                                 param->fp_verbose |= VERBOSE_PATTERN;
5452                                 param->fp_max_depth = 0;
5453                         }
5454                         break;
5455 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5456                 case 'M':
5457                         fprintf(stderr,
5458                                 "warning: '-M' deprecated, use '--mdt-index' or '-m' instead\n");
5459 #endif
5460                 case 'm':
5461                         if (!(param->fp_verbose & VERBOSE_DETAIL))
5462                                 param->fp_max_depth = 0;
5463                         param->fp_verbose |= VERBOSE_MDTINDEX;
5464                         break;
5465                 case 'N':
5466                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
5467                                 param->fp_verbose |= VERBOSE_MIRROR_COUNT;
5468                                 param->fp_max_depth = 0;
5469                         }
5470                         break;
5471                 case 'O':
5472                         if (param->fp_obd_uuid) {
5473                                 fprintf(stderr,
5474                                         "error: %s: only one obduuid allowed",
5475                                         argv[0]);
5476                                 return CMD_HELP;
5477                         }
5478                         param->fp_obd_uuid = (struct obd_uuid *)optarg;
5479                         break;
5480                 case 'p':
5481                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
5482                                 param->fp_verbose |= VERBOSE_POOL;
5483                                 param->fp_max_depth = 0;
5484                         }
5485                         break;
5486                 case 'q':
5487                         param->fp_quiet++;
5488                         break;
5489                 case 'r':
5490                         param->fp_recursive = 1;
5491                         break;
5492                 case 'R':
5493                         param->fp_raw = 1;
5494                         break;
5495                 case 'S':
5496                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
5497                                 param->fp_verbose |= VERBOSE_STRIPE_SIZE;
5498                                 param->fp_max_depth = 0;
5499                         }
5500                         break;
5501                 case 'v':
5502                         param->fp_verbose = VERBOSE_DEFAULT | VERBOSE_DETAIL;
5503                         break;
5504                 case 'y':
5505                         param->fp_yaml = 1;
5506                         break;
5507                 case 'z':
5508                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
5509                                 param->fp_verbose |= VERBOSE_EXT_SIZE;
5510                                 param->fp_max_depth = 0;
5511                         }
5512                         break;
5513                 default:
5514                         return CMD_HELP;
5515                 }
5516         }
5517
5518         if (pathstart == -1) {
5519                 fprintf(stderr, "error: %s: no filename|pathname\n",
5520                                 argv[0]);
5521                 return CMD_HELP;
5522         } else if (pathend == -1) {
5523                 /* no options */
5524                 pathend = argc;
5525         }
5526
5527         if (pathend > argc)
5528                 return CMD_HELP;
5529
5530         if (param->fp_recursive)
5531                 param->fp_max_depth = -1;
5532         else if (param->fp_verbose & VERBOSE_DETAIL)
5533                 param->fp_max_depth = 1;
5534
5535         if (!param->fp_verbose)
5536                 param->fp_verbose = VERBOSE_DEFAULT;
5537         if (param->fp_quiet)
5538                 param->fp_verbose = VERBOSE_OBJID;
5539
5540         do {
5541                 rc = llapi_getstripe(argv[pathstart], param);
5542         } while (++pathstart < pathend && !rc);
5543
5544         if (rc)
5545                 fprintf(stderr, "error: %s failed for %s.\n",
5546                         argv[0], argv[optind - 1]);
5547         return rc;
5548 }
5549
5550 static int lfs_tgts(int argc, char **argv)
5551 {
5552         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
5553         struct find_param param;
5554         int index = 0, rc = 0;
5555
5556         if (argc > 2)
5557                 return CMD_HELP;
5558
5559         if (argc == 2 && !realpath(argv[1], path)) {
5560                 rc = -errno;
5561                 fprintf(stderr, "error: invalid path '%s': %s\n",
5562                         argv[1], strerror(-rc));
5563                 return rc;
5564         }
5565
5566         while (!llapi_search_mounts(path, index++, mntdir, NULL)) {
5567                 /* Check if we have a mount point */
5568                 if (mntdir[0] == '\0')
5569                         continue;
5570
5571                 memset(&param, 0, sizeof(param));
5572                 if (!strcmp(argv[0], "mdts"))
5573                         param.fp_get_lmv = 1;
5574
5575                 rc = llapi_ostlist(mntdir, &param);
5576                 if (rc) {
5577                         fprintf(stderr, "error: %s: failed on %s\n",
5578                                 argv[0], mntdir);
5579                 }
5580                 if (path[0] != '\0')
5581                         break;
5582                 memset(mntdir, 0, PATH_MAX);
5583         }
5584
5585         return rc;
5586 }
5587
5588 static int lfs_getstripe(int argc, char **argv)
5589 {
5590         struct find_param param = { 0 };
5591
5592         param.fp_max_depth = 1;
5593         return lfs_getstripe_internal(argc, argv, &param);
5594 }
5595
5596 /* functions */
5597 static int lfs_getdirstripe(int argc, char **argv)
5598 {
5599         struct find_param param = { 0 };
5600         struct option long_opts[] = {
5601         { .val = 'c',   .name = "mdt-count",    .has_arg = no_argument },
5602         { .val = 'D',   .name = "default",      .has_arg = no_argument },
5603         { .val = 'H',   .name = "mdt-hash",     .has_arg = no_argument },
5604         { .val = 'i',   .name = "mdt-index",    .has_arg = no_argument },
5605         { .val = 'm',   .name = "mdt-index",    .has_arg = no_argument },
5606         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
5607         { .val = 'r',   .name = "recursive",    .has_arg = no_argument },
5608         { .val = 'T',   .name = "mdt-count",    .has_arg = no_argument },
5609         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
5610         { .val = 'y',   .name = "yaml",         .has_arg = no_argument },
5611         { .name = NULL } };
5612         int c, rc;
5613
5614         param.fp_get_lmv = 1;
5615
5616         while ((c = getopt_long(argc, argv,
5617                                 "cDHimO:rtTvy", long_opts, NULL)) != -1) {
5618                 switch (c) {
5619                 case 'c':
5620                 case 'T':
5621                         param.fp_verbose |= VERBOSE_COUNT;
5622                         break;
5623                 case 'D':
5624                         param.fp_get_default_lmv = 1;
5625                         break;
5626                 case 'i':
5627                 case 'm':
5628                         param.fp_verbose |= VERBOSE_STRIPE_OFFSET;
5629                         break;
5630 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
5631                 case 't':
5632                         fprintf(stderr,
5633                                 "warning: '-t' deprecated, use '--mdt-hash' or '-H' instead\n");
5634 #endif
5635                 case 'H':
5636                         param.fp_verbose |= VERBOSE_HASH_TYPE;
5637                         break;
5638                 case 'O':
5639                         if (param.fp_obd_uuid) {
5640                                 fprintf(stderr,
5641                                         "error: %s: only one obduuid allowed",
5642                                         argv[0]);
5643                                 return CMD_HELP;
5644                         }
5645                         param.fp_obd_uuid = (struct obd_uuid *)optarg;
5646                         break;
5647                 case 'r':
5648                         param.fp_recursive = 1;
5649                         break;
5650                 case 'v':
5651                         param.fp_verbose |= VERBOSE_DETAIL;
5652                         break;
5653                 case 'y':
5654                         param.fp_yaml = 1;
5655                         break;
5656                 default:
5657                         fprintf(stderr, "%s %s: unrecognized option '%s'\n",
5658                                 progname, argv[0], argv[optind - 1]);
5659                         return CMD_HELP;
5660                 }
5661         }
5662
5663         if (optind >= argc)
5664                 return CMD_HELP;
5665
5666         if (param.fp_recursive)
5667                 param.fp_max_depth = -1;
5668
5669         if (!param.fp_verbose)
5670                 param.fp_verbose = VERBOSE_DEFAULT;
5671
5672         do {
5673                 rc = llapi_getstripe(argv[optind], &param);
5674         } while (++optind < argc && !rc);
5675
5676         if (rc)
5677                 fprintf(stderr, "error: %s failed for %s.\n",
5678                         argv[0], argv[optind - 1]);
5679         return rc;
5680 }
5681
5682 enum mntdf_flags {
5683         MNTDF_INODES    = 0x0001,
5684         MNTDF_COOKED    = 0x0002,
5685         MNTDF_LAZY      = 0x0004,
5686         MNTDF_VERBOSE   = 0x0008,
5687         MNTDF_SHOW      = 0x0010,
5688 };
5689
5690 #define COOK(value)                                             \
5691 ({                                                              \
5692         int radix = 0;                                          \
5693         while (value > 1024) {                                  \
5694                 value /= 1024;                                  \
5695                 radix++;                                        \
5696         }                                                       \
5697         radix;                                                  \
5698 })
5699 #define UUF     "%-20s"
5700 #define CSF     "%11s"
5701 #define CDF     "%11llu"
5702 #define HDF     "%8.1f%c"
5703 #define RSF     "%4s"
5704 #define RDF     "%3d%%"
5705
5706 static inline int obd_statfs_ratio(const struct obd_statfs *st, bool inodes)
5707 {
5708         double avail, used, ratio = 0;
5709
5710         if (inodes) {
5711                 avail = st->os_ffree;
5712                 used = st->os_files - st->os_ffree;
5713         } else {
5714                 avail = st->os_bavail;
5715                 used = st->os_blocks - st->os_bfree;
5716         }
5717         if (avail + used > 0)
5718                 ratio = used / (used + avail) * 100;
5719
5720         /* Round up to match df(1) usage percentage */
5721         return (ratio - (int)ratio) > 0 ? (int)(ratio + 1) : (int)ratio;
5722 }
5723
5724 /*
5725  * This is to identify various problem states for "lfs df" if .osn_err = true,
5726  * so only show flags reflecting those states by default. Informational states
5727  * are only shown with "-v" and use lower-case names to distinguish them.
5728  * UNUSED[12] were for "EROFS = 30" until 1.6 but are now available for use.
5729  */
5730 static struct obd_statfs_state_names {
5731         enum obd_statfs_state   osn_state;
5732         const char              osn_name;
5733         bool                    osn_err;
5734 } oss_names[] = {
5735         { .osn_state = OS_STATFS_DEGRADED,   .osn_name = 'D', .osn_err = true },
5736         { .osn_state = OS_STATFS_READONLY,   .osn_name = 'R', .osn_err = true },
5737         { .osn_state = OS_STATFS_NOPRECREATE,.osn_name = 'N', .osn_err = true },
5738         { .osn_state = OS_STATFS_UNUSED1,    .osn_name = '?', .osn_err = true },
5739         { .osn_state = OS_STATFS_UNUSED2,    .osn_name = '?', .osn_err = true },
5740         { .osn_state = OS_STATFS_ENOSPC,     .osn_name = 'S', .osn_err = true },
5741         { .osn_state = OS_STATFS_ENOINO,     .osn_name = 'I', .osn_err = true },
5742         { .osn_state = OS_STATFS_SUM,        .osn_name = 'a', /* aggregate */ },
5743         { .osn_state = OS_STATFS_NONROT,     .osn_name = 'f', /* flash */     },
5744 };
5745
5746 static int showdf(char *mntdir, struct obd_statfs *stat,
5747                   char *uuid, enum mntdf_flags flags,
5748                   char *type, int index, int rc)
5749 {
5750         long long avail, used, total;
5751         int ratio = 0;
5752         char *suffix = "KMGTPEZY";
5753         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
5754         char tbuf[3 * sizeof(__u64)];
5755         char ubuf[3 * sizeof(__u64)];
5756         char abuf[3 * sizeof(__u64)];
5757         char rbuf[3 * sizeof(__u64)];
5758
5759         if (!uuid || !stat)
5760                 return -EINVAL;
5761
5762         switch (rc) {
5763         case 0:
5764                 if (flags & MNTDF_INODES) {
5765                         avail = stat->os_ffree;
5766                         used = stat->os_files - stat->os_ffree;
5767                         total = stat->os_files;
5768                 } else {
5769                         int shift = flags & MNTDF_COOKED ? 0 : 10;
5770
5771                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
5772                         used  = ((stat->os_blocks - stat->os_bfree) *
5773                                  stat->os_bsize) >> shift;
5774                         total = (stat->os_blocks * stat->os_bsize) >> shift;
5775                 }
5776
5777                 ratio = obd_statfs_ratio(stat, flags & MNTDF_INODES);
5778
5779                 if (flags & MNTDF_COOKED) {
5780                         int i;
5781                         double cook_val;
5782
5783                         cook_val = (double)total;
5784                         i = COOK(cook_val);
5785                         if (i > 0)
5786                                 snprintf(tbuf, sizeof(tbuf), HDF, cook_val,
5787                                          suffix[i - 1]);
5788                         else
5789                                 snprintf(tbuf, sizeof(tbuf), CDF, total);
5790
5791                         cook_val = (double)used;
5792                         i = COOK(cook_val);
5793                         if (i > 0)
5794                                 snprintf(ubuf, sizeof(ubuf), HDF, cook_val,
5795                                          suffix[i - 1]);
5796                         else
5797                                 snprintf(ubuf, sizeof(ubuf), CDF, used);
5798
5799                         cook_val = (double)avail;
5800                         i = COOK(cook_val);
5801                         if (i > 0)
5802                                 snprintf(abuf, sizeof(abuf), HDF, cook_val,
5803                                          suffix[i - 1]);
5804                         else
5805                                 snprintf(abuf, sizeof(abuf), CDF, avail);
5806                 } else {
5807                         snprintf(tbuf, sizeof(tbuf), CDF, total);
5808                         snprintf(ubuf, sizeof(tbuf), CDF, used);
5809                         snprintf(abuf, sizeof(tbuf), CDF, avail);
5810                 }
5811
5812                 sprintf(rbuf, RDF, ratio);
5813                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
5814                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
5815                 if (type)
5816                         printf("[%s:%d]", type, index);
5817
5818                 if (stat->os_state) {
5819                         uint32_t i;
5820
5821                         printf(" ");
5822                         for (i = 0; i < ARRAY_SIZE(oss_names); i++) {
5823                                 if (oss_names[i].osn_state & stat->os_state &&
5824                                     (oss_names[i].osn_err ||
5825                                      flags & MNTDF_VERBOSE))
5826                                         printf("%c", oss_names[i].osn_name);
5827                         }
5828                 }
5829
5830                 printf("\n");
5831                 break;
5832         case -ENODATA:
5833                 printf(UUF": inactive device\n", uuid);
5834                 break;
5835         default:
5836                 printf(UUF": %s\n", uuid, strerror(-rc));
5837                 break;
5838         }
5839
5840         return 0;
5841 }
5842
5843 struct ll_stat_type {
5844         int   st_op;
5845         char *st_name;
5846 };
5847
5848 #define LL_STATFS_MAX   LOV_MAX_STRIPE_COUNT
5849
5850 struct ll_statfs_data {
5851         int                     sd_index;
5852         struct obd_statfs       sd_st;
5853 };
5854
5855 struct ll_statfs_buf {
5856         int                     sb_count;
5857         struct ll_statfs_data   sb_buf[LL_STATFS_MAX];
5858 };
5859
5860 static int mntdf(char *mntdir, char *fsname, char *pool, enum mntdf_flags flags,
5861                  int ops, struct ll_statfs_buf *lsb)
5862 {
5863         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
5864         struct obd_uuid uuid_buf;
5865         char *poolname = NULL;
5866         struct ll_stat_type types[] = {
5867                 { .st_op = LL_STATFS_LMV,       .st_name = "MDT" },
5868                 { .st_op = LL_STATFS_LOV,       .st_name = "OST" },
5869                 { .st_name = NULL } };
5870         struct ll_stat_type *tp;
5871         __u64 ost_files = 0;
5872         __u64 ost_ffree = 0;
5873         __u32 index;
5874         __u32 type;
5875         int fd;
5876         int rc = 0;
5877         int rc2;
5878
5879         if (pool) {
5880                 poolname = strchr(pool, '.');
5881                 if (poolname) {
5882                         if (strncmp(fsname, pool, strlen(fsname))) {
5883                                 fprintf(stderr, "filesystem name incorrect\n");
5884                                 return -ENODEV;
5885                         }
5886                         poolname++;
5887                 } else
5888                         poolname = pool;
5889         }
5890
5891         fd = open(mntdir, O_RDONLY);
5892         if (fd < 0) {
5893                 rc = -errno;
5894                 fprintf(stderr, "%s: cannot open '%s': %s\n", progname, mntdir,
5895                         strerror(errno));
5896                 return rc;
5897         }
5898
5899         if (flags & MNTDF_SHOW) {
5900                 if (flags & MNTDF_INODES)
5901                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
5902                                "UUID", "Inodes", "IUsed", "IFree",
5903                                "IUse%", "Mounted on");
5904                 else
5905                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
5906                                "UUID",
5907                                flags & MNTDF_COOKED ? "bytes" : "1K-blocks",
5908                                "Used", "Available", "Use%", "Mounted on");
5909         }
5910
5911         for (tp = types; tp->st_name != NULL; tp++) {
5912                 bool have_ost = false;
5913
5914                 if (!(tp->st_op & ops))
5915                         continue;
5916
5917                 for (index = 0; ; index++) {
5918                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
5919                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
5920                         type = flags & MNTDF_LAZY ?
5921                                 tp->st_op | LL_STATFS_NODELAY : tp->st_op;
5922                         rc2 = llapi_obd_fstatfs(fd, type, index,
5923                                                &stat_buf, &uuid_buf);
5924                         if (rc2 == -ENODEV)
5925                                 break;
5926                         if (rc2 == -EAGAIN)
5927                                 continue;
5928                         if (rc2 == -ENODATA) { /* Inactive device, OK. */
5929                                 if (!(flags & MNTDF_VERBOSE))
5930                                         continue;
5931                         } else if (rc2 < 0 && rc == 0) {
5932                                 rc = rc2;
5933                         }
5934
5935                         /*
5936                          * If we have OSTs then don't report MDT block counts.
5937                          * For MDT-only filesystems the expectation is that all
5938                          * layouts have a DoM component.  For filesystems with
5939                          * OSTs, files are not necessarily going to store data
5940                          * on MDTs, and MDT space is limited to a fraction of
5941                          * OST space, so don't include it in the summary.
5942                          */
5943                         if (tp->st_op == LL_STATFS_LOV && !have_ost) {
5944                                 have_ost = true;
5945                                 sum.os_blocks = 0;
5946                                 sum.os_bfree = 0;
5947                                 sum.os_bavail = 0;
5948                         }
5949
5950                         if (poolname && tp->st_op == LL_STATFS_LOV &&
5951                             llapi_search_ost(fsname, poolname,
5952                                              obd_uuid2str(&uuid_buf)) != 1)
5953                                 continue;
5954
5955                         /*
5956                          * the llapi_obd_fstatfs() call may have returned with
5957                          * an error, but if it filled in uuid_buf we will at
5958                          * lease use that to print out a message for that OBD.
5959                          * If we didn't get anything in the uuid_buf, then fill
5960                          * it in so that we can print an error message.
5961                          */
5962                         if (uuid_buf.uuid[0] == '\0')
5963                                 snprintf(uuid_buf.uuid, sizeof(uuid_buf.uuid),
5964                                          "%s%04x", tp->st_name, index);
5965                         if (!rc && lsb) {
5966                                 lsb->sb_buf[lsb->sb_count].sd_index = index;
5967                                 lsb->sb_buf[lsb->sb_count].sd_st = stat_buf;
5968                                 lsb->sb_count++;
5969                         }
5970                         if (flags & MNTDF_SHOW)
5971                                 showdf(mntdir, &stat_buf,
5972                                        obd_uuid2str(&uuid_buf), flags,
5973                                        tp->st_name, index, rc2);
5974
5975                         if (rc2)
5976                                 continue;
5977
5978                         if (tp->st_op == LL_STATFS_LMV) {
5979                                 sum.os_ffree += stat_buf.os_ffree;
5980                                 sum.os_files += stat_buf.os_files;
5981                         } else /* if (tp->st_op == LL_STATFS_LOV) */ {
5982                                 ost_files += stat_buf.os_files;
5983                                 ost_ffree += stat_buf.os_ffree;
5984                         }
5985                         sum.os_blocks += stat_buf.os_blocks *
5986                                          stat_buf.os_bsize;
5987                         sum.os_bfree  += stat_buf.os_bfree *
5988                                          stat_buf.os_bsize;
5989                         sum.os_bavail += stat_buf.os_bavail *
5990                                          stat_buf.os_bsize;
5991                 }
5992         }
5993
5994         close(fd);
5995
5996         /*
5997          * If we have _some_ OSTs, but don't have as many free objects on the
5998          * OST as inodes on the MDTs, reduce the reported number of inodes
5999          * to compensate, so that the "inodes in use" number is correct.
6000          * This should be kept in sync with ll_statfs_internal().
6001          */
6002         if (ost_files && ost_ffree < sum.os_ffree) {
6003                 sum.os_files = (sum.os_files - sum.os_ffree) + ost_ffree;
6004                 sum.os_ffree = ost_ffree;
6005         }
6006         if (flags & MNTDF_SHOW) {
6007                 printf("\n");
6008                 showdf(mntdir, &sum, "filesystem_summary:", flags, NULL, 0, 0);
6009                 printf("\n");
6010         }
6011
6012         return rc;
6013 }
6014
6015 /* functions */
6016 static int lfs_setdirstripe(int argc, char **argv)
6017 {
6018         char *dname;
6019         struct lfs_setstripe_args lsa = { 0 };
6020         struct llapi_stripe_param *param = NULL;
6021         __u32 mdts[LMV_MAX_STRIPE_COUNT] = { 0 };
6022         char *end;
6023         int c;
6024         char *mode_opt = NULL;
6025         bool default_stripe = false;
6026         bool delete = false;
6027         bool foreign_mode = false;
6028         mode_t mode = S_IRWXU | S_IRWXG | S_IRWXO;
6029         mode_t previous_mode = 0;
6030         char *xattr = NULL;
6031         __u32 type = LU_FOREIGN_TYPE_DAOS, flags = 0;
6032         struct option long_opts[] = {
6033         { .val = 'c',   .name = "count",        .has_arg = required_argument },
6034         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument },
6035         { .val = 'd',   .name = "delete",       .has_arg = no_argument },
6036         { .val = 'D',   .name = "default",      .has_arg = no_argument },
6037         { .val = 'D',   .name = "default_stripe", .has_arg = no_argument },
6038         { .val = LFS_LAYOUT_FLAGS_OPT,
6039                         .name = "flags",        .has_arg = required_argument },
6040         { .val = LFS_LAYOUT_FOREIGN_OPT,
6041                         .name = "foreign",      .has_arg = optional_argument},
6042         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
6043 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 17, 53, 0)
6044         { .val = 'i',   .name = "mdt-index",    .has_arg = required_argument },
6045         { .val = 'i',   .name = "mdt",          .has_arg = required_argument },
6046 #else
6047 /* find { .val = 'l',   .name = "lazy",         .has_arg = no_argument }, */
6048         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
6049         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
6050 #endif
6051 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6052         { .val = 'i',   .name = "index",        .has_arg = required_argument },
6053 #endif
6054         { .val = 'o',   .name = "mode",         .has_arg = required_argument },
6055 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6056         { .val = 't',   .name = "hash-type",    .has_arg = required_argument },
6057 #endif
6058         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
6059 /* setstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
6060         { .val = 'x',   .name = "xattr",        .has_arg = required_argument },
6061         { .name = NULL } };
6062         int result = 0;
6063
6064         setstripe_args_init(&lsa);
6065
6066         while ((c = getopt_long(argc, argv, "c:dDi:H:m:o:t:T:x:",
6067                                 long_opts, NULL)) >= 0) {
6068                 switch (c) {
6069                 case 0:
6070                         /* Long options. */
6071                         break;
6072                 case 'c':
6073                 case 'T':
6074                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
6075                         if (*end != '\0') {
6076                                 fprintf(stderr,
6077                                         "%s %s: invalid stripe count '%s'\n",
6078                                         progname, argv[0], optarg);
6079                                 return CMD_HELP;
6080                         }
6081                         break;
6082                 case 'd':
6083                         delete = true;
6084                         default_stripe = true;
6085                         break;
6086                 case 'D':
6087                         default_stripe = true;
6088                         break;
6089                 case LFS_LAYOUT_FOREIGN_OPT:
6090                         if (optarg) {
6091                                 /* check pure numeric */
6092                                 type = strtoul(optarg, &end, 0);
6093                                 if (*end) {
6094                                         /* check name */
6095                                         type = check_foreign_type_name(optarg);
6096                                         if (type == LU_FOREIGN_TYPE_UNKNOWN) {
6097                                                 fprintf(stderr,
6098                                                         "%s %s: unknown foreign type '%s'\n",
6099                                                         progname, argv[0],
6100                                                         optarg);
6101                                                 return CMD_HELP;
6102                                         }
6103                                 }
6104                         }
6105                         foreign_mode = true;
6106                         break;
6107                 case LFS_LAYOUT_FLAGS_OPT:
6108                         flags = strtoul(optarg, &end, 16);
6109                         if (*end != '\0') {
6110                                 fprintf(stderr,
6111                                         "%s %s: bad flags '%s'\n",
6112                                         progname, argv[0], optarg);
6113                                 return CMD_HELP;
6114                         }
6115                         break;
6116 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6117                 case 't':
6118                         fprintf(stderr,
6119                                 "warning: '--hash-type' and '-t' deprecated, use '--mdt-hash' or '-H' instead\n");
6120 #endif
6121                 case 'H':
6122                         lsa.lsa_pattern = check_hashtype(optarg);
6123                         if (lsa.lsa_pattern == 0) {
6124                                 fprintf(stderr,
6125                                         "%s %s: bad stripe hash type '%s'\n",
6126                                         progname, argv[0], optarg);
6127                                 return CMD_HELP;
6128                         }
6129                         break;
6130                 case 'i':
6131 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 17, 53, 0)
6132                 case 'm':
6133 #endif
6134 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6135                         if (strcmp(argv[optind - 1], "--index") == 0)
6136                                 fprintf(stderr,
6137                                         "%s %s: warning: '--index' deprecated, use '--mdt-index' instead\n",
6138                                         progname, argv[0]);
6139 #endif
6140                         lsa.lsa_nr_tgts = parse_targets(mdts,
6141                                                 sizeof(mdts) / sizeof(__u32),
6142                                                 lsa.lsa_nr_tgts, optarg, NULL);
6143                         if (lsa.lsa_nr_tgts < 0) {
6144                                 fprintf(stderr,
6145                                         "%s %s: invalid MDT target(s) '%s'\n",
6146                                         progname, argv[0], optarg);
6147                                 return CMD_HELP;
6148                         }
6149
6150                         lsa.lsa_tgts = mdts;
6151                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
6152                                 lsa.lsa_stripe_off = mdts[0];
6153                         break;
6154 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 15, 53, 0)
6155                 case 'm':
6156                         fprintf(stderr,
6157                                 "warning: '-m' is deprecated, use '--mode' or '-o' instead\n");
6158 #endif
6159                 case 'o':
6160                         mode_opt = optarg;
6161                         break;
6162                 case 'x':
6163                         xattr = optarg;
6164                         break;
6165                 default:
6166                         fprintf(stderr, "%s %s: unrecognized option '%s'\n",
6167                                 progname, argv[0], argv[optind - 1]);
6168                         return CMD_HELP;
6169                 }
6170         }
6171
6172         if (optind == argc) {
6173                 fprintf(stderr, "%s %s: DIR must be specified\n",
6174                         progname, argv[0]);
6175                 return CMD_HELP;
6176         }
6177
6178         if (xattr && !foreign_mode) {
6179                 /*
6180                  * only print a warning as this is armless and will be
6181                  * ignored
6182                  */
6183                 fprintf(stderr,
6184                         "%s %s: xattr has been specified for non-foreign layout\n",
6185                         progname, argv[0]);
6186         } else if (foreign_mode && !xattr) {
6187                 fprintf(stderr,
6188                         "%s %s: xattr must be provided in foreign mode\n",
6189                         progname, argv[0]);
6190                 return CMD_HELP;
6191         }
6192
6193         if (foreign_mode && (delete || default_stripe || lsa.lsa_nr_tgts ||
6194             lsa.lsa_tgts || setstripe_args_specified(&lsa))) {
6195                 fprintf(stderr,
6196                         "%s %s: only --xattr/--flags/--mode options are valid with --foreign\n",
6197                         progname, argv[0]);
6198                 return CMD_HELP;
6199         }
6200
6201         if (!delete && lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT &&
6202             lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT && !foreign_mode) {
6203                 fprintf(stderr,
6204                         "%s %s: stripe offset and count must be specified\n",
6205                         progname, argv[0]);
6206                 return CMD_HELP;
6207         }
6208
6209         if (delete &&
6210             (lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
6211              lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)) {
6212                 fprintf(stderr,
6213                         "%s %s: cannot specify -d with -c or -i options\n",
6214                         progname, argv[0]);
6215                 return CMD_HELP;
6216         }
6217
6218         if (mode_opt) {
6219                 mode = strtoul(mode_opt, &end, 8);
6220                 if (*end != '\0') {
6221                         fprintf(stderr,
6222                                 "%s %s: bad MODE '%s'\n",
6223                                 progname, argv[0], mode_opt);
6224                         return CMD_HELP;
6225                 }
6226                 previous_mode = umask(0);
6227         }
6228
6229         /* foreign LMV/dir case */
6230         if (foreign_mode) {
6231                 if (argc > optind + 1) {
6232                         fprintf(stderr,
6233                                 "%s %s: cannot specify multiple foreign dirs\n",
6234                                 progname, argv[0]);
6235                         return CMD_HELP;
6236                 }
6237
6238                 dname = argv[optind];
6239                 result = llapi_dir_create_foreign(dname, mode, type, flags,
6240                                                   xattr);
6241                 if (result != 0)
6242                         fprintf(stderr,
6243                                 "%s mkdir: can't create foreign dir '%s': %s\n",
6244                                 progname, dname, strerror(-result));
6245                 return result;
6246         }
6247
6248         /*
6249          * initialize stripe parameters, in case param is converted to specific,
6250          * i.e, 'lfs mkdir -i -1 -c N', always allocate space for lsp_tgts.
6251          */
6252         param = calloc(1, offsetof(typeof(*param),
6253                        lsp_tgts[lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ?
6254                                 lsa.lsa_stripe_count : lsa.lsa_nr_tgts]));
6255         if (!param) {
6256                 fprintf(stderr,
6257                         "%s %s: cannot allocate memory for parameters: %s\n",
6258                         progname, argv[0], strerror(ENOMEM));
6259                 return CMD_HELP;
6260         }
6261
6262         /* if "lfs setdirstripe -D -i -1" is used, assume 1-stripe directory */
6263         if (default_stripe && lsa.lsa_stripe_off == -1 &&
6264             (lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT ||
6265              lsa.lsa_stripe_count == 0))
6266                 lsa.lsa_stripe_count = 1;
6267         if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
6268                 param->lsp_stripe_count = lsa.lsa_stripe_count;
6269         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
6270                 param->lsp_stripe_offset = -1;
6271         else
6272                 param->lsp_stripe_offset = lsa.lsa_stripe_off;
6273         if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
6274                 param->lsp_stripe_pattern = lsa.lsa_pattern;
6275         else
6276                 param->lsp_stripe_pattern = LMV_HASH_TYPE_UNKNOWN;
6277         param->lsp_pool = lsa.lsa_pool_name;
6278         param->lsp_is_specific = false;
6279         if (lsa.lsa_nr_tgts > 1) {
6280                 if (lsa.lsa_stripe_count > 0 &&
6281                     lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
6282                     lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
6283                         fprintf(stderr,
6284                                 "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
6285                                 argv[0], lsa.lsa_stripe_count,
6286                                 lsa.lsa_nr_tgts);
6287                         free(param);
6288                         return CMD_HELP;
6289                 }
6290
6291                 param->lsp_is_specific = true;
6292                 param->lsp_stripe_count = lsa.lsa_nr_tgts;
6293                 memcpy(param->lsp_tgts, mdts, sizeof(*mdts) * lsa.lsa_nr_tgts);
6294         }
6295
6296         dname = argv[optind];
6297         do {
6298                 if (default_stripe) {
6299                         result = llapi_dir_set_default_lmv(dname, param);
6300                         if (result)
6301                                 fprintf(stderr,
6302                                         "%s setdirstripe: cannot set default stripe on dir '%s': %s\n",
6303                                         progname, dname, strerror(-result));
6304                         continue;
6305                 }
6306
6307                 result = llapi_dir_create(dname, mode, param);
6308                 if (result)
6309                         fprintf(stderr,
6310                                 "%s setdirstripe: cannot create dir '%s': %s\n",
6311                                 progname, dname, strerror(-result));
6312         } while (!result && (dname = argv[++optind]));
6313
6314         if (mode_opt)
6315                 umask(previous_mode);
6316
6317         free(param);
6318         return result;
6319 }
6320
6321 /* functions */
6322 static int lfs_rmentry(int argc, char **argv)
6323 {
6324         char *dname;
6325         int   index;
6326         int   result = 0;
6327
6328         if (argc <= 1) {
6329                 fprintf(stderr, "error: %s: missing dirname\n",
6330                         argv[0]);
6331                 return CMD_HELP;
6332         }
6333
6334         index = 1;
6335         dname = argv[index];
6336         while (dname) {
6337                 result = llapi_direntry_remove(dname);
6338                 if (result) {
6339                         fprintf(stderr,
6340                                 "error: %s: remove dir entry '%s' failed\n",
6341                                 argv[0], dname);
6342                         break;
6343                 }
6344                 dname = argv[++index];
6345         }
6346         return result;
6347 }
6348
6349 static int lfs_mv(int argc, char **argv)
6350 {
6351         struct lmv_user_md lmu = { LMV_USER_MAGIC };
6352         struct find_param param = {
6353                 .fp_max_depth = -1,
6354                 .fp_mdt_index = -1,
6355         };
6356         char *end;
6357         int c;
6358         int rc = 0;
6359         struct option long_opts[] = {
6360         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
6361         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
6362         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
6363         { .name = NULL } };
6364
6365         while ((c = getopt_long(argc, argv, "m:M:v", long_opts, NULL)) != -1) {
6366                 switch (c) {
6367 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6368                 case 'M':
6369                         fprintf(stderr,
6370                                 "warning: '-M' deprecated, use '--mdt-index' or '-m' instead\n");
6371 #endif
6372                 case 'm':
6373                         lmu.lum_stripe_offset = strtoul(optarg, &end, 0);
6374                         if (*end != '\0') {
6375                                 fprintf(stderr, "%s mv: bad MDT index '%s'\n",
6376                                         progname, optarg);
6377                                 return CMD_HELP;
6378                         }
6379                         break;
6380                 case 'v':
6381                         param.fp_verbose = VERBOSE_DETAIL;
6382                         break;
6383                 default:
6384                         fprintf(stderr, "%s mv: unrecognized option '%s'\n",
6385                                 progname, argv[optind - 1]);
6386                         return CMD_HELP;
6387                 }
6388         }
6389
6390         if (lmu.lum_stripe_offset == LMV_OFFSET_DEFAULT) {
6391                 fprintf(stderr, "%s mv: MDT index must be specified\n",
6392                         progname);
6393                 return CMD_HELP;
6394         }
6395
6396         if (optind >= argc) {
6397                 fprintf(stderr, "%s mv: DIR must be specified\n", progname);
6398                 return CMD_HELP;
6399         }
6400
6401         lmu.lum_hash_type = LMV_HASH_TYPE_UNKNOWN;
6402
6403         /* initialize migrate mdt parameters */
6404         param.fp_lmv_md = &lmu;
6405         param.fp_migrate = 1;
6406         rc = llapi_migrate_mdt(argv[optind], &param);
6407         if (rc != 0)
6408                 fprintf(stderr, "%s mv: cannot migrate '%s' to MDT%04x: %s\n",
6409                         progname, argv[optind], lmu.lum_stripe_offset,
6410                         strerror(-rc));
6411         return rc;
6412 }
6413
6414 static int lfs_osts(int argc, char **argv)
6415 {
6416         return lfs_tgts(argc, argv);
6417 }
6418
6419 static int lfs_mdts(int argc, char **argv)
6420 {
6421         return lfs_tgts(argc, argv);
6422 }
6423
6424 static int lfs_df(int argc, char **argv)
6425 {
6426         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
6427         enum mntdf_flags flags = MNTDF_SHOW;
6428         int ops = LL_STATFS_LMV | LL_STATFS_LOV;
6429         int c, rc = 0, index = 0;
6430         char fsname[PATH_MAX] = "", *pool_name = NULL;
6431         struct option long_opts[] = {
6432         { .val = 'h',   .name = "human-readable",
6433                                                 .has_arg = no_argument },
6434         { .val = 'i',   .name = "inodes",       .has_arg = no_argument },
6435         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
6436         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
6437         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
6438         { .name = NULL} };
6439
6440         while ((c = getopt_long(argc, argv, "hilp:v", long_opts, NULL)) != -1) {
6441                 switch (c) {
6442                 case 'h':
6443                         flags |= MNTDF_COOKED;
6444                         break;
6445                 case 'i':
6446                         flags |= MNTDF_INODES;
6447                         break;
6448                 case 'l':
6449                         flags |= MNTDF_LAZY;
6450                         break;
6451                 case 'p':
6452                         pool_name = optarg;
6453                         break;
6454                 case 'v':
6455                         flags |= MNTDF_VERBOSE;
6456                         break;
6457                 default:
6458                         return CMD_HELP;
6459                 }
6460         }
6461         if (optind < argc && !realpath(argv[optind], path)) {
6462                 rc = -errno;
6463                 fprintf(stderr, "error: invalid path '%s': %s\n",
6464                         argv[optind], strerror(-rc));
6465                 return rc;
6466         }
6467
6468         while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
6469                 /* Check if we have a mount point */
6470                 if (mntdir[0] == '\0')
6471                         continue;
6472
6473                 rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
6474                 if (rc || path[0] != '\0')
6475                         break;
6476                 fsname[0] = '\0'; /* avoid matching in next loop */
6477                 mntdir[0] = '\0'; /* avoid matching in next loop */
6478         }
6479
6480         return rc;
6481 }
6482
6483 static int print_instance(const char *mntdir, char *buf, size_t buflen,
6484                           bool opt_instance, bool opt_fsname, bool opt_mntdir)
6485 {
6486         int rc = 0;
6487
6488         if (opt_fsname == opt_instance) { /* both true or both false */
6489                 rc = llapi_getname(mntdir, buf, buflen);
6490         } else if (opt_fsname) {
6491                 /*
6492                  * llapi_search_mounts() fills @buf with fsname, but that is not
6493                  * called if explicit paths are specified on the command-line
6494                  */
6495                 if (buf[0] == '\0')
6496                         rc = llapi_get_fsname(mntdir, buf, buflen);
6497         } else /* if (opt_instance) */ {
6498                 rc = llapi_get_instance(mntdir, buf, buflen);
6499         }
6500
6501         if (rc < 0) {
6502                 fprintf(stderr, "cannot get instance for '%s': %s\n",
6503                         mntdir, strerror(-rc));
6504                 return rc;
6505         }
6506
6507         if (opt_mntdir)
6508                 printf("%s %s\n", buf, mntdir);
6509         else
6510                 printf("%s\n", buf);
6511
6512         return 0;
6513 }
6514
6515 static int lfs_getname(int argc, char **argv)
6516 {
6517         struct option long_opts[] = {
6518         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6519         { .val = 'i',   .name = "instance",     .has_arg = no_argument },
6520         { .val = 'n',   .name = "fsname",       .has_arg = no_argument },
6521         { .name = NULL} };
6522         bool opt_instance = false, opt_fsname = false;
6523         char fsname[PATH_MAX] = "";
6524         int rc = 0, rc2, c;
6525
6526         while ((c = getopt_long(argc, argv, "hin", long_opts, NULL)) != -1) {
6527                 switch (c) {
6528                 case 'i':
6529                         opt_instance = true;
6530                         break;
6531                 case 'n':
6532                         opt_fsname = true;
6533                         break;
6534                 case 'h':
6535                 default:
6536                         return CMD_HELP;
6537                 }
6538         }
6539
6540         if (optind == argc) { /* no paths specified, get all paths. */
6541                 char mntdir[PATH_MAX] = "", path[PATH_MAX] = "";
6542                 int index = 0;
6543
6544                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
6545                         rc2 = print_instance(mntdir, fsname, sizeof(fsname),
6546                                              opt_instance, opt_fsname, true);
6547                         if (!rc)
6548                                 rc = rc2;
6549                         path[0] = fsname[0] = mntdir[0] = '\0';
6550                 }
6551         } else { /* paths specified, only attempt to search these. */
6552                 bool opt_mntdir;
6553
6554                 /* if only one path is given, print only requested info */
6555                 opt_mntdir = argc - optind > 1 || (opt_instance == opt_fsname);
6556
6557                 for (; optind < argc; optind++) {
6558                         rc2 = print_instance(argv[optind], fsname,
6559                                              sizeof(fsname), opt_instance,
6560                                              opt_fsname, opt_mntdir);
6561                         if (!rc)
6562                                 rc = rc2;
6563                         fsname[0] = '\0';
6564                 }
6565         }
6566
6567         return rc;
6568 }
6569
6570 static int lfs_check(int argc, char **argv)
6571 {
6572         char mntdir[PATH_MAX] = {'\0'};
6573         int num_types = 1;
6574         char *obd_types[3];
6575         char obd_type1[4];
6576         char obd_type2[4];
6577         char obd_type3[4];
6578         int rc;
6579
6580         if (argc != 2) {
6581                 fprintf(stderr, "%s check: server type must be specified\n",
6582                         progname);
6583                 return CMD_HELP;
6584         }
6585
6586         obd_types[0] = obd_type1;
6587         obd_types[1] = obd_type2;
6588         obd_types[2] = obd_type3;
6589
6590         if (strcmp(argv[1], "osts") == 0) {
6591                 strcpy(obd_types[0], "osc");
6592         } else if (strcmp(argv[1], "mdts") == 0 ||
6593                    strcmp(argv[1], "mds") == 0) {
6594                 strcpy(obd_types[0], "mdc");
6595         } else if (strcmp(argv[1], "mgts") == 0) {
6596                 strcpy(obd_types[0], "mgc");
6597         } else if (strcmp(argv[1], "all") == 0 ||
6598                    strcmp(argv[1], "servers") == 0) {
6599                 num_types = 3;
6600                 strcpy(obd_types[0], "osc");
6601                 strcpy(obd_types[1], "mdc");
6602                 strcpy(obd_types[2], "mgc");
6603         } else {
6604                 fprintf(stderr, "%s check: unrecognized option '%s'\n",
6605                         progname, argv[1]);
6606                 return CMD_HELP;
6607         }
6608
6609         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
6610         if (rc < 0 || mntdir[0] == '\0') {
6611                 fprintf(stderr,
6612                         "%s check: cannot find mounted Lustre filesystem: %s\n",
6613                         progname, (rc < 0) ? strerror(-rc) : strerror(ENODEV));
6614                 return rc;
6615         }
6616
6617         rc = llapi_target_check(num_types, obd_types, mntdir);
6618         if (rc)
6619                 fprintf(stderr, "%s check: cannot check target '%s': %s\n",
6620                         progname, argv[1], strerror(-rc));
6621
6622         return rc;
6623 }
6624
6625 #ifdef HAVE_SYS_QUOTA_H
6626 #define ADD_OVERFLOW(a, b) \
6627                      ((((a) + (b)) < (a)) ? \
6628                       ((a) = ULONG_MAX) : ((a) = (a) + (b)))
6629
6630 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
6631  * returns the value or ULONG_MAX on integer overflow or incorrect format
6632  * Notes:
6633  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
6634  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
6635  *        3. empty integer value is interpreted as 0
6636  */
6637 static unsigned long str2sec(const char *timestr)
6638 {
6639         const char spec[] = "smhdw";
6640         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
6641         unsigned long val = 0;
6642         char *tail;
6643
6644         if (strpbrk(timestr, spec) == NULL) {
6645                 /*
6646                  * no specifiers inside the time string,
6647                  * should treat it as an integer value
6648                  */
6649                 val = strtoul(timestr, &tail, 10);
6650                 return *tail ? ULONG_MAX : val;
6651         }
6652
6653         /* format string is XXwXXdXXhXXmXXs */
6654         while (*timestr) {
6655                 unsigned long v;
6656                 int ind;
6657                 char *ptr;
6658
6659                 v = strtoul(timestr, &tail, 10);
6660                 if (v == ULONG_MAX || *tail == '\0')
6661                         /*
6662                          * value too large (ULONG_MAX or more)
6663                          * or missing specifier
6664                          */
6665                         goto error;
6666
6667                 ptr = strchr(spec, *tail);
6668                 if (!ptr)
6669                         /* unknown specifier */
6670                         goto error;
6671
6672                 ind = ptr - spec;
6673
6674                 /* check if product will overflow the type */
6675                 if (!(v < ULONG_MAX / mult[ind]))
6676                         goto error;
6677
6678                 ADD_OVERFLOW(val, mult[ind] * v);
6679                 if (val == ULONG_MAX)
6680                         goto error;
6681
6682                 timestr = tail + 1;
6683         }
6684
6685         return val;
6686
6687 error:
6688         return ULONG_MAX;
6689 }
6690
6691 #define ARG2ULL(nr, str, def_units)                                     \
6692 do {                                                                    \
6693         unsigned long long limit, units = def_units;                    \
6694         int rc;                                                         \
6695                                                                         \
6696         rc = llapi_parse_size(str, &limit, &units, 1);                  \
6697         if (rc < 0) {                                                   \
6698                 fprintf(stderr, "%s: invalid limit '%s'\n",             \
6699                         progname, str);                                 \
6700                 return CMD_HELP;                                        \
6701         }                                                               \
6702         nr = limit;                                                     \
6703 } while (0)
6704
6705 static inline int has_times_option(int argc, char **argv)
6706 {
6707         int i;
6708
6709         for (i = 1; i < argc; i++)
6710                 if (!strcmp(argv[i], "-t"))
6711                         return 1;
6712
6713         return 0;
6714 }
6715
6716 static inline int lfs_verify_poolarg(char *pool)
6717 {
6718         if (strnlen(optarg, LOV_MAXPOOLNAME + 1) > LOV_MAXPOOLNAME) {
6719                 fprintf(stderr,
6720                         "Pool name '%.*s' is longer than %d\n",
6721                         LOV_MAXPOOLNAME, pool, LOV_MAXPOOLNAME);
6722                 return 1;
6723         }
6724         return 0;
6725 }
6726
6727 int lfs_setquota_times(int argc, char **argv, struct if_quotactl *qctl)
6728 {
6729         int c, rc;
6730         char *mnt, *obd_type = (char *)qctl->obd_type;
6731         struct obd_dqblk *dqb = &qctl->qc_dqblk;
6732         struct obd_dqinfo *dqi = &qctl->qc_dqinfo;
6733         struct option long_opts[] = {
6734         { .val = 'b',   .name = "block-grace",  .has_arg = required_argument },
6735         { .val = 'g',   .name = "group",        .has_arg = no_argument },
6736         { .val = 'i',   .name = "inode-grace",  .has_arg = required_argument },
6737         { .val = 'p',   .name = "projid",       .has_arg = no_argument },
6738         { .val = 't',   .name = "times",        .has_arg = no_argument },
6739         { .val = 'u',   .name = "user",         .has_arg = no_argument },
6740         { .val = LFS_POOL_OPT,
6741                         .name = "pool",         .has_arg = required_argument },
6742         { .name = NULL } };
6743         int qtype;
6744
6745         qctl->qc_cmd  = LUSTRE_Q_SETINFO;
6746         qctl->qc_type = ALLQUOTA;
6747
6748         while ((c = getopt_long(argc, argv, "b:gi:ptu",
6749                                 long_opts, NULL)) != -1) {
6750                 switch (c) {
6751                 case 'u':
6752                         qtype = USRQUOTA;
6753                         goto quota_type;
6754                 case 'g':
6755                         qtype = GRPQUOTA;
6756                         goto quota_type;
6757                 case 'p':
6758                         qtype = PRJQUOTA;
6759 quota_type:
6760                         if (qctl->qc_type != ALLQUOTA) {
6761                                 fprintf(stderr,
6762                                         "error: -u/g/p can't be used more than once\n");
6763                                 return CMD_HELP;
6764                         }
6765                         qctl->qc_type = qtype;
6766                         break;
6767                 case 'b':
6768                         if (strncmp(optarg, NOTIFY_GRACE,
6769                                     strlen(NOTIFY_GRACE)) == 0) {
6770                                 dqi->dqi_bgrace = NOTIFY_GRACE_TIME;
6771                         } else {
6772                                 dqi->dqi_bgrace = str2sec(optarg);
6773                                 if (dqi->dqi_bgrace >= NOTIFY_GRACE_TIME) {
6774                                         fprintf(stderr,
6775                                                 "error: bad block-grace: %s\n",
6776                                                 optarg);
6777                                         return CMD_HELP;
6778                                 }
6779                         }
6780                         dqb->dqb_valid |= QIF_BTIME;
6781                         break;
6782                 case 'i':
6783                         if (strncmp(optarg, NOTIFY_GRACE,
6784                                     strlen(NOTIFY_GRACE)) == 0) {
6785                                 dqi->dqi_igrace = NOTIFY_GRACE_TIME;
6786                         } else {
6787                                 dqi->dqi_igrace = str2sec(optarg);
6788                                 if (dqi->dqi_igrace >= NOTIFY_GRACE_TIME) {
6789                                         fprintf(stderr,
6790                                                 "error: bad inode-grace: %s\n",
6791                                                 optarg);
6792                                         return CMD_HELP;
6793                                 }
6794                         }
6795                         dqb->dqb_valid |= QIF_ITIME;
6796                         break;
6797                 case 't': /* Yes, of course! */
6798                         break;
6799                 case LFS_POOL_OPT:
6800                         if (lfs_verify_poolarg(optarg))
6801                                 return -1;
6802                         fprintf(stdout,
6803                                 "Trying to set grace for pool %s\n", optarg);
6804                         strncpy(qctl->qc_poolname, optarg, LOV_MAXPOOLNAME);
6805                         qctl->qc_cmd  = LUSTRE_Q_SETINFOPOOL;
6806                         break;
6807                 /* getopt prints error message for us when opterr != 0 */
6808                 default:
6809                         return CMD_HELP;
6810                 }
6811         }
6812
6813         if (qctl->qc_type == ALLQUOTA) {
6814                 fprintf(stderr, "error: neither -u, -g nor -p specified\n");
6815                 return CMD_HELP;
6816         }
6817
6818         if (optind != argc - 1) {
6819                 fprintf(stderr, "error: unexpected parameters encountered\n");
6820                 return CMD_HELP;
6821         }
6822
6823         mnt = argv[optind];
6824         rc = llapi_quotactl(mnt, qctl);
6825         if (rc) {
6826                 if (*obd_type)
6827                         fprintf(stderr, "%s %s ", obd_type,
6828                                 obd_uuid2str(&qctl->obd_uuid));
6829                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
6830                 return rc;
6831         }
6832
6833         return 0;
6834 }
6835
6836 #define BSLIMIT (1 << 0)
6837 #define BHLIMIT (1 << 1)
6838 #define ISLIMIT (1 << 2)
6839 #define IHLIMIT (1 << 3)
6840
6841 int lfs_setquota(int argc, char **argv)
6842 {
6843         int c, rc = 0;
6844         struct if_quotactl *qctl;
6845         char *mnt, *obd_type;
6846         struct obd_dqblk *dqb;
6847         struct option long_opts[] = {
6848         { .val = 'b',   .name = "block-softlimit",
6849                                                 .has_arg = required_argument },
6850         { .val = 'B',   .name = "block-hardlimit",
6851                                                 .has_arg = required_argument },
6852         { .val = 'd',   .name = "default",      .has_arg = no_argument },
6853         { .val = 'g',   .name = "group",        .has_arg = required_argument },
6854         { .val = 'G',   .name = "default-grp",  .has_arg = no_argument },
6855         { .val = 'i',   .name = "inode-softlimit",
6856                                                 .has_arg = required_argument },
6857         { .val = 'I',   .name = "inode-hardlimit",
6858                                                 .has_arg = required_argument },
6859         { .val = 'p',   .name = "projid",       .has_arg = required_argument },
6860         { .val = 'P',   .name = "default-prj",  .has_arg = no_argument },
6861         { .val = 'u',   .name = "user",         .has_arg = required_argument },
6862         { .val = 'U',   .name = "default-usr",  .has_arg = no_argument },
6863         { .val = LFS_POOL_OPT,
6864                         .name = "pool",         .has_arg = required_argument },
6865         { .name = NULL } };
6866         unsigned int limit_mask = 0;
6867         bool use_default = false;
6868         int qtype, qctl_len;
6869
6870         qctl_len = sizeof(*qctl) + LOV_MAXPOOLNAME + 1;
6871         qctl = malloc(qctl_len);
6872         if (!qctl)
6873                 return -ENOMEM;
6874
6875         memset(qctl, 0, qctl_len);
6876         obd_type = (char *)qctl->obd_type;
6877         dqb = &qctl->qc_dqblk;
6878
6879         if (has_times_option(argc, argv)) {
6880                 rc = lfs_setquota_times(argc, argv, qctl);
6881                 goto out;
6882         }
6883
6884         qctl->qc_cmd  = LUSTRE_Q_SETQUOTA;
6885         qctl->qc_type = ALLQUOTA; /* ALLQUOTA makes no sense for setquota,
6886                                    * so it can be used as a marker that qc_type
6887                                    * isn't reinitialized from command line
6888                                    */
6889
6890         while ((c = getopt_long(argc, argv, "b:B:dg:Gi:I:p:Pu:U",
6891                 long_opts, NULL)) != -1) {
6892                 switch (c) {
6893                 case 'U':
6894                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
6895                         qtype = USRQUOTA;
6896                         qctl->qc_id = 0;
6897                         goto quota_type_def;
6898                 case 'u':
6899                         qtype = USRQUOTA;
6900                         rc = name2uid(&qctl->qc_id, optarg);
6901                         goto quota_type;
6902                 case 'G':
6903                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
6904                         qtype = GRPQUOTA;
6905                         qctl->qc_id = 0;
6906                         goto quota_type_def;
6907                 case 'g':
6908                         qtype = GRPQUOTA;
6909                         rc = name2gid(&qctl->qc_id, optarg);
6910                         goto quota_type;
6911                 case 'P':
6912                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
6913                         qtype = PRJQUOTA;
6914                         qctl->qc_id = 0;
6915                         goto quota_type_def;
6916                 case 'p':
6917                         qtype = PRJQUOTA;
6918                         rc = name2projid(&qctl->qc_id, optarg);
6919 quota_type:
6920                         if (rc) {
6921                                 if (str2quotaid(&qctl->qc_id, optarg)) {
6922                                         fprintf(stderr,
6923                                                 "%s setquota: invalid id '%s'\n",
6924                                                 progname, optarg);
6925                                         rc = -1;
6926                                         goto out;
6927                                 }
6928                         }
6929
6930                         if (qctl->qc_id == 0) {
6931                                 fprintf(stderr,
6932                                         "%s setquota: can't set quota for root usr/group/project.\n",
6933                                         progname);
6934                                 rc = -1;
6935                                 goto out;
6936                         }
6937
6938 quota_type_def:
6939                         if (qctl->qc_type != ALLQUOTA) {
6940                                 fprintf(stderr,
6941                                         "%s setquota: only one of -u, -U, -g, -G, -p or -P may be specified\n",
6942                                         progname);
6943                                 rc = CMD_HELP;
6944                                 goto out;
6945                         }
6946                         qctl->qc_type = qtype;
6947                         break;
6948                 case 'd':
6949                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
6950                         use_default = true;
6951                         break;
6952                 case 'b':
6953                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
6954                         dqb->dqb_bsoftlimit >>= 10;
6955                         limit_mask |= BSLIMIT;
6956                         if (dqb->dqb_bsoftlimit &&
6957                             dqb->dqb_bsoftlimit <= 1024) /* <= 1M? */
6958                                 fprintf(stderr,
6959                                         "%s setquota: warning: block softlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
6960                                         progname,
6961                                         (unsigned long long)dqb->dqb_bsoftlimit,
6962                                         progname);
6963                         break;
6964                 case 'B':
6965                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
6966                         dqb->dqb_bhardlimit >>= 10;
6967                         limit_mask |= BHLIMIT;
6968                         if (dqb->dqb_bhardlimit &&
6969                             dqb->dqb_bhardlimit <= 1024) /* <= 1M? */
6970                                 fprintf(stderr,
6971                                         "%s setquota: warning: block hardlimit '%llu' smaller than minimum qunit size\n"
6972                                         "See '%s help setquota' or Lustre manual for details\n",
6973                                         progname,
6974                                         (unsigned long long)dqb->dqb_bhardlimit,
6975                                         progname);
6976                         break;
6977                 case 'i':
6978                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
6979                         limit_mask |= ISLIMIT;
6980                         if (dqb->dqb_isoftlimit &&
6981                             dqb->dqb_isoftlimit <= 1024) /* <= 1K inodes? */
6982                                 fprintf(stderr,
6983                                         "%s setquota: warning: inode softlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
6984                                         progname,
6985                                         (unsigned long long)dqb->dqb_isoftlimit,
6986                                         progname);
6987                         break;
6988                 case 'I':
6989                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
6990                         limit_mask |= IHLIMIT;
6991                         if (dqb->dqb_ihardlimit &&
6992                             dqb->dqb_ihardlimit <= 1024) /* <= 1K inodes? */
6993                                 fprintf(stderr,
6994                                         "%s setquota: warning: inode hardlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
6995                                         progname,
6996                                         (unsigned long long)dqb->dqb_ihardlimit,
6997                                         progname);
6998                         break;
6999                 case LFS_POOL_OPT:
7000                         if (lfs_verify_poolarg(optarg)) {
7001                                 rc = -1;
7002                                 goto out;
7003                         }
7004                         fprintf(stdout,
7005                                 "Trying to set quota for pool %s\n", optarg);
7006                         strncpy(qctl->qc_poolname, optarg, LOV_MAXPOOLNAME);
7007                         qctl->qc_cmd  = LUSTRE_Q_SETQUOTAPOOL;
7008                         break;
7009                 default:
7010                         fprintf(stderr,
7011                                 "%s setquota: unrecognized option '%s'\n",
7012                                 progname, argv[optind - 1]);
7013                         rc = CMD_HELP;
7014                         goto out;
7015                 }
7016         }
7017
7018         if (qctl->qc_type == ALLQUOTA) {
7019                 fprintf(stderr,
7020                         "%s setquota: either -u or -g must be specified\n",
7021                         progname);
7022                 rc = CMD_HELP;
7023                 goto out;
7024         }
7025
7026         if (!use_default && limit_mask == 0) {
7027                 fprintf(stderr,
7028                         "%s setquota: at least one limit must be specified\n",
7029                         progname);
7030                 rc = CMD_HELP;
7031                 goto out;
7032         }
7033
7034         if (use_default && limit_mask != 0) {
7035                 fprintf(stderr,
7036                         "%s setquota: limits should not be specified when using default quota\n",
7037                         progname);
7038                 rc = CMD_HELP;
7039                 goto out;
7040         }
7041
7042         if (use_default && qctl->qc_id == 0) {
7043                 fprintf(stderr,
7044                         "%s setquota: can not set default quota for root user/group/project\n",
7045                         progname);
7046                 rc = CMD_HELP;
7047                 goto out;
7048         }
7049
7050         if (optind != argc - 1) {
7051                 fprintf(stderr,
7052                         "%s setquota: filesystem not specified or unexpected argument '%s'\n",
7053                         progname, argv[optind]);
7054                 rc = CMD_HELP;
7055                 goto out;
7056         }
7057
7058         mnt = argv[optind];
7059
7060         if (use_default) {
7061                 dqb->dqb_bhardlimit = 0;
7062                 dqb->dqb_bsoftlimit = 0;
7063                 dqb->dqb_ihardlimit = 0;
7064                 dqb->dqb_isoftlimit = 0;
7065                 dqb->dqb_itime = 0;
7066                 dqb->dqb_btime = 0;
7067                 dqb->dqb_valid |= QIF_LIMITS | QIF_TIMES;
7068         } else if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
7069                    (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
7070                 /* sigh, we can't just set blimits/ilimits */
7071                 struct if_quotactl tmp_qctl = {.qc_cmd  = LUSTRE_Q_GETQUOTA,
7072                                                .qc_type = qctl->qc_type,
7073                                                .qc_id   = qctl->qc_id};
7074
7075                 rc = llapi_quotactl(mnt, &tmp_qctl);
7076                 if (rc < 0)
7077                         goto out;
7078
7079                 if (!(limit_mask & BHLIMIT))
7080                         dqb->dqb_bhardlimit = tmp_qctl.qc_dqblk.dqb_bhardlimit;
7081                 if (!(limit_mask & BSLIMIT))
7082                         dqb->dqb_bsoftlimit = tmp_qctl.qc_dqblk.dqb_bsoftlimit;
7083                 if (!(limit_mask & IHLIMIT))
7084                         dqb->dqb_ihardlimit = tmp_qctl.qc_dqblk.dqb_ihardlimit;
7085                 if (!(limit_mask & ISLIMIT))
7086                         dqb->dqb_isoftlimit = tmp_qctl.qc_dqblk.dqb_isoftlimit;
7087
7088                 /* Keep grace times if we have got no softlimit arguments */
7089                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
7090                         dqb->dqb_valid |= QIF_BTIME;
7091                         dqb->dqb_btime = tmp_qctl.qc_dqblk.dqb_btime;
7092                 }
7093
7094                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
7095                         dqb->dqb_valid |= QIF_ITIME;
7096                         dqb->dqb_itime = tmp_qctl.qc_dqblk.dqb_itime;
7097                 }
7098         }
7099
7100         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
7101         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
7102
7103         rc = llapi_quotactl(mnt, qctl);
7104         if (rc) {
7105                 if (*obd_type)
7106                         fprintf(stderr,
7107                                 "%s setquota: cannot quotactl '%s' '%s': %s",
7108                                 progname, obd_type,
7109                                 obd_uuid2str(&qctl->obd_uuid), strerror(-rc));
7110         }
7111 out:
7112         free(qctl);
7113         return rc;
7114 }
7115
7116 /* Converts seconds value into format string
7117  * result is returned in buf
7118  * Notes:
7119  *        1. result is in descenting order: 1w2d3h4m5s
7120  *        2. zero fields are not filled (except for p. 3): 5d1s
7121  *        3. zero seconds value is presented as "0s"
7122  */
7123 static char *__sec2str(time_t seconds, char *buf)
7124 {
7125         const char spec[] = "smhdw";
7126         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
7127         unsigned long c;
7128         char *tail = buf;
7129         int i;
7130
7131         for (i = ARRAY_SIZE(mult) - 1 ; i >= 0; i--) {
7132                 c = seconds / mult[i];
7133
7134                 if (c > 0 || (i == 0 && buf == tail))
7135                         tail += scnprintf(tail, 40-(tail-buf), "%lu%c", c,
7136                                           spec[i]);
7137
7138                 seconds %= mult[i];
7139         }
7140
7141         return tail;
7142 }
7143
7144 static void sec2str(time_t seconds, char *buf, int rc)
7145 {
7146         char *tail = buf;
7147
7148         if (rc)
7149                 *tail++ = '[';
7150
7151         tail = __sec2str(seconds, tail);
7152
7153         if (rc && tail - buf < 39) {
7154                 *tail++ = ']';
7155                 *tail++ = 0;
7156         }
7157 }
7158
7159 static void diff2str(time_t seconds, char *buf, time_t now)
7160 {
7161         buf[0] = 0;
7162         if (!seconds)
7163                 return;
7164         if (seconds <= now) {
7165                 strcpy(buf, "none");
7166                 return;
7167         }
7168         __sec2str(seconds - now, buf);
7169 }
7170
7171 static void print_quota_title(char *name, struct if_quotactl *qctl,
7172                               bool human_readable, bool show_default)
7173 {
7174         if (show_default) {
7175                 printf("Disk default %s quota:\n", qtype_name(qctl->qc_type));
7176                 printf("%15s %8s%8s%8s %8s%8s%8s\n",
7177                        "Filesystem", "bquota", "blimit", "bgrace",
7178                        "iquota", "ilimit", "igrace");
7179         } else {
7180                 printf("Disk quotas for %s %s (%cid %u):\n",
7181                        qtype_name(qctl->qc_type), name,
7182                        *qtype_name(qctl->qc_type), qctl->qc_id);
7183                 printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
7184                        "Filesystem", human_readable ? "used" : "kbytes",
7185                        "quota", "limit", "grace",
7186                        "files", "quota", "limit", "grace");
7187         }
7188 }
7189
7190 static void kbytes2str(__u64 num, char *buf, int buflen, bool h)
7191 {
7192         if (!h) {
7193                 snprintf(buf, buflen, "%ju", (uintmax_t)num);
7194         } else {
7195                 if (num >> 40)
7196                         snprintf(buf, buflen, "%5.4gP",
7197                                  (double)num / ((__u64)1 << 40));
7198                 else if (num >> 30)
7199                         snprintf(buf, buflen, "%5.4gT",
7200                                  (double)num / (1 << 30));
7201                 else if (num >> 20)
7202                         snprintf(buf, buflen, "%5.4gG",
7203                                  (double)num / (1 << 20));
7204                 else if (num >> 10)
7205                         snprintf(buf, buflen, "%5.4gM",
7206                                  (double)num / (1 << 10));
7207                 else
7208                         snprintf(buf, buflen, "%ju%s", (uintmax_t)num, "k");
7209         }
7210 }
7211
7212 #define STRBUF_LEN      32
7213 static void print_quota(char *mnt, struct if_quotactl *qctl, int type,
7214                         int rc, bool h, bool show_default)
7215 {
7216         time_t now;
7217
7218         time(&now);
7219
7220         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA ||
7221             qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ||
7222             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) {
7223                 int bover = 0, iover = 0;
7224                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
7225                 char numbuf[3][STRBUF_LEN];
7226                 char timebuf[40];
7227                 char strbuf[STRBUF_LEN];
7228
7229                 if (dqb->dqb_bhardlimit &&
7230                     lustre_stoqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
7231                         bover = 1;
7232                 } else if (dqb->dqb_bsoftlimit && dqb->dqb_btime) {
7233                         if (dqb->dqb_btime > now)
7234                                 bover = 2;
7235                         else
7236                                 bover = 3;
7237                 }
7238
7239                 if (dqb->dqb_ihardlimit &&
7240                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
7241                         iover = 1;
7242                 } else if (dqb->dqb_isoftlimit && dqb->dqb_itime) {
7243                         if (dqb->dqb_itime > now)
7244                                 iover = 2;
7245                         else
7246                                 iover = 3;
7247                 }
7248
7249                 if (strlen(mnt) > 15)
7250                         printf("%s\n%15s", mnt, "");
7251                 else
7252                         printf("%15s", mnt);
7253
7254                 if (bover)
7255                         diff2str(dqb->dqb_btime, timebuf, now);
7256                 else if (show_default)
7257                         snprintf(timebuf, sizeof(timebuf), "%llu",
7258                                  (unsigned long long)dqb->dqb_btime);
7259
7260                 kbytes2str(lustre_stoqb(dqb->dqb_curspace),
7261                            strbuf, sizeof(strbuf), h);
7262                 if (rc == -EREMOTEIO)
7263                         sprintf(numbuf[0], "%s*", strbuf);
7264                 else
7265                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
7266                                 "%s" : "[%s]", strbuf);
7267
7268                 kbytes2str(dqb->dqb_bsoftlimit, strbuf, sizeof(strbuf), h);
7269                 if (type == QC_GENERAL)
7270                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS) ?
7271                                 "%s" : "[%s]", strbuf);
7272                 else
7273                         sprintf(numbuf[1], "%s", "-");
7274
7275                 kbytes2str(dqb->dqb_bhardlimit, strbuf, sizeof(strbuf), h);
7276                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS) ?
7277                         "%s" : "[%s]", strbuf);
7278
7279                 if (show_default)
7280                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
7281                 else
7282                         printf(" %7s%c %6s %7s %7s",
7283                                numbuf[0], bover ? '*' : ' ', numbuf[1],
7284                                numbuf[2], bover > 1 ? timebuf : "-");
7285
7286                 if (iover)
7287                         diff2str(dqb->dqb_itime, timebuf, now);
7288                 else if (show_default)
7289                         snprintf(timebuf, sizeof(timebuf), "%llu",
7290                                  (unsigned long long)dqb->dqb_itime);
7291
7292                 snprintf(numbuf[0], sizeof(numbuf),
7293                          (dqb->dqb_valid & QIF_INODES) ? "%ju" : "[%ju]",
7294                          (uintmax_t)dqb->dqb_curinodes);
7295
7296                 if (type == QC_GENERAL)
7297                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS) ?
7298                                 "%ju" : "[%ju]",
7299                                 (uintmax_t)dqb->dqb_isoftlimit);
7300                 else
7301                         sprintf(numbuf[1], "%s", "-");
7302
7303                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
7304                         "%ju" : "[%ju]", (uintmax_t)dqb->dqb_ihardlimit);
7305
7306                 if (show_default)
7307                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
7308                 else if (type != QC_OSTIDX)
7309                         printf(" %7s%c %6s %7s %7s",
7310                                numbuf[0], iover ? '*' : ' ', numbuf[1],
7311                                numbuf[2], iover > 1 ? timebuf : "-");
7312                 else
7313                         printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
7314                 printf("\n");
7315         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO || LUSTRE_Q_GETINFOPOOL ||
7316                    qctl->qc_cmd == Q_GETOINFO) {
7317                 char bgtimebuf[40];
7318                 char igtimebuf[40];
7319
7320                 if (qctl->qc_dqinfo.dqi_bgrace == NOTIFY_GRACE_TIME)
7321                         strncpy(bgtimebuf, NOTIFY_GRACE, 40);
7322                 else
7323                         sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
7324                 if (qctl->qc_dqinfo.dqi_igrace == NOTIFY_GRACE_TIME)
7325                         strncpy(igtimebuf, NOTIFY_GRACE, 40);
7326                 else
7327                         sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
7328
7329                 printf("Block grace time: %s; Inode grace time: %s\n",
7330                        bgtimebuf, igtimebuf);
7331         }
7332 }
7333
7334 static int tgt_name2index(const char *tgtname, unsigned int *idx)
7335 {
7336         char *dash, *endp;
7337
7338         /* format is "lustre-OST0001" */
7339         dash = memchr(tgtname, '-', LUSTRE_MAXFSNAME + 1);
7340         if (!dash) {
7341                 fprintf(stderr, "wrong tgtname format '%s'\n", tgtname);
7342                 return -EINVAL;
7343         }
7344         dash += 4;
7345
7346         *idx = strtoul(dash, &endp, 16);
7347         if (*idx > 0xffff) {
7348                 fprintf(stderr, "wrong index %s\n", tgtname);
7349                 return -ERANGE;
7350         }
7351
7352         return 0;
7353 }
7354
7355 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt,
7356                            bool h, __u64 *total)
7357 {
7358         int rc = 0, rc1 = 0, count = 0, i = 0;
7359         char **list = NULL, *buffer = NULL;
7360         __u32 valid = qctl->qc_valid;
7361
7362         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL && is_mdt)
7363                 return 0;
7364
7365         /* Is it correct for the case OST0000, OST0002, OST0003 -
7366          * we will ask OST0001 that is absent and won't ask OST0003? */
7367         rc = llapi_get_obd_count(mnt, &count, is_mdt);
7368         if (rc) {
7369                 fprintf(stderr, "can not get %s count: %s\n",
7370                         is_mdt ? "mdt" : "ost", strerror(-rc));
7371                 return rc;
7372         }
7373
7374         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
7375                 char fname[PATH_MAX];
7376                 char fsname[LUSTRE_MAXFSNAME + 1];
7377                 int bufsize = sizeof(struct obd_uuid) * count;
7378
7379                 rc = llapi_search_fsname(mnt, fsname);
7380                 if (rc) {
7381                         fprintf(stderr, "cannot get fsname for mountpoint %s\n",
7382                                 mnt);
7383                         goto out;
7384                 }
7385                 buffer = malloc(bufsize + sizeof(*list) * count);
7386                 if (!buffer)
7387                         return -ENOMEM;
7388                 list = (char **)(buffer + bufsize);
7389                 snprintf(fname, PATH_MAX, "%s.%s", fsname, qctl->qc_poolname);
7390                 count = llapi_get_poolmembers(fname, list, count,
7391                                               buffer, bufsize);
7392                 if (count <= 0)
7393                         goto out;
7394         }
7395
7396         for (i = 0; i < count; i++) {
7397                 if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
7398                         unsigned int index;
7399
7400                         if (tgt_name2index(list[i], &index))
7401                                 continue;
7402                         qctl->qc_idx = index;
7403                 } else {
7404                         qctl->qc_idx = i;
7405                 }
7406
7407                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
7408                 rc = llapi_quotactl(mnt, qctl);
7409                 if (rc) {
7410                         /* It is remote client case. */
7411                         if (rc == -EOPNOTSUPP) {
7412                                 rc = 0;
7413                                 goto out;
7414                         }
7415
7416                         if (!rc1)
7417                                 rc1 = rc;
7418                         fprintf(stderr, "quotactl %s%d failed.\n",
7419                                 is_mdt ? "mdt" : "ost", qctl->qc_idx);
7420                         continue;
7421                 }
7422
7423                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl,
7424                             qctl->qc_valid, 0, h, false);
7425                 *total += is_mdt ? qctl->qc_dqblk.dqb_ihardlimit :
7426                                    qctl->qc_dqblk.dqb_bhardlimit;
7427         }
7428 out:
7429         if (buffer)
7430                 free(buffer);
7431         qctl->qc_valid = valid;
7432         return rc ? : rc1;
7433 }
7434
7435 static int get_print_quota(char *mnt, char *name, struct if_quotactl *qctl,
7436                            int verbose, int quiet, bool human_readable,
7437                            bool show_default)
7438 {
7439         int rc1 = 0, rc2 = 0, rc3 = 0;
7440         char *obd_type = (char *)qctl->obd_type;
7441         char *obd_uuid = (char *)qctl->obd_uuid.uuid;
7442         __u64 total_ialloc = 0, total_balloc = 0;
7443         bool use_default_for_blk = false;
7444         bool use_default_for_file = false;
7445         int inacc;
7446
7447         rc1 = llapi_quotactl(mnt, qctl);
7448         if (rc1 < 0) {
7449                 switch (rc1) {
7450                 case -ESRCH:
7451                         fprintf(stderr, "%s quotas are not enabled.\n",
7452                                 qtype_name(qctl->qc_type));
7453                         goto out;
7454                 case -EPERM:
7455                         fprintf(stderr, "Permission denied.\n");
7456                 case -ENODEV:
7457                 case -ENOENT:
7458                         /* We already got error message. */
7459                         goto out;
7460                 default:
7461                         fprintf(stderr, "Unexpected quotactl error: %s\n",
7462                                 strerror(-rc1));
7463                 }
7464         }
7465
7466         if (!show_default && qctl->qc_id == 0) {
7467                 qctl->qc_dqblk.dqb_bhardlimit = 0;
7468                 qctl->qc_dqblk.dqb_bsoftlimit = 0;
7469                 qctl->qc_dqblk.dqb_ihardlimit = 0;
7470                 qctl->qc_dqblk.dqb_isoftlimit = 0;
7471                 qctl->qc_dqblk.dqb_btime = 0;
7472                 qctl->qc_dqblk.dqb_itime = 0;
7473                 qctl->qc_dqblk.dqb_valid |= QIF_LIMITS | QIF_TIMES;
7474         }
7475
7476         if (qctl->qc_dqblk.dqb_valid & QIF_BTIME &&
7477             LQUOTA_FLAG(qctl->qc_dqblk.dqb_btime) & LQUOTA_FLAG_DEFAULT) {
7478                 use_default_for_blk = true;
7479                 qctl->qc_dqblk.dqb_btime &= LQUOTA_GRACE_MASK;
7480         }
7481
7482         if (qctl->qc_dqblk.dqb_valid & QIF_ITIME &&
7483             LQUOTA_FLAG(qctl->qc_dqblk.dqb_itime) & LQUOTA_FLAG_DEFAULT) {
7484                 use_default_for_file = true;
7485                 qctl->qc_dqblk.dqb_itime &= LQUOTA_GRACE_MASK;
7486         }
7487
7488         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
7489              qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ||
7490              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) && !quiet)
7491                 print_quota_title(name, qctl, human_readable, show_default);
7492
7493         if (rc1 && *obd_type)
7494                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
7495
7496         if (qctl->qc_valid != QC_GENERAL)
7497                 mnt = "";
7498
7499         inacc = (qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
7500                  qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) &&
7501                 ((qctl->qc_dqblk.dqb_valid & (QIF_LIMITS|QIF_USAGE)) !=
7502                  (QIF_LIMITS|QIF_USAGE));
7503
7504         print_quota(mnt, qctl, QC_GENERAL, rc1, human_readable, show_default);
7505
7506         if (!show_default && verbose &&
7507             qctl->qc_valid == QC_GENERAL && qctl->qc_cmd != LUSTRE_Q_GETINFO &&
7508             qctl->qc_cmd != LUSTRE_Q_GETINFOPOOL) {
7509                 char strbuf[STRBUF_LEN];
7510
7511                 rc2 = print_obd_quota(mnt, qctl, 1, human_readable,
7512                                       &total_ialloc);
7513                 rc3 = print_obd_quota(mnt, qctl, 0, human_readable,
7514                                       &total_balloc);
7515                 kbytes2str(total_balloc, strbuf, sizeof(strbuf),
7516                            human_readable);
7517                 printf("Total allocated inode limit: %ju, total allocated block limit: %s\n",
7518                        (uintmax_t)total_ialloc, strbuf);
7519         }
7520
7521         if (use_default_for_blk)
7522                 printf("%cid %u is using default block quota setting\n",
7523                        *qtype_name(qctl->qc_type), qctl->qc_id);
7524
7525         if (use_default_for_file)
7526                 printf("%cid %u is using default file quota setting\n",
7527                        *qtype_name(qctl->qc_type), qctl->qc_id);
7528
7529         if (rc1 || rc2 || rc3 || inacc)
7530                 printf("Some errors happened when getting quota info. Some devices may be not working or deactivated. The data in \"[]\" is inaccurate.\n");
7531 out:
7532         if (rc1)
7533                 return rc1;
7534         if (rc2)
7535                 return rc2;
7536         if (rc3)
7537                 return rc3;
7538         if (inacc)
7539                 return -EIO;
7540
7541         return 0;
7542 }
7543
7544 static int lfs_project(int argc, char **argv)
7545 {
7546         int ret = 0, err = 0, c, i;
7547         struct project_handle_control phc = { 0 };
7548         enum lfs_project_ops_t op;
7549
7550         phc.newline = true;
7551         phc.assign_projid = false;
7552         /* default action */
7553         op = LFS_PROJECT_LIST;
7554
7555         while ((c = getopt(argc, argv, "p:cCsdkr0")) != -1) {
7556                 switch (c) {
7557                 case 'c':
7558                         if (op != LFS_PROJECT_LIST) {
7559                                 fprintf(stderr,
7560                                         "%s: cannot specify '-c' '-C' '-s' together\n",
7561                                         progname);
7562                                 return CMD_HELP;
7563                         }
7564
7565                         op = LFS_PROJECT_CHECK;
7566                         break;
7567                 case 'C':
7568                         if (op != LFS_PROJECT_LIST) {
7569                                 fprintf(stderr,
7570                                         "%s: cannot specify '-c' '-C' '-s' together\n",
7571                                         progname);
7572                                 return CMD_HELP;
7573                         }
7574
7575                         op = LFS_PROJECT_CLEAR;
7576                         break;
7577                 case 's':
7578                         if (op != LFS_PROJECT_LIST) {
7579                                 fprintf(stderr,
7580                                         "%s: cannot specify '-c' '-C' '-s' together\n",
7581                                         progname);
7582                                 return CMD_HELP;
7583                         }
7584
7585                         phc.set_inherit = true;
7586                         op = LFS_PROJECT_SET;
7587                         break;
7588                 case 'd':
7589                         phc.dironly = true;
7590                         break;
7591                 case 'k':
7592                         phc.keep_projid = true;
7593                         break;
7594                 case 'r':
7595                         phc.recursive = true;
7596                         break;
7597                 case 'p':
7598                         if (str2quotaid(&phc.projid, optarg)) {
7599                                 fprintf(stderr,
7600                                         "Invalid project ID: %s\n",
7601                                         optarg);
7602                                 return CMD_HELP;
7603                         }
7604
7605                         phc.assign_projid = true;
7606
7607                         break;
7608                 case '0':
7609                         phc.newline = false;
7610                         break;
7611                 default:
7612                         fprintf(stderr, "%s: invalid option '%c'\n",
7613                                 progname, optopt);
7614                         return CMD_HELP;
7615                 }
7616         }
7617
7618         if (phc.assign_projid && op == LFS_PROJECT_LIST) {
7619                 op = LFS_PROJECT_SET;
7620                 phc.set_projid = true;
7621         } else if (phc.assign_projid && op == LFS_PROJECT_SET) {
7622                 phc.set_projid = true;
7623         }
7624
7625         switch (op) {
7626         case LFS_PROJECT_CHECK:
7627                 if (phc.keep_projid) {
7628                         fprintf(stderr,
7629                                 "%s: '-k' is useless together with '-c'\n",
7630                                 progname);
7631                         return CMD_HELP;
7632                 }
7633                 break;
7634         case LFS_PROJECT_CLEAR:
7635                 if (!phc.newline) {
7636                         fprintf(stderr,
7637                                 "%s: '-0' is useless together with '-C'\n",
7638                                 progname);
7639                         return CMD_HELP;
7640                 }
7641                 if (phc.assign_projid) {
7642                         fprintf(stderr,
7643                                 "%s: '-p' is useless together with '-C'\n",
7644                                 progname);
7645                         return CMD_HELP;
7646                 }
7647                 break;
7648         case LFS_PROJECT_SET:
7649                 if (!phc.newline) {
7650                         fprintf(stderr,
7651                                 "%s: '-0' is useless together with '-s'\n",
7652                                 progname);
7653                         return CMD_HELP;
7654                 }
7655                 if (phc.keep_projid) {
7656                         fprintf(stderr,
7657                                 "%s: '-k' is useless together with '-s'\n",
7658                                 progname);
7659                         return CMD_HELP;
7660                 }
7661                 break;
7662         default:
7663                 if (!phc.newline) {
7664                         fprintf(stderr,
7665                                 "%s: '-0' is useless for list operations\n",
7666                                 progname);
7667                         return CMD_HELP;
7668                 }
7669                 break;
7670         }
7671
7672         argv += optind;
7673         argc -= optind;
7674         if (argc == 0) {
7675                 fprintf(stderr, "%s: missing file or directory target(s)\n",
7676                         progname);
7677                 return CMD_HELP;
7678         }
7679
7680         for (i = 0; i < argc; i++) {
7681                 switch (op) {
7682                 case LFS_PROJECT_CHECK:
7683                         err = lfs_project_check(argv[i], &phc);
7684                         break;
7685                 case LFS_PROJECT_LIST:
7686                         err = lfs_project_list(argv[i], &phc);
7687                         break;
7688                 case LFS_PROJECT_CLEAR:
7689                         err = lfs_project_clear(argv[i], &phc);
7690                         break;
7691                 case LFS_PROJECT_SET:
7692                         err = lfs_project_set(argv[i], &phc);
7693                         break;
7694                 default:
7695                         break;
7696                 }
7697                 if (err && !ret)
7698                         ret = err;
7699         }
7700
7701         return ret;
7702 }
7703
7704 static int lfs_quota(int argc, char **argv)
7705 {
7706         int c;
7707         char *mnt, *name = NULL;
7708         struct if_quotactl *qctl;
7709         char *obd_uuid;
7710         int rc = 0, rc1 = 0, verbose = 0, quiet = 0;
7711         __u32 valid = QC_GENERAL, idx = 0;
7712         bool human_readable = false;
7713         bool show_default = false;
7714         int qtype;
7715         struct option long_opts[] = {
7716         { .val = LFS_POOL_OPT, .name = "pool", .has_arg = required_argument },
7717         { .name = NULL } };
7718
7719         qctl = calloc(1, sizeof(*qctl) + LOV_MAXPOOLNAME + 1);
7720         if (!qctl)
7721                 return -ENOMEM;
7722
7723         qctl->qc_cmd = LUSTRE_Q_GETQUOTA;
7724         qctl->qc_type = ALLQUOTA;
7725         obd_uuid = (char *)qctl->obd_uuid.uuid;
7726
7727         while ((c = getopt_long(argc, argv, "gGi:I:o:pPqtuUvh",
7728                 long_opts, NULL)) != -1) {
7729                 switch (c) {
7730                 case 'U':
7731                         show_default = true;
7732                 case 'u':
7733                         qtype = USRQUOTA;
7734                         goto quota_type;
7735                 case 'G':
7736                         show_default = true;
7737                 case 'g':
7738                         qtype = GRPQUOTA;
7739                         goto quota_type;
7740                 case 'P':
7741                         show_default = true;
7742                 case 'p':
7743                         qtype = PRJQUOTA;
7744 quota_type:
7745                         if (qctl->qc_type != ALLQUOTA) {
7746                                 fprintf(stderr,
7747                                         "%s quota: only one of -u, -g, or -p may be specified\n",
7748                                         progname);
7749                                 rc = CMD_HELP;
7750                                 goto out;
7751                         }
7752                         qctl->qc_type = qtype;
7753                         break;
7754                 case 't':
7755                         qctl->qc_cmd = LUSTRE_Q_GETINFO;
7756                         break;
7757                 case 'o':
7758                         valid = qctl->qc_valid = QC_UUID;
7759                         snprintf(obd_uuid, sizeof(*obd_uuid), "%s", optarg);
7760                         break;
7761                 case 'i':
7762                         valid = qctl->qc_valid = QC_MDTIDX;
7763                         idx = qctl->qc_idx = atoi(optarg);
7764                         if (idx == 0 && *optarg != '0') {
7765                                 fprintf(stderr,
7766                                         "%s quota: invalid MDT index '%s'\n",
7767                                         progname, optarg);
7768                                 rc = CMD_HELP;
7769                                 goto out;
7770                         }
7771                         break;
7772                 case 'I':
7773                         valid = qctl->qc_valid = QC_OSTIDX;
7774                         idx = qctl->qc_idx = atoi(optarg);
7775                         if (idx == 0 && *optarg != '0') {
7776                                 fprintf(stderr,
7777                                         "%s quota: invalid OST index '%s'\n",
7778                                         progname, optarg);
7779                                 rc = CMD_HELP;
7780                                 goto out;
7781                         }
7782                         break;
7783                 case 'v':
7784                         verbose = 1;
7785                         break;
7786                 case 'q':
7787                         quiet = 1;
7788                         break;
7789                 case 'h':
7790                         human_readable = true;
7791                         break;
7792                 case LFS_POOL_OPT:
7793                         if (lfs_verify_poolarg(optarg)) {
7794                                 rc = -1;
7795                                 goto out;
7796                         }
7797                         strncpy(qctl->qc_poolname, optarg, LOV_MAXPOOLNAME);
7798                         qctl->qc_cmd = qctl->qc_cmd == LUSTRE_Q_GETINFO ?
7799                                                 LUSTRE_Q_GETINFOPOOL :
7800                                                 LUSTRE_Q_GETQUOTAPOOL;
7801                         break;
7802                 default:
7803                         fprintf(stderr, "%s quota: unrecognized option '%s'\n",
7804                                 progname, argv[optind - 1]);
7805                         rc = CMD_HELP;
7806                         goto out;
7807                 }
7808         }
7809
7810         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
7811         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
7812              qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) &&
7813              qctl->qc_type == ALLQUOTA &&
7814              optind == argc - 1 && !show_default) {
7815                 qctl->qc_idx = idx;
7816
7817                 for (qtype = USRQUOTA; qtype <= GRPQUOTA; qtype++) {
7818                         qctl->qc_type = qtype;
7819                         qctl->qc_valid = valid;
7820                         if (qtype == USRQUOTA) {
7821                                 qctl->qc_id = geteuid();
7822                                 rc = uid2name(&name, qctl->qc_id);
7823                         } else {
7824                                 qctl->qc_id = getegid();
7825                                 rc = gid2name(&name, qctl->qc_id);
7826                                 memset(&qctl->qc_dqblk, 0,
7827                                        sizeof(qctl->qc_dqblk));
7828                         }
7829                         if (rc)
7830                                 name = "<unknown>";
7831                         mnt = argv[optind];
7832                         rc1 = get_print_quota(mnt, name, qctl, verbose, quiet,
7833                                               human_readable, show_default);
7834                         if (rc1 && !rc)
7835                                 rc = rc1;
7836                 }
7837                 goto out;
7838         /* lfs quota -u username /path/to/lustre/mount */
7839         } else if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
7840                    qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
7841                 /* options should be followed by u/g-name and mntpoint */
7842                 if ((!show_default && optind + 2 != argc) ||
7843                     (show_default && optind + 1 != argc) ||
7844                     qctl->qc_type == ALLQUOTA) {
7845                         fprintf(stderr,
7846                                 "%s quota: name and mount point must be specified\n",
7847                                 progname);
7848                         rc = CMD_HELP;
7849                         goto out;
7850                 }
7851
7852                 if (!show_default) {
7853                         name = argv[optind++];
7854                         switch (qctl->qc_type) {
7855                         case USRQUOTA:
7856                                 rc = name2uid(&qctl->qc_id, name);
7857                                 break;
7858                         case GRPQUOTA:
7859                                 rc = name2gid(&qctl->qc_id, name);
7860                                 break;
7861                         case PRJQUOTA:
7862                                 rc = name2projid(&qctl->qc_id, name);
7863                                 break;
7864                         default:
7865                                 rc = -ENOTSUP;
7866                                 break;
7867                         }
7868                 } else {
7869                         qctl->qc_valid = QC_GENERAL;
7870                         qctl->qc_cmd = LUSTRE_Q_GETDEFAULT;
7871                         qctl->qc_id = 0;
7872                 }
7873
7874                 if (rc) {
7875                         if (str2quotaid(&qctl->qc_id, name)) {
7876                                 fprintf(stderr, "%s quota: invalid id '%s'\n",
7877                                         progname, name);
7878                                 rc = CMD_HELP;
7879                                 goto out;
7880                         }
7881                 }
7882         } else if (optind + 1 != argc || qctl->qc_type == ALLQUOTA) {
7883                 fprintf(stderr, "%s quota: missing quota info argument(s)\n",
7884                         progname);
7885                 rc = CMD_HELP;
7886                 goto out;
7887         }
7888
7889         mnt = argv[optind];
7890         rc = get_print_quota(mnt, name, qctl, verbose, quiet,
7891                              human_readable, show_default);
7892 out:
7893         free(qctl);
7894         return rc;
7895 }
7896 #endif /* HAVE_SYS_QUOTA_H! */
7897
7898 static int flushctx_ioctl(char *mp)
7899 {
7900         int fd, rc;
7901
7902         fd = open(mp, O_RDONLY);
7903         if (fd == -1) {
7904                 fprintf(stderr, "flushctx: error open %s: %s\n",
7905                         mp, strerror(errno));
7906                 return -1;
7907         }
7908
7909         rc = ioctl(fd, LL_IOC_FLUSHCTX);
7910         if (rc == -1)
7911                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
7912                         mp, strerror(errno));
7913
7914         close(fd);
7915         return rc;
7916 }
7917
7918 static int lfs_flushctx(int argc, char **argv)
7919 {
7920         int     kdestroy = 0, c;
7921         char    mntdir[PATH_MAX] = {'\0'};
7922         int     index = 0;
7923         int     rc = 0;
7924
7925         while ((c = getopt(argc, argv, "k")) != -1) {
7926                 switch (c) {
7927                 case 'k':
7928                         kdestroy = 1;
7929                         break;
7930                 default:
7931                         fprintf(stderr,
7932                                 "error: %s: option '-%c' unrecognized\n",
7933                                 argv[0], c);
7934                         return CMD_HELP;
7935                 }
7936         }
7937
7938         if (kdestroy) {
7939                 rc = system("kdestroy > /dev/null");
7940                 if (rc) {
7941                         rc = WEXITSTATUS(rc);
7942                         fprintf(stderr,
7943                                 "error destroying tickets: %d, continuing\n",
7944                                 rc);
7945                 }
7946         }
7947
7948         if (optind >= argc) {
7949                 /* flush for all mounted lustre fs. */
7950                 while (!llapi_search_mounts(NULL, index++, mntdir, NULL)) {
7951                         /* Check if we have a mount point */
7952                         if (mntdir[0] == '\0')
7953                                 continue;
7954
7955                         if (flushctx_ioctl(mntdir))
7956                                 rc = -1;
7957
7958                         mntdir[0] = '\0'; /* avoid matching in next loop */
7959                 }
7960         } else {
7961                 /* flush fs as specified */
7962                 while (optind < argc) {
7963                         if (flushctx_ioctl(argv[optind++]))
7964                                 rc = -1;
7965                 }
7966         }
7967         return rc;
7968 }
7969
7970 static int lfs_changelog(int argc, char **argv)
7971 {
7972         void *changelog_priv;
7973         struct changelog_rec *rec;
7974         long long startrec = 0, endrec = 0;
7975         char *mdd;
7976         struct option long_opts[] = {
7977                 { .val = 'f', .name = "follow", .has_arg = no_argument },
7978                 { .name = NULL } };
7979         char short_opts[] = "f";
7980         int rc, follow = 0;
7981
7982         while ((rc = getopt_long(argc, argv, short_opts,
7983                 long_opts, NULL)) != -1) {
7984                 switch (rc) {
7985                 case 'f':
7986                         follow++;
7987                         break;
7988                 default:
7989                         fprintf(stderr,
7990                                 "%s changelog: unrecognized option '%s'\n",
7991                                 progname, argv[optind - 1]);
7992                         return CMD_HELP;
7993                 }
7994         }
7995         if (optind >= argc) {
7996                 fprintf(stderr, "%s changelog: mdtname must be specified\n",
7997                         progname);
7998                 return CMD_HELP;
7999         }
8000
8001         mdd = argv[optind++];
8002         if (argc > optind)
8003                 startrec = strtoll(argv[optind++], NULL, 10);
8004         if (argc > optind)
8005                 endrec = strtoll(argv[optind++], NULL, 10);
8006
8007         rc = llapi_changelog_start(&changelog_priv,
8008                                    CHANGELOG_FLAG_BLOCK |
8009                                    CHANGELOG_FLAG_JOBID |
8010                                    CHANGELOG_FLAG_EXTRA_FLAGS |
8011                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
8012                                    mdd, startrec);
8013         if (rc < 0) {
8014                 fprintf(stderr, "%s changelog: cannot start changelog: %s\n",
8015                         progname, strerror(errno = -rc));
8016                 return rc;
8017         }
8018
8019         rc = llapi_changelog_set_xflags(changelog_priv,
8020                                         CHANGELOG_EXTRA_FLAG_UIDGID |
8021                                         CHANGELOG_EXTRA_FLAG_NID |
8022                                         CHANGELOG_EXTRA_FLAG_OMODE |
8023                                         CHANGELOG_EXTRA_FLAG_XATTR);
8024         if (rc < 0) {
8025                 fprintf(stderr,
8026                         "%s changelog: cannot set xflags for changelog: %s\n",
8027                         progname, strerror(errno = -rc));
8028                 return rc;
8029         }
8030
8031         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
8032                 time_t secs;
8033                 struct tm ts;
8034
8035                 if (endrec && rec->cr_index > endrec) {
8036                         llapi_changelog_free(&rec);
8037                         break;
8038                 }
8039                 if (rec->cr_index < startrec) {
8040                         llapi_changelog_free(&rec);
8041                         continue;
8042                 }
8043
8044                 secs = rec->cr_time >> 30;
8045                 gmtime_r(&secs, &ts);
8046                 printf("%ju %02d%-5s %02d:%02d:%02d.%09d %04d.%02d.%02d "
8047                        "0x%x t="DFID, (uintmax_t)rec->cr_index, rec->cr_type,
8048                        changelog_type2str(rec->cr_type),
8049                        ts.tm_hour, ts.tm_min, ts.tm_sec,
8050                        (int)(rec->cr_time & ((1 << 30) - 1)),
8051                        ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday,
8052                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
8053
8054                 if (rec->cr_flags & CLF_JOBID) {
8055                         struct changelog_ext_jobid *jid =
8056                                 changelog_rec_jobid(rec);
8057
8058                         if (jid->cr_jobid[0] != '\0')
8059                                 printf(" j=%s", jid->cr_jobid);
8060                 }
8061
8062                 if (rec->cr_flags & CLF_EXTRA_FLAGS) {
8063                         struct changelog_ext_extra_flags *ef =
8064                                 changelog_rec_extra_flags(rec);
8065
8066                         printf(" ef=0x%llx",
8067                                (unsigned long long)ef->cr_extra_flags);
8068
8069                         if (ef->cr_extra_flags & CLFE_UIDGID) {
8070                                 struct changelog_ext_uidgid *uidgid =
8071                                         changelog_rec_uidgid(rec);
8072
8073                                 printf(" u=%llu:%llu",
8074                                        (unsigned long long)uidgid->cr_uid,
8075                                        (unsigned long long)uidgid->cr_gid);
8076                         }
8077                         if (ef->cr_extra_flags & CLFE_NID) {
8078                                 struct changelog_ext_nid *nid =
8079                                         changelog_rec_nid(rec);
8080
8081                                 printf(" nid=%s",
8082                                        libcfs_nid2str(nid->cr_nid));
8083                         }
8084
8085                         if (ef->cr_extra_flags & CLFE_OPEN) {
8086                                 struct changelog_ext_openmode *omd =
8087                                         changelog_rec_openmode(rec);
8088                                 char mode[] = "---";
8089
8090                                 /* exec mode must be exclusive */
8091                                 if (omd->cr_openflags & MDS_FMODE_EXEC) {
8092                                         mode[2] = 'x';
8093                                 } else {
8094                                         if (omd->cr_openflags & MDS_FMODE_READ)
8095                                                 mode[0] = 'r';
8096                                         if (omd->cr_openflags &
8097                                             (MDS_FMODE_WRITE |
8098                                              MDS_OPEN_TRUNC |
8099                                              MDS_OPEN_APPEND))
8100                                                 mode[1] = 'w';
8101                                 }
8102
8103                                 if (strcmp(mode, "---") != 0)
8104                                         printf(" m=%s", mode);
8105                         }
8106
8107                         if (ef->cr_extra_flags & CLFE_XATTR) {
8108                                 struct changelog_ext_xattr *xattr =
8109                                         changelog_rec_xattr(rec);
8110
8111                                 if (xattr->cr_xattr[0] != '\0')
8112                                         printf(" x=%s", xattr->cr_xattr);
8113                         }
8114                 }
8115
8116                 if (!fid_is_zero(&rec->cr_pfid))
8117                         printf(" p="DFID, PFID(&rec->cr_pfid));
8118                 if (rec->cr_namelen)
8119                         printf(" %.*s", rec->cr_namelen,
8120                                changelog_rec_name(rec));
8121
8122                 if (rec->cr_flags & CLF_RENAME) {
8123                         struct changelog_ext_rename *rnm =
8124                                 changelog_rec_rename(rec);
8125
8126                         if (!fid_is_zero(&rnm->cr_sfid))
8127                                 printf(" s="DFID" sp="DFID" %.*s",
8128                                        PFID(&rnm->cr_sfid),
8129                                        PFID(&rnm->cr_spfid),
8130                                        (int)changelog_rec_snamelen(rec),
8131                                        changelog_rec_sname(rec));
8132                 }
8133                 printf("\n");
8134
8135                 llapi_changelog_free(&rec);
8136         }
8137
8138         llapi_changelog_fini(&changelog_priv);
8139
8140         if (rc < 0)
8141                 fprintf(stderr, "%s changelog: cannot access changelog: %s\n",
8142                         progname, strerror(errno = -rc));
8143
8144         return (rc == 1 ? 0 : rc);
8145 }
8146
8147 static int lfs_changelog_clear(int argc, char **argv)
8148 {
8149         long long endrec;
8150         int rc;
8151
8152         if (argc != 4)
8153                 return CMD_HELP;
8154
8155         endrec = strtoll(argv[3], NULL, 10);
8156
8157         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
8158
8159         if (rc == -EINVAL)
8160                 fprintf(stderr, "%s: record out of range: %llu\n",
8161                         argv[0], endrec);
8162         else if (rc == -ENOENT)
8163                 fprintf(stderr, "%s: no changelog user: %s\n",
8164                         argv[0], argv[2]);
8165         else if (rc)
8166                 fprintf(stderr, "%s error: %s\n", argv[0],
8167                         strerror(-rc));
8168
8169         if (rc)
8170                 errno = -rc;
8171
8172         return rc;
8173 }
8174
8175 static int lfs_fid2path(int argc, char **argv)
8176 {
8177         struct option long_opts[] = {
8178                 { .val = 'c',   .name = "cur",  .has_arg = no_argument },
8179                 { .val = 'l',   .name = "link", .has_arg = required_argument },
8180                 { .val = 'r',   .name = "rec",  .has_arg = required_argument },
8181                 { .name = NULL } };
8182         char short_opts[] = "cl:r:";
8183         char mntdir[PATH_MAX];
8184         char *device, *fid, *path, *rootpath;
8185         long long recno = -1;
8186         int linkno = -1;
8187         int lnktmp;
8188         int printcur = 0;
8189         int rc = 0;
8190         char *endptr = NULL;
8191
8192         while ((rc = getopt_long(argc, argv, short_opts,
8193                 long_opts, NULL)) != -1) {
8194                 switch (rc) {
8195                 case 'c':
8196                         printcur++;
8197                         break;
8198                 case 'l':
8199                         linkno = strtol(optarg, &endptr, 10);
8200                         if (*endptr != '\0') {
8201                                 fprintf(stderr,
8202                                         "%s fid2path: invalid linkno '%s'\n",
8203                                         progname, optarg);
8204                                 return CMD_HELP;
8205                         }
8206                         break;
8207                 case 'r':
8208                         recno = strtoll(optarg, &endptr, 10);
8209                         if (*endptr != '\0') {
8210                                 fprintf(stderr,
8211                                         "%s fid2path: invalid recno '%s'\n",
8212                                         progname, optarg);
8213                                 return CMD_HELP;
8214                         }
8215                         break;
8216                 default:
8217                         fprintf(stderr,
8218                                 "%s fid2path: unrecognized option '%s'\n",
8219                                 progname, argv[optind - 1]);
8220                         return CMD_HELP;
8221                 }
8222         }
8223
8224         if (argc < 3) {
8225                 fprintf(stderr,
8226                         "%s fid2path: <fsname|rootpath> and <fid>... must be specified\n",
8227                         progname);
8228                 return CMD_HELP;
8229         }
8230
8231         device = argv[optind++];
8232         path = calloc(1, PATH_MAX);
8233         if (!path) {
8234                 rc = -errno;
8235                 fprintf(stderr,
8236                         "%s fid2path: cannot allocate memory for path: %s\n",
8237                         progname, strerror(-rc));
8238                 return rc;
8239         }
8240
8241         rc = 0;
8242         /* in case that device is not the mountpoint */
8243         if (device[0] == '/') {
8244                 rc = llapi_search_mounts(device, 0, mntdir, NULL);
8245                 if (rc == 0) {
8246                         rootpath = mntdir;
8247                 } else {
8248                         fprintf(stderr,
8249                                 "%s fid2path: %s has no mountpoint: %s\n",
8250                                 progname, device, strerror(-rc));
8251                         goto out;
8252                 }
8253         }
8254         while (optind < argc) {
8255                 fid = argv[optind++];
8256
8257                 lnktmp = (linkno >= 0) ? linkno : 0;
8258                 while (1) {
8259                         int oldtmp = lnktmp;
8260                         long long rectmp = recno;
8261                         int rc2;
8262
8263                         rc2 = llapi_fid2path(device, fid, path, PATH_MAX,
8264                                              &rectmp, &lnktmp);
8265                         if (rc2 < 0) {
8266                                 fprintf(stderr,
8267                                         "%s fid2path: cannot find %s %s: %s\n",
8268                                         progname, device, fid,
8269                                         strerror(errno = -rc2));
8270                                 if (rc == 0)
8271                                         rc = rc2;
8272                                 break;
8273                         }
8274
8275                         if (printcur)
8276                                 fprintf(stdout, "%lld ", rectmp);
8277                         if (device[0] == '/') {
8278                                 fprintf(stdout, "%s", rootpath);
8279                                 if (rootpath[strlen(rootpath) - 1] != '/')
8280                                         fprintf(stdout, "/");
8281                         } else if (path[0] == '\0') {
8282                                 fprintf(stdout, "/");
8283                         }
8284                         fprintf(stdout, "%s\n", path);
8285
8286                         if (linkno >= 0)
8287                                 /* specified linkno */
8288                                 break;
8289                         if (oldtmp == lnktmp)
8290                                 /* no more links */
8291                                 break;
8292                 }
8293         }
8294 out:
8295         free(path);
8296         return rc;
8297 }
8298
8299 static int lfs_path2fid(int argc, char **argv)
8300 {
8301         struct option long_opts[] = {
8302                 { .val = 'p', .name = "parents", .has_arg = no_argument },
8303                 { .name = NULL } };
8304         char            **path;
8305         const char        short_opts[] = "p";
8306         const char       *sep = "";
8307         struct lu_fid     fid;
8308         int               rc = 0;
8309         bool              show_parents = false;
8310
8311         while ((rc = getopt_long(argc, argv, short_opts,
8312                                  long_opts, NULL)) != -1) {
8313                 switch (rc) {
8314                 case 'p':
8315                         show_parents = true;
8316                         break;
8317                 default:
8318                         fprintf(stderr,
8319                                 "%s path2fid: unrecognized option '%s'\n",
8320                                 progname, argv[optind - 1]);
8321                         return CMD_HELP;
8322                 }
8323         }
8324
8325         if (optind > argc - 1) {
8326                 fprintf(stderr, "%s path2fid: FILE... must be specified\n",
8327                         progname);
8328                 return CMD_HELP;
8329         } else if (optind < argc - 1) {
8330                 sep = ": ";
8331         }
8332
8333         rc = 0;
8334         for (path = argv + optind; *path != NULL; path++) {
8335                 int err = 0;
8336
8337                 if (!show_parents) {
8338                         err = llapi_path2fid(*path, &fid);
8339                         if (!err)
8340                                 printf("%s%s"DFID"\n",
8341                                        *sep != '\0' ? *path : "", sep,
8342                                        PFID(&fid));
8343                 } else {
8344                         char            name[NAME_MAX + 1];
8345                         unsigned int    linkno = 0;
8346
8347                         while ((err = llapi_path2parent(*path, linkno, &fid,
8348                                                 name, sizeof(name))) == 0) {
8349                                 if (*sep != '\0' && linkno == 0)
8350                                         printf("%s%s", *path, sep);
8351
8352                                 printf("%s"DFID"/%s", linkno != 0 ? "\t" : "",
8353                                        PFID(&fid), name);
8354                                 linkno++;
8355                         }
8356
8357                         /* err == -ENODATA is end-of-loop */
8358                         if (linkno > 0 && err == -ENODATA) {
8359                                 printf("\n");
8360                                 err = 0;
8361                         }
8362                 }
8363
8364                 if (err) {
8365                         fprintf(stderr,
8366                                 "%s path2fid: cannot get %sfid for '%s': %s\n",
8367                                 progname, show_parents ? "parent " : "", *path,
8368                                 strerror(-err));
8369                         if (rc == 0) {
8370                                 rc = err;
8371                                 errno = -err;
8372                         }
8373                 }
8374         }
8375
8376         return rc;
8377 }
8378
8379 #define MAX_ERRNO       4095
8380 #define IS_ERR_VALUE(x) ((unsigned long)(x) >= (unsigned long)-MAX_ERRNO)
8381
8382 static int lfs_rmfid_and_show_errors(const char *device, struct fid_array *fa)
8383 {
8384         int rc, rc2 = 0, k;
8385
8386         rc = llapi_rmfid(device, fa);
8387         if (rc) {
8388                 fprintf(stderr, "rmfid(): rc = %d\n", rc);
8389                 return rc;
8390         }
8391
8392         for (k = 0; k < fa->fa_nr; k++) {
8393                 rc = (__s32)fa->fa_fids[k].f_ver;
8394                 if (!IS_ERR_VALUE(rc))
8395                         continue;
8396                 if (!rc2 && rc)
8397                         rc2 = rc;
8398                 if (!rc)
8399                         continue;
8400                 fa->fa_fids[k].f_ver = 0;
8401                 fprintf(stderr, "rmfid("DFID"): rc = %d\n",
8402                         PFID(&fa->fa_fids[k]), rc);
8403         }
8404
8405         return rc2;
8406 }
8407
8408 static int lfs_rmfid(int argc, char **argv)
8409 {
8410         char *fidstr, *device;
8411         int rc = 0, rc2, nr;
8412         struct fid_array *fa;
8413
8414         if (optind > argc - 1) {
8415                 fprintf(stderr, "%s rmfid: missing dirname\n", progname);
8416                 return CMD_HELP;
8417         }
8418
8419         device = argv[optind++];
8420
8421         nr = argc - optind;
8422         fa = malloc(offsetof(struct fid_array, fa_fids[nr + 1]));
8423         if (!fa)
8424                 return -ENOMEM;
8425
8426         fa->fa_nr = 0;
8427         rc = 0;
8428         while (optind < argc) {
8429                 int found;
8430
8431                 fidstr = argv[optind++];
8432                 while (*fidstr == '[')
8433                         fidstr++;
8434                 found = sscanf(fidstr, SFID, RFID(&fa->fa_fids[fa->fa_nr]));
8435                 if (found != 3) {
8436                         fprintf(stderr, "unrecognized FID: %s\n",
8437                                 argv[optind - 1]);
8438                         exit(1);
8439                 }
8440                 fa->fa_nr++;
8441                 if (fa->fa_nr == OBD_MAX_FIDS_IN_ARRAY) {
8442                         /* start another batch */
8443                         rc2 = lfs_rmfid_and_show_errors(device, fa);
8444                         if (rc2 && !rc)
8445                                 rc = rc2;
8446                         fa->fa_nr = 0;
8447                 }
8448         }
8449         if (fa->fa_nr) {
8450                 rc2 = lfs_rmfid_and_show_errors(device, fa);
8451                 if (rc2 && !rc)
8452                         rc = rc2;
8453         }
8454
8455         return rc;
8456 }
8457
8458 static int lfs_data_version(int argc, char **argv)
8459 {
8460         char *path;
8461         __u64 data_version;
8462         int fd;
8463         int rc;
8464         int c;
8465         int data_version_flags = LL_DV_RD_FLUSH; /* Read by default */
8466
8467         if (argc < 2) {
8468                 fprintf(stderr, "%s data_version: FILE must be specified\n",
8469                         progname);
8470                 return CMD_HELP;
8471         }
8472
8473         while ((c = getopt(argc, argv, "nrw")) != -1) {
8474                 switch (c) {
8475                 case 'n':
8476                         data_version_flags = 0;
8477                         break;
8478                 case 'r':
8479                         data_version_flags |= LL_DV_RD_FLUSH;
8480                         break;
8481                 case 'w':
8482                         data_version_flags |= LL_DV_WR_FLUSH;
8483                         break;
8484                 default:
8485                         fprintf(stderr,
8486                                 "%s data_version: unrecognized option '%s'\n",
8487                                 progname, argv[optind - 1]);
8488                         return CMD_HELP;
8489                 }
8490         }
8491         if (optind == argc) {
8492                 fprintf(stderr, "%s data_version: FILE must be specified\n",
8493                         progname);
8494                 return CMD_HELP;
8495         }
8496
8497         path = argv[optind];
8498         fd = open(path, O_RDONLY);
8499         if (fd < 0) {
8500                 rc = -errno;
8501                 fprintf(stderr, "%s data_version: cannot open file '%s': %s\n",
8502                         progname, path, strerror(-rc));
8503                 return rc;
8504         }
8505
8506         rc = llapi_get_data_version(fd, &data_version, data_version_flags);
8507         if (rc < 0)
8508                 fprintf(stderr,
8509                         "%s data_version: cannot get version for '%s': %s\n",
8510                         progname, path, strerror(-rc));
8511         else
8512                 printf("%ju" "\n", (uintmax_t)data_version);
8513
8514         close(fd);
8515         return rc;
8516 }
8517
8518 static int lfs_hsm_state(int argc, char **argv)
8519 {
8520         int rc;
8521         int i = 1;
8522         char *path;
8523         struct hsm_user_state hus;
8524
8525         if (argc < 2)
8526                 return CMD_HELP;
8527
8528         do {
8529                 path = argv[i];
8530
8531                 rc = llapi_hsm_state_get(path, &hus);
8532                 if (rc) {
8533                         fprintf(stderr, "can't get hsm state for %s: %s\n",
8534                                 path, strerror(errno = -rc));
8535                         return rc;
8536                 }
8537
8538                 /* Display path name and status flags */
8539                 printf("%s: (0x%08x)", path, hus.hus_states);
8540
8541                 if (hus.hus_states & HS_RELEASED)
8542                         printf(" released");
8543                 if (hus.hus_states & HS_EXISTS)
8544                         printf(" exists");
8545                 if (hus.hus_states & HS_DIRTY)
8546                         printf(" dirty");
8547                 if (hus.hus_states & HS_ARCHIVED)
8548                         printf(" archived");
8549                 /* Display user-settable flags */
8550                 if (hus.hus_states & HS_NORELEASE)
8551                         printf(" never_release");
8552                 if (hus.hus_states & HS_NOARCHIVE)
8553                         printf(" never_archive");
8554                 if (hus.hus_states & HS_LOST)
8555                         printf(" lost_from_hsm");
8556
8557                 if (hus.hus_archive_id != 0)
8558                         printf(", archive_id:%d", hus.hus_archive_id);
8559                 printf("\n");
8560
8561         } while (++i < argc);
8562
8563         return 0;
8564 }
8565
8566 #define LFS_HSM_SET   0
8567 #define LFS_HSM_CLEAR 1
8568
8569 /**
8570  * Generic function to set or clear HSM flags.
8571  * Used by hsm_set and hsm_clear.
8572  *
8573  * @mode  if LFS_HSM_SET, set the flags, if LFS_HSM_CLEAR, clear the flags.
8574  */
8575 static int lfs_hsm_change_flags(int argc, char **argv, int mode)
8576 {
8577         struct option long_opts[] = {
8578         { .val = 'A',   .name = "archived",     .has_arg = no_argument },
8579         { .val = 'a',   .name = "noarchive",    .has_arg = no_argument },
8580         { .val = 'd',   .name = "dirty",        .has_arg = no_argument },
8581         { .val = 'e',   .name = "exists",       .has_arg = no_argument },
8582         { .val = 'l',   .name = "lost",         .has_arg = no_argument },
8583         { .val = 'r',   .name = "norelease",    .has_arg = no_argument },
8584         { .val = 'i',   .name = "archive-id",   .has_arg = required_argument },
8585         { .name = NULL } };
8586         char short_opts[] = "lraAdei:";
8587         __u64 mask = 0;
8588         int c, rc;
8589         char *path;
8590         __u32 archive_id = 0;
8591         char *end = NULL;
8592
8593         if (argc < 3)
8594                 return CMD_HELP;
8595
8596         while ((c = getopt_long(argc, argv, short_opts,
8597                                 long_opts, NULL)) != -1) {
8598                 switch (c) {
8599                 case 'l':
8600                         mask |= HS_LOST;
8601                         break;
8602                 case 'a':
8603                         mask |= HS_NOARCHIVE;
8604                         break;
8605                 case 'A':
8606                         mask |= HS_ARCHIVED;
8607                         break;
8608                 case 'r':
8609                         mask |= HS_NORELEASE;
8610                         break;
8611                 case 'd':
8612                         mask |= HS_DIRTY;
8613                         break;
8614                 case 'e':
8615                         mask |= HS_EXISTS;
8616                         break;
8617                 case 'i':
8618                         archive_id = strtol(optarg, &end, 10);
8619                         if (*end != '\0') {
8620                                 fprintf(stderr, "invalid archive_id: '%s'\n",
8621                                         end);
8622                                 return CMD_HELP;
8623                         }
8624                         break;
8625                 case '?':
8626                         return CMD_HELP;
8627                 default:
8628                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
8629                                 argv[0], argv[optind - 1]);
8630                         return CMD_HELP;
8631                 }
8632         }
8633
8634         /* User should have specified a flag */
8635         if (mask == 0)
8636                 return CMD_HELP;
8637
8638         while (optind < argc) {
8639                 path = argv[optind];
8640
8641                 /* If mode == 0, this means we apply the mask. */
8642                 if (mode == LFS_HSM_SET)
8643                         rc = llapi_hsm_state_set(path, mask, 0, archive_id);
8644                 else
8645                         rc = llapi_hsm_state_set(path, 0, mask, 0);
8646
8647                 if (rc != 0) {
8648                         fprintf(stderr, "Can't change hsm flags for %s: %s\n",
8649                                 path, strerror(errno = -rc));
8650                         return rc;
8651                 }
8652                 optind++;
8653         }
8654
8655         return 0;
8656 }
8657
8658 static int lfs_hsm_action(int argc, char **argv)
8659 {
8660         int                              rc;
8661         int                              i = 1;
8662         char                            *path;
8663         struct hsm_current_action        hca;
8664         struct hsm_extent                he;
8665         enum hsm_user_action             hua;
8666         enum hsm_progress_states         hps;
8667
8668         if (argc < 2)
8669                 return CMD_HELP;
8670
8671         do {
8672                 path = argv[i];
8673
8674                 rc = llapi_hsm_current_action(path, &hca);
8675                 if (rc) {
8676                         fprintf(stderr, "can't get hsm action for %s: %s\n",
8677                                 path, strerror(errno = -rc));
8678                         return rc;
8679                 }
8680                 he = hca.hca_location;
8681                 hua = hca.hca_action;
8682                 hps = hca.hca_state;
8683
8684                 printf("%s: %s", path, hsm_user_action2name(hua));
8685
8686                 /* Skip file without action */
8687                 if (hca.hca_action == HUA_NONE) {
8688                         printf("\n");
8689                         continue;
8690                 }
8691
8692                 printf(" %s ", hsm_progress_state2name(hps));
8693
8694                 if ((hps == HPS_RUNNING) &&
8695                     (hua == HUA_ARCHIVE || hua == HUA_RESTORE))
8696                         printf("(%llu bytes moved)\n",
8697                                (unsigned long long)he.length);
8698                 else if ((he.offset + he.length) == LUSTRE_EOF)
8699                         printf("(from %llu to EOF)\n",
8700                                (unsigned long long)he.offset);
8701                 else
8702                         printf("(from %llu to %llu)\n",
8703                                (unsigned long long)he.offset,
8704                                (unsigned long long)(he.offset + he.length));
8705
8706         } while (++i < argc);
8707
8708         return 0;
8709 }
8710
8711 static int lfs_hsm_set(int argc, char **argv)
8712 {
8713         return lfs_hsm_change_flags(argc, argv, LFS_HSM_SET);
8714 }
8715
8716 static int lfs_hsm_clear(int argc, char **argv)
8717 {
8718         return lfs_hsm_change_flags(argc, argv, LFS_HSM_CLEAR);
8719 }
8720
8721 /**
8722  * Check file state and return its fid, to be used by lfs_hsm_request().
8723  *
8724  * \param[in]     file      Path to file to check
8725  * \param[in,out] fid       Pointer to allocated lu_fid struct.
8726  * \param[in,out] last_dev  Pointer to last device id used.
8727  *
8728  * \return 0 on success.
8729  */
8730 static int lfs_hsm_prepare_file(const char *file, struct lu_fid *fid,
8731                                 dev_t *last_dev)
8732 {
8733         struct stat     st;
8734         int             rc;
8735
8736         rc = lstat(file, &st);
8737         if (rc) {
8738                 fprintf(stderr, "Cannot stat %s: %s\n", file, strerror(errno));
8739                 return -errno;
8740         }
8741         /*
8742          * Checking for regular file as archiving as posix copytool
8743          * rejects archiving files other than regular files
8744          */
8745         if (!S_ISREG(st.st_mode)) {
8746                 fprintf(stderr, "error: \"%s\" is not a regular file\n", file);
8747                 return CMD_HELP;
8748         }
8749         /* A request should be ... */
8750         if (*last_dev != st.st_dev && *last_dev != 0) {
8751                 fprintf(stderr,
8752                         "All files should be on the same filesystem: %s\n",
8753                         file);
8754                 return -EINVAL;
8755         }
8756         *last_dev = st.st_dev;
8757
8758         rc = llapi_path2fid(file, fid);
8759         if (rc) {
8760                 fprintf(stderr, "Cannot read FID of %s: %s\n",
8761                         file, strerror(-rc));
8762                 return rc;
8763         }
8764         return 0;
8765 }
8766
8767 /* Fill an HSM HUR item with a given file name.
8768  *
8769  * If mntpath is set, then the filename is actually a FID, and no
8770  * lookup on the filesystem will be performed.
8771  *
8772  * \param[in]  hur         the user request to fill
8773  * \param[in]  idx         index of the item inside the HUR to fill
8774  * \param[in]  mntpath     mountpoint of Lustre
8775  * \param[in]  fname       filename (if mtnpath is NULL)
8776  *                         or FID (if mntpath is set)
8777  * \param[in]  last_dev    pointer to last device id used
8778  *
8779  * \retval 0 on success
8780  * \retval CMD_HELP or a negative errno on error
8781  */
8782 static int fill_hur_item(struct hsm_user_request *hur, unsigned int idx,
8783                          const char *mntpath, const char *fname,
8784                          dev_t *last_dev)
8785 {
8786         struct hsm_user_item *hui = &hur->hur_user_item[idx];
8787         int rc;
8788
8789         hui->hui_extent.length = -1;
8790
8791         if (mntpath) {
8792                 rc = llapi_fid_parse(fname, &hui->hui_fid, NULL);
8793                 if (rc)
8794                         fprintf(stderr, "hsm: '%s' is not a valid FID\n",
8795                                 fname);
8796         } else {
8797                 rc = lfs_hsm_prepare_file(fname, &hui->hui_fid, last_dev);
8798         }
8799
8800         if (rc == 0)
8801                 hur->hur_request.hr_itemcount++;
8802
8803         return rc;
8804 }
8805
8806 static int lfs_hsm_request(int argc, char **argv, int action)
8807 {
8808         struct option long_opts[] = {
8809         { .val = 'a',   .name = "archive",      .has_arg = required_argument },
8810         { .val = 'D',   .name = "data",         .has_arg = required_argument },
8811         { .val = 'l',   .name = "filelist",     .has_arg = required_argument },
8812         { .val = 'm',   .name = "mntpath",      .has_arg = required_argument },
8813         { .name = NULL } };
8814         dev_t last_dev = 0;
8815         char short_opts[] = "l:D:a:m:";
8816         struct hsm_user_request *hur, *oldhur;
8817         int c, i;
8818         size_t len;
8819         int nbfile;
8820         char *line = NULL;
8821         char *filelist = NULL;
8822         char fullpath[PATH_MAX];
8823         char *opaque = NULL;
8824         int opaque_len = 0;
8825         int archive_id = 0;
8826         FILE *fp;
8827         int nbfile_alloc = 0;
8828         char *some_file = NULL;
8829         char *mntpath = NULL;
8830         int rc;
8831
8832         if (argc < 2)
8833                 return CMD_HELP;
8834
8835         while ((c = getopt_long(argc, argv, short_opts,
8836                                 long_opts, NULL)) != -1) {
8837                 switch (c) {
8838                 case 'l':
8839                         filelist = optarg;
8840                         break;
8841                 case 'D':
8842                         opaque = optarg;
8843                         break;
8844                 case 'a':
8845                         if (action != HUA_ARCHIVE &&
8846                             action != HUA_REMOVE) {
8847                                 fprintf(stderr,
8848                                         "error: -a is supported only when archiving or removing\n");
8849                                 return CMD_HELP;
8850                         }
8851                         archive_id = atoi(optarg);
8852                         break;
8853                 case 'm':
8854                         if (!some_file) {
8855                                 mntpath = optarg;
8856                                 some_file = strdup(optarg);
8857                         }
8858                         break;
8859                 case '?':
8860                         return CMD_HELP;
8861                 default:
8862                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
8863                                 argv[0], argv[optind - 1]);
8864                         return CMD_HELP;
8865                 }
8866         }
8867
8868         /* All remaining args are files, so we have at least nbfile */
8869         nbfile = argc - optind;
8870
8871         if ((nbfile == 0) && (!filelist))
8872                 return CMD_HELP;
8873
8874         if (opaque)
8875                 opaque_len = strlen(opaque);
8876
8877         /*
8878          * Alloc the request structure with enough place to store all files
8879          * from command line.
8880          */
8881         hur = llapi_hsm_user_request_alloc(nbfile, opaque_len);
8882         if (!hur) {
8883                 fprintf(stderr, "Cannot create the request: %s\n",
8884                         strerror(errno));
8885                 return errno;
8886         }
8887         nbfile_alloc = nbfile;
8888
8889         hur->hur_request.hr_action = action;
8890         hur->hur_request.hr_archive_id = archive_id;
8891         hur->hur_request.hr_flags = 0;
8892
8893         /* All remaining args are files, add them */
8894         if (nbfile != 0 && some_file == NULL)
8895                 some_file = strdup(argv[optind]);
8896
8897         for (i = 0; i < nbfile; i++) {
8898                 rc = fill_hur_item(hur, i, mntpath, argv[optind + i],
8899                                    &last_dev);
8900                 if (rc)
8901                         goto out_free;
8902         }
8903
8904         /* from here stop using nb_file, use hur->hur_request.hr_itemcount */
8905
8906         /* If a filelist was specified, read the filelist from it. */
8907         if (filelist) {
8908                 fp = fopen(filelist, "r");
8909                 if (!fp) {
8910                         fprintf(stderr, "Cannot read the file list %s: %s\n",
8911                                 filelist, strerror(errno));
8912                         rc = -errno;
8913                         goto out_free;
8914                 }
8915
8916                 while ((rc = getline(&line, &len, fp)) != -1) {
8917                         /*
8918                          * If allocated buffer was too small, get something
8919                          * larger
8920                          */
8921                         if (nbfile_alloc <= hur->hur_request.hr_itemcount) {
8922                                 ssize_t size;
8923
8924                                 nbfile_alloc = nbfile_alloc * 2 + 1;
8925                                 oldhur = hur;
8926                                 hur = llapi_hsm_user_request_alloc(nbfile_alloc,
8927                                                                    opaque_len);
8928                                 if (!hur) {
8929                                         fprintf(stderr,
8930                                                 "hsm: cannot allocate the request: %s\n",
8931                                                 strerror(errno));
8932                                         hur = oldhur;
8933                                         rc = -errno;
8934                                         fclose(fp);
8935                                         goto out_free;
8936                                 }
8937                                 size = hur_len(oldhur);
8938                                 if (size < 0) {
8939                                         fprintf(stderr,
8940                                                 "hsm: cannot allocate %u files + %u bytes data\n",
8941                                                 oldhur->hur_request.hr_itemcount,
8942                                                 oldhur->hur_request.hr_data_len);
8943                                         free(hur);
8944                                         hur = oldhur;
8945                                         rc = -E2BIG;
8946                                         fclose(fp);
8947                                         goto out_free;
8948                                 }
8949                                 memcpy(hur, oldhur, size);
8950                                 free(oldhur);
8951                         }
8952
8953                         /* Chop CR */
8954                         if (line[strlen(line) - 1] == '\n')
8955                                 line[strlen(line) - 1] = '\0';
8956
8957                         rc = fill_hur_item(hur, hur->hur_request.hr_itemcount,
8958                                            mntpath, line, &last_dev);
8959                         if (rc) {
8960                                 fclose(fp);
8961                                 goto out_free;
8962                         }
8963
8964                         if (!some_file) {
8965                                 some_file = line;
8966                                 line = NULL;
8967                         }
8968                 }
8969
8970                 rc = fclose(fp);
8971                 free(line);
8972         }
8973
8974         /* If a --data was used, add it to the request */
8975         hur->hur_request.hr_data_len = opaque_len;
8976         if (opaque)
8977                 memcpy(hur_data(hur), opaque, opaque_len);
8978
8979         /* Send the HSM request */
8980         if (realpath(some_file, fullpath) == NULL) {
8981                 fprintf(stderr, "Could not find path '%s': %s\n",
8982                         some_file, strerror(errno));
8983         }
8984         rc = llapi_hsm_request(fullpath, hur);
8985         if (rc) {
8986                 fprintf(stderr, "Cannot send HSM request (use of %s): %s\n",
8987                         some_file, strerror(-rc));
8988                 goto out_free;
8989         }
8990
8991 out_free:
8992         free(some_file);
8993         free(hur);
8994         return rc;
8995 }
8996
8997 static int lfs_hsm_archive(int argc, char **argv)
8998 {
8999         return lfs_hsm_request(argc, argv, HUA_ARCHIVE);
9000 }
9001
9002 static int lfs_hsm_restore(int argc, char **argv)
9003 {
9004         return lfs_hsm_request(argc, argv, HUA_RESTORE);
9005 }
9006
9007 static int lfs_hsm_release(int argc, char **argv)
9008 {
9009         return lfs_hsm_request(argc, argv, HUA_RELEASE);
9010 }
9011
9012 static int lfs_hsm_remove(int argc, char **argv)
9013 {
9014         return lfs_hsm_request(argc, argv, HUA_REMOVE);
9015 }
9016
9017 static int lfs_hsm_cancel(int argc, char **argv)
9018 {
9019         return lfs_hsm_request(argc, argv, HUA_CANCEL);
9020 }
9021
9022 static int lfs_swap_layouts(int argc, char **argv)
9023 {
9024         if (argc != 3)
9025                 return CMD_HELP;
9026
9027         return llapi_swap_layouts(argv[1], argv[2], 0, 0,
9028                                   SWAP_LAYOUTS_KEEP_MTIME |
9029                                   SWAP_LAYOUTS_KEEP_ATIME);
9030 }
9031
9032 static const char *const ladvise_names[] = LU_LADVISE_NAMES;
9033
9034 static const char *const lock_mode_names[] = LOCK_MODE_NAMES;
9035
9036 int lfs_get_mode(const char *string)
9037 {
9038         enum lock_mode_user mode;
9039
9040         for (mode = 0; mode < ARRAY_SIZE(lock_mode_names); mode++) {
9041                 if (lock_mode_names[mode] == NULL)
9042                         continue;
9043                 if (strcmp(string, lock_mode_names[mode]) == 0)
9044                         return mode;
9045         }
9046
9047         return -EINVAL;
9048 }
9049
9050 static enum lu_ladvise_type lfs_get_ladvice(const char *string)
9051 {
9052         enum lu_ladvise_type advice;
9053
9054         for (advice = 0;
9055              advice < ARRAY_SIZE(ladvise_names); advice++) {
9056                 if (ladvise_names[advice] == NULL)
9057                         continue;
9058                 if (strcmp(string, ladvise_names[advice]) == 0)
9059                         return advice;
9060         }
9061
9062         return LU_LADVISE_INVALID;
9063 }
9064
9065 static int lfs_ladvise(int argc, char **argv)
9066 {
9067         struct option long_opts[] = {
9068         { .val = 'a',   .name = "advice",       .has_arg = required_argument },
9069         { .val = 'b',   .name = "background",   .has_arg = no_argument },
9070         { .val = 'e',   .name = "end",          .has_arg = required_argument },
9071         { .val = 'l',   .name = "length",       .has_arg = required_argument },
9072         { .val = 'm',   .name = "mode",         .has_arg = required_argument },
9073         { .val = 's',   .name = "start",        .has_arg = required_argument },
9074         { .val = 'u',   .name = "unset",        .has_arg = no_argument },
9075         { .name = NULL } };
9076         char                     short_opts[] = "a:be:l:m:s:u";
9077         int                      c;
9078         int                      rc = 0;
9079         const char              *path;
9080         int                      fd;
9081         struct llapi_lu_ladvise  advice;
9082         enum lu_ladvise_type     advice_type = LU_LADVISE_INVALID;
9083         unsigned long long       start = 0;
9084         unsigned long long       end = LUSTRE_EOF;
9085         unsigned long long       length = 0;
9086         unsigned long long       size_units;
9087         unsigned long long       flags = 0;
9088         int                      mode = 0;
9089
9090         optind = 0;
9091         while ((c = getopt_long(argc, argv, short_opts,
9092                                 long_opts, NULL)) != -1) {
9093                 switch (c) {
9094                 case 'a':
9095                         advice_type = lfs_get_ladvice(optarg);
9096                         if (advice_type == LU_LADVISE_INVALID) {
9097                                 fprintf(stderr,
9098                                         "%s: invalid advice type '%s'\n",
9099                                         argv[0], optarg);
9100                                 fprintf(stderr, "Valid types:");
9101
9102                                 for (advice_type = 0;
9103                                      advice_type < ARRAY_SIZE(ladvise_names);
9104                                      advice_type++) {
9105                                         if (ladvise_names[advice_type] == NULL)
9106                                                 continue;
9107                                         fprintf(stderr, " %s",
9108                                                 ladvise_names[advice_type]);
9109                                 }
9110                                 fprintf(stderr, "\n");
9111
9112                                 return CMD_HELP;
9113                         }
9114                         break;
9115                 case 'b':
9116                         flags |= LF_ASYNC;
9117                         break;
9118                 case 'u':
9119                         flags |= LF_UNSET;
9120                         break;
9121                 case 'e':
9122                         size_units = 1;
9123                         rc = llapi_parse_size(optarg, &end,
9124                                               &size_units, 0);
9125                         if (rc) {
9126                                 fprintf(stderr, "%s: bad end offset '%s'\n",
9127                                         argv[0], optarg);
9128                                 return CMD_HELP;
9129                         }
9130                         break;
9131                 case 's':
9132                         size_units = 1;
9133                         rc = llapi_parse_size(optarg, &start,
9134                                               &size_units, 0);
9135                         if (rc) {
9136                                 fprintf(stderr,
9137                                         "%s: bad start offset '%s'\n",
9138                                         argv[0], optarg);
9139                                 return CMD_HELP;
9140                         }
9141                         break;
9142                 case 'l':
9143                         size_units = 1;
9144                         rc = llapi_parse_size(optarg, &length,
9145                                               &size_units, 0);
9146                         if (rc) {
9147                                 fprintf(stderr, "%s: bad length '%s'\n",
9148                                         argv[0], optarg);
9149                                 return CMD_HELP;
9150                         }
9151                         break;
9152                 case 'm':
9153                         mode = lfs_get_mode(optarg);
9154                         if (mode < 0) {
9155                                 fprintf(stderr,
9156                                         "%s: bad mode '%s', valid modes are READ or WRITE\n",
9157                                         argv[0], optarg);
9158                                 return CMD_HELP;
9159                         }
9160                         break;
9161                 case '?':
9162                         return CMD_HELP;
9163                 default:
9164                         fprintf(stderr, "%s: option '%s' unrecognized\n",
9165                                 argv[0], argv[optind - 1]);
9166                         return CMD_HELP;
9167                 }
9168         }
9169
9170         if (advice_type == LU_LADVISE_INVALID) {
9171                 fprintf(stderr, "%s: please give an advice type\n", argv[0]);
9172                 fprintf(stderr, "Valid types:");
9173                 for (advice_type = 0; advice_type < ARRAY_SIZE(ladvise_names);
9174                      advice_type++) {
9175                         if (ladvise_names[advice_type] == NULL)
9176                                 continue;
9177                         fprintf(stderr, " %s", ladvise_names[advice_type]);
9178                 }
9179                 fprintf(stderr, "\n");
9180                 return CMD_HELP;
9181         }
9182
9183         if (advice_type == LU_LADVISE_LOCKNOEXPAND) {
9184                 fprintf(stderr,
9185                         "%s: Lock no expand advice is a per file descriptor advice, so when called from lfs, it does nothing.\n",
9186                         argv[0]);
9187                 return CMD_HELP;
9188         }
9189
9190         if (argc <= optind) {
9191                 fprintf(stderr, "%s: please give one or more file names\n",
9192                         argv[0]);
9193                 return CMD_HELP;
9194         }
9195
9196         if (end != LUSTRE_EOF && length != 0 && end != start + length) {
9197                 fprintf(stderr, "%s: conflicting arguments of -l and -e\n",
9198                         argv[0]);
9199                 return CMD_HELP;
9200         }
9201
9202         if (end == LUSTRE_EOF && length != 0)
9203                 end = start + length;
9204
9205         if (end <= start) {
9206                 fprintf(stderr, "%s: range [%llu, %llu] is invalid\n",
9207                         argv[0], start, end);
9208                 return CMD_HELP;
9209         }
9210
9211         if (advice_type != LU_LADVISE_LOCKAHEAD && mode != 0) {
9212                 fprintf(stderr, "%s: mode is only valid with lockahead\n",
9213                         argv[0]);
9214                 return CMD_HELP;
9215         }
9216
9217         if (advice_type == LU_LADVISE_LOCKAHEAD && mode == 0) {
9218                 fprintf(stderr, "%s: mode is required with lockahead\n",
9219                         argv[0]);
9220                 return CMD_HELP;
9221         }
9222
9223         while (optind < argc) {
9224                 int rc2;
9225
9226                 path = argv[optind++];
9227
9228                 fd = open(path, O_RDONLY);
9229                 if (fd < 0) {
9230                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
9231                                 argv[0], path, strerror(errno));
9232                         rc2 = -errno;
9233                         goto next;
9234                 }
9235
9236                 advice.lla_start = start;
9237                 advice.lla_end = end;
9238                 advice.lla_advice = advice_type;
9239                 advice.lla_value1 = 0;
9240                 advice.lla_value2 = 0;
9241                 advice.lla_value3 = 0;
9242                 advice.lla_value4 = 0;
9243                 if (advice_type == LU_LADVISE_LOCKAHEAD) {
9244                         advice.lla_lockahead_mode = mode;
9245                         advice.lla_peradvice_flags = flags;
9246                 }
9247
9248                 rc2 = llapi_ladvise(fd, flags, 1, &advice);
9249                 close(fd);
9250                 if (rc2 < 0) {
9251                         fprintf(stderr,
9252                                 "%s: cannot give advice '%s' to file '%s': %s\n",
9253                                 argv[0], ladvise_names[advice_type],
9254                                 path, strerror(errno));
9255
9256                         goto next;
9257                 }
9258
9259 next:
9260                 if (rc == 0 && rc2 < 0)
9261                         rc = rc2;
9262         }
9263         return rc;
9264 }
9265
9266 static const char *const heat_names[] = LU_HEAT_NAMES;
9267
9268 static int lfs_heat_get(int argc, char **argv)
9269 {
9270         struct lu_heat *heat;
9271         int rc = 0, rc2;
9272         char *path;
9273         int fd;
9274         int i;
9275
9276         if (argc <= 1)
9277                 return CMD_HELP;
9278
9279         heat = calloc(sizeof(*heat) + sizeof(__u64) * OBD_HEAT_COUNT, 1);
9280         if (!heat) {
9281                 fprintf(stderr, "%s: memory allocation failed\n", argv[0]);
9282                 return -ENOMEM;
9283         }
9284
9285         optind = 1;
9286         while (optind < argc) {
9287                 path = argv[optind++];
9288
9289                 fd = open(path, O_RDONLY);
9290                 if (fd < 0) {
9291                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
9292                                 argv[0], path, strerror(errno));
9293                         rc2 = -errno;
9294                         goto next;
9295                 }
9296
9297                 heat->lh_count = OBD_HEAT_COUNT;
9298                 rc2 = llapi_heat_get(fd, heat);
9299                 close(fd);
9300                 if (rc2 < 0) {
9301                         fprintf(stderr,
9302                                 "%s: cannot get heat of file '%s': %s\n",
9303                                 argv[0], path, strerror(errno));
9304                         goto next;
9305                 }
9306
9307                 printf("flags: %x\n", heat->lh_flags);
9308                 for (i = 0; i < heat->lh_count; i++)
9309                         printf("%s: %llu\n", heat_names[i],
9310                                (unsigned long long)heat->lh_heat[i]);
9311 next:
9312                 if (rc == 0 && rc2 < 0)
9313                         rc = rc2;
9314         }
9315
9316         free(heat);
9317         return rc;
9318 }
9319
9320 static int lfs_heat_set(int argc, char **argv)
9321 {
9322         struct option long_opts[] = {
9323         { .val = 'c',   .name = "clear",        .has_arg = no_argument },
9324         { .val = 'o',   .name = "off",          .has_arg = no_argument },
9325         { .val = 'O',   .name = "on",           .has_arg = no_argument },
9326         { .name = NULL } };
9327         enum lu_heat_flag flags = 0;
9328         int rc = 0, rc2;
9329         char *path;
9330         int fd;
9331         int c;
9332
9333         if (argc <= 1)
9334                 return CMD_HELP;
9335
9336         optind = 0;
9337         while ((c = getopt_long(argc, argv, "coO", long_opts, NULL)) != -1) {
9338                 switch (c) {
9339                 case 'c':
9340                         flags |= LU_HEAT_FLAG_CLEAR;
9341                         break;
9342                 case 'o':
9343                         flags |= LU_HEAT_FLAG_CLEAR;
9344                         flags |= LU_HEAT_FLAG_OFF;
9345                         break;
9346                 case 'O':
9347                         flags &= ~LU_HEAT_FLAG_OFF;
9348                         break;
9349                 case '?':
9350                         return CMD_HELP;
9351                 default:
9352                         fprintf(stderr, "%s: option '%s' unrecognized\n",
9353                                 argv[0], argv[optind - 1]);
9354                         return CMD_HELP;
9355                 }
9356         }
9357
9358         if (argc <= optind) {
9359                 fprintf(stderr, "%s: please give one or more file names\n",
9360                         argv[0]);
9361                 return CMD_HELP;
9362         }
9363
9364         while (optind < argc) {
9365                 path = argv[optind++];
9366
9367                 fd = open(path, O_RDONLY);
9368                 if (fd < 0) {
9369                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
9370                                 argv[0], path, strerror(errno));
9371                         rc2 = -errno;
9372                         goto next;
9373                 }
9374
9375                 rc2 = llapi_heat_set(fd, flags);
9376                 close(fd);
9377                 if (rc2 < 0) {
9378                         fprintf(stderr,
9379                                 "%s: cannot setflags heat of file '%s': %s\n",
9380                                 argv[0], path, strerror(errno));
9381                         goto next;
9382                 }
9383 next:
9384                 if (rc == 0 && rc2 < 0)
9385                         rc = rc2;
9386         }
9387         return rc;
9388 }
9389
9390 /**
9391  * The input string contains a comma delimited list of component ids and
9392  * ranges, for example "1,2-4,7".
9393  */
9394 static int parse_mirror_ids(__u16 *ids, int size, char *arg)
9395 {
9396         bool end_of_loop = false;
9397         char *ptr = NULL;
9398         int nr = 0;
9399         int rc;
9400
9401         if (!arg)
9402                 return -EINVAL;
9403
9404         while (!end_of_loop) {
9405                 int start_index;
9406                 int end_index;
9407                 int i;
9408                 char *endptr = NULL;
9409
9410                 rc = -EINVAL;
9411                 ptr = strchrnul(arg, ',');
9412                 end_of_loop = *ptr == '\0';
9413                 *ptr = '\0';
9414
9415                 start_index = strtol(arg, &endptr, 0);
9416                 if (endptr == arg) /* no data at all */
9417                         break;
9418                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
9419                         break;
9420                 if (start_index < 0)
9421                         break;
9422
9423                 end_index = start_index;
9424                 if (*endptr == '-') {
9425                         end_index = strtol(endptr + 1, &endptr, 0);
9426                         if (*endptr != '\0')
9427                                 break;
9428                         if (end_index < start_index)
9429                                 break;
9430                 }
9431
9432                 for (i = start_index; i <= end_index && size > 0; i++) {
9433                         int j;
9434
9435                         /* remove duplicate */
9436                         for (j = 0; j < nr; j++) {
9437                                 if (ids[j] == i)
9438                                         break;
9439                         }
9440                         if (j == nr) { /* no duplicate */
9441                                 ids[nr++] = i;
9442                                 --size;
9443                         }
9444                 }
9445
9446                 if (size == 0 && i < end_index)
9447                         break;
9448
9449                 *ptr = ',';
9450                 arg = ++ptr;
9451                 rc = 0;
9452         }
9453         if (!end_of_loop && ptr)
9454                 *ptr = ',';
9455
9456         return rc < 0 ? rc : nr;
9457 }
9458
9459 /**
9460  * struct verify_mirror_id - Mirror id to be verified.
9461  * @mirror_id:   A specified mirror id.
9462  * @is_valid_id: @mirror_id is valid or not in the mirrored file.
9463  */
9464 struct verify_mirror_id {
9465         __u16 mirror_id;
9466         bool is_valid_id;
9467 };
9468
9469 /**
9470  * compare_mirror_ids() - Compare mirror ids.
9471  * @layout: Mirror component list.
9472  * @cbdata: Callback data in verify_mirror_id structure.
9473  *
9474  * This is a callback function called by llapi_layout_comp_iterate()
9475  * to compare the specified mirror id with the one in the current
9476  * component of @layout. If they are the same, then the specified
9477  * mirror id is valid.
9478  *
9479  * Return: a negative error code on failure or
9480  *         LLAPI_LAYOUT_ITER_CONT: Proceed iteration
9481  *         LLAPI_LAYOUT_ITER_STOP: Stop iteration
9482  */
9483 static inline
9484 int compare_mirror_ids(struct llapi_layout *layout, void *cbdata)
9485 {
9486         struct verify_mirror_id *mirror_id_cbdata =
9487                                  (struct verify_mirror_id *)cbdata;
9488         uint32_t mirror_id;
9489         int rc = 0;
9490
9491         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
9492         if (rc < 0) {
9493                 rc = -errno;
9494                 fprintf(stderr,
9495                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
9496                         progname, strerror(errno));
9497                 return rc;
9498         }
9499
9500         if (mirror_id_cbdata->mirror_id == mirror_id) {
9501                 mirror_id_cbdata->is_valid_id = true;
9502                 return LLAPI_LAYOUT_ITER_STOP;
9503         }
9504
9505         return LLAPI_LAYOUT_ITER_CONT;
9506 }
9507
9508 /**
9509  * verify_mirror_ids() - Verify specified mirror ids.
9510  * @fname:      Mirrored file name.
9511  * @mirror_ids: Specified mirror ids to be verified.
9512  * @ids_nr:     Number of specified mirror ids.
9513  *
9514  * This function verifies that specified @mirror_ids are valid
9515  * in the mirrored file @fname.
9516  *
9517  * Return: 0 on success or a negative error code on failure.
9518  */
9519 static inline
9520 int verify_mirror_ids(const char *fname, __u16 *mirror_ids, int ids_nr)
9521 {
9522         struct llapi_layout *layout = NULL;
9523         struct verify_mirror_id mirror_id_cbdata = { 0 };
9524         struct stat stbuf;
9525         uint32_t flr_state;
9526         int i;
9527         int fd;
9528         int rc = 0;
9529         int rc2 = 0;
9530
9531         if (ids_nr <= 0)
9532                 return -EINVAL;
9533
9534         if (stat(fname, &stbuf) < 0) {
9535                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
9536                         progname, fname, strerror(errno));
9537                 rc = -errno;
9538                 goto error;
9539         }
9540
9541         if (!S_ISREG(stbuf.st_mode)) {
9542                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
9543                         progname, fname);
9544                 rc = -EINVAL;
9545                 goto error;
9546         }
9547
9548         fd = open(fname, O_DIRECT | O_RDONLY);
9549         if (fd < 0) {
9550                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
9551                         progname, fname, strerror(errno));
9552                 rc = -errno;
9553                 goto error;
9554         }
9555
9556         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
9557         if (rc < 0) {
9558                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
9559                         progname, fname, strerror(errno));
9560                 goto close_fd;
9561         }
9562
9563         layout = llapi_layout_get_by_fd(fd, 0);
9564         if (!layout) {
9565                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
9566                         progname, fname, strerror(errno));
9567                 rc = -errno;
9568                 llapi_lease_release(fd);
9569                 goto close_fd;
9570         }
9571
9572         rc = llapi_layout_flags_get(layout, &flr_state);
9573         if (rc < 0) {
9574                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
9575                         progname, fname, strerror(errno));
9576                 rc = -errno;
9577                 goto free_layout;
9578         }
9579
9580         flr_state &= LCM_FL_FLR_MASK;
9581         switch (flr_state) {
9582         case LCM_FL_NONE:
9583                 rc = -EINVAL;
9584                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
9585                         progname, fname, llapi_layout_flags_string(flr_state));
9586                 goto free_layout;
9587         default:
9588                 break;
9589         }
9590
9591         rc2 = 0;
9592         for (i = 0; i < ids_nr; i++) {
9593                 mirror_id_cbdata.mirror_id = mirror_ids[i];
9594                 mirror_id_cbdata.is_valid_id = false;
9595
9596                 rc = llapi_layout_comp_iterate(layout, compare_mirror_ids,
9597                                                &mirror_id_cbdata);
9598                 if (rc < 0) {
9599                         rc = -errno;
9600                         fprintf(stderr,
9601                                 "%s: '%s' failed to verify mirror id: %u.\n",
9602                                 progname, fname, mirror_ids[i]);
9603                         goto free_layout;
9604                 }
9605
9606                 if (!mirror_id_cbdata.is_valid_id) {
9607                         rc2 = -EINVAL;
9608                         fprintf(stderr,
9609                                 "%s: '%s' invalid specified mirror id: %u.\n",
9610                                 progname, fname, mirror_ids[i]);
9611                 }
9612         }
9613         rc = rc2;
9614
9615 free_layout:
9616         llapi_layout_free(layout);
9617         llapi_lease_release(fd);
9618 close_fd:
9619         close(fd);
9620 error:
9621         return rc;
9622 }
9623
9624 static inline
9625 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
9626                            __u16 *mirror_ids, int ids_nr)
9627 {
9628         struct llapi_resync_comp comp_array[1024] = { { 0 } };
9629         struct llapi_layout *layout;
9630         struct stat stbuf;
9631         uint32_t flr_state;
9632         uint64_t start;
9633         uint64_t end;
9634         int comp_size = 0;
9635         int idx;
9636         int fd;
9637         int rc;
9638         int rc2;
9639
9640         if (stat(fname, &stbuf) < 0) {
9641                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
9642                         progname, fname, strerror(errno));
9643                 rc = -errno;
9644                 goto error;
9645         }
9646         if (!S_ISREG(stbuf.st_mode)) {
9647                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
9648                         progname, fname);
9649                 rc = -EINVAL;
9650                 goto error;
9651         }
9652
9653         fd = open(fname, O_DIRECT | O_RDWR);
9654         if (fd < 0) {
9655                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
9656                         progname, fname, strerror(errno));
9657                 rc = -errno;
9658                 goto error;
9659         }
9660
9661         layout = llapi_layout_get_by_fd(fd, 0);
9662         if (!layout) {
9663                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
9664                         progname, fname, strerror(errno));
9665                 rc = -errno;
9666                 goto close_fd;
9667         }
9668
9669         rc = llapi_layout_flags_get(layout, &flr_state);
9670         if (rc) {
9671                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
9672                         progname, fname, strerror(errno));
9673                 rc = -errno;
9674                 goto free_layout;
9675         }
9676
9677         flr_state &= LCM_FL_FLR_MASK;
9678         if (flr_state == LCM_FL_NONE) {
9679                 rc = -EINVAL;
9680                 fprintf(stderr, "%s: '%s' is not a FLR file.\n",
9681                         progname, fname);
9682                 goto free_layout;
9683         }
9684
9685         /* get stale component info */
9686         comp_size = llapi_mirror_find_stale(layout, comp_array,
9687                                             ARRAY_SIZE(comp_array),
9688                                             mirror_ids, ids_nr);
9689         if (comp_size <= 0) {
9690                 rc = comp_size;
9691                 goto free_layout;
9692         }
9693
9694         ioc->lil_mode = LL_LEASE_WRLCK;
9695         ioc->lil_flags = LL_LEASE_RESYNC;
9696         rc = llapi_lease_set(fd, ioc);
9697         if (rc < 0) {
9698                 if (rc == -EALREADY)
9699                         rc = 0;
9700                 else
9701                         fprintf(stderr,
9702                             "%s: '%s' llapi_lease_get_ext resync failed: %s.\n",
9703                                 progname, fname, strerror(-rc));
9704                 goto free_layout;
9705         }
9706
9707         /* get the read range [start, end) */
9708         start = comp_array[0].lrc_start;
9709         end = comp_array[0].lrc_end;
9710         for (idx = 1; idx < comp_size; idx++) {
9711                 if (comp_array[idx].lrc_start < start)
9712                         start = comp_array[idx].lrc_start;
9713                 if (end < comp_array[idx].lrc_end)
9714                         end = comp_array[idx].lrc_end;
9715         }
9716
9717         rc = llapi_lease_check(fd);
9718         if (rc != LL_LEASE_WRLCK) {
9719                 fprintf(stderr, "%s: '%s' lost lease lock.\n",
9720                         progname, fname);
9721                 goto free_layout;
9722         }
9723
9724         rc = llapi_mirror_resync_many(fd, layout, comp_array, comp_size,
9725                                       start, end);
9726         if (rc < 0)
9727                 fprintf(stderr, "%s: '%s' llapi_mirror_resync_many: %s.\n",
9728                         progname, fname, strerror(-rc));
9729
9730         /* need to do the lease unlock even resync fails */
9731         ioc->lil_mode = LL_LEASE_UNLCK;
9732         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
9733         ioc->lil_count = 0;
9734         for (idx = 0; idx < comp_size; idx++) {
9735                 if (comp_array[idx].lrc_synced) {
9736                         ioc->lil_ids[ioc->lil_count] = comp_array[idx].lrc_id;
9737                         ioc->lil_count++;
9738                 }
9739         }
9740
9741         rc2 = llapi_lease_set(fd, ioc);
9742         /**
9743          * llapi_lease_set returns lease mode when it request to unlock
9744          * the lease lock.
9745          */
9746         if (rc2 <= 0) {
9747                 /* rc2 == 0 means lost lease lock */
9748                 if (rc2 == 0 && rc == 0)
9749                         rc = -EBUSY;
9750                 fprintf(stderr, "%s: resync file '%s' failed: %s.\n",
9751                         progname, fname,
9752                         rc2 == 0 ? "lost lease lock" : strerror(-rc2));
9753         }
9754
9755 free_layout:
9756         llapi_layout_free(layout);
9757 close_fd:
9758         close(fd);
9759 error:
9760         return rc;
9761 }
9762
9763 static inline int lfs_mirror_resync(int argc, char **argv)
9764 {
9765         struct ll_ioc_lease *ioc = NULL;
9766         __u16 mirror_ids[128] = { 0 };
9767         int ids_nr = 0;
9768         int c;
9769         int rc = 0;
9770
9771         struct option long_opts[] = {
9772         { .val = 'o',   .name = "only",         .has_arg = required_argument },
9773         { .name = NULL } };
9774
9775         while ((c = getopt_long(argc, argv, "o:", long_opts, NULL)) >= 0) {
9776                 switch (c) {
9777                 case 'o':
9778                         rc = parse_mirror_ids(mirror_ids,
9779                                         sizeof(mirror_ids) / sizeof(__u16),
9780                                         optarg);
9781                         if (rc < 0) {
9782                                 fprintf(stderr,
9783                                         "%s: bad mirror ids '%s'.\n",
9784                                         argv[0], optarg);
9785                                 goto error;
9786                         }
9787                         ids_nr = rc;
9788                         break;
9789                 default:
9790                         fprintf(stderr, "%s: options '%s' unrecognized.\n",
9791                                 argv[0], argv[optind - 1]);
9792                         rc = -EINVAL;
9793                         goto error;
9794                 }
9795         }
9796
9797         if (argc == optind) {
9798                 fprintf(stderr, "%s: no file name given.\n", argv[0]);
9799                 rc = CMD_HELP;
9800                 goto error;
9801         }
9802
9803         if (ids_nr > 0 && argc > optind + 1) {
9804                 fprintf(stderr,
9805                     "%s: option '--only' cannot be used upon multiple files.\n",
9806                         argv[0]);
9807                 rc = CMD_HELP;
9808                 goto error;
9809         }
9810
9811         if (ids_nr > 0) {
9812                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
9813                 if (rc < 0)
9814                         goto error;
9815         }
9816
9817         /* set the lease on the file */
9818         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
9819         if (!ioc) {
9820                 fprintf(stderr, "%s: cannot alloc id array for ioc: %s.\n",
9821                         argv[0], strerror(errno));
9822                 rc = -errno;
9823                 goto error;
9824         }
9825
9826         for (; optind < argc; optind++) {
9827                 rc = lfs_mirror_resync_file(argv[optind], ioc,
9828                                             mirror_ids, ids_nr);
9829                 /* ignore previous file's error, continue with next file */
9830
9831                 /* reset ioc */
9832                 memset(ioc, 0, sizeof(*ioc) + sizeof(__u32) * 4096);
9833         }
9834
9835         free(ioc);
9836 error:
9837         return rc;
9838 }
9839
9840 static inline int verify_mirror_id_by_fd(int fd, __u16 mirror_id)
9841 {
9842         struct llapi_layout *layout;
9843         int rc;
9844
9845         layout = llapi_layout_get_by_fd(fd, 0);
9846         if (!layout) {
9847                 fprintf(stderr, "could not get layout.\n");
9848                 return  -EINVAL;
9849         }
9850
9851         rc = llapi_layout_comp_iterate(layout, find_mirror_id, &mirror_id);
9852         if (rc < 0) {
9853                 fprintf(stderr, "failed to iterate layout\n");
9854                 llapi_layout_free(layout);
9855
9856                 return rc;
9857         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
9858                 fprintf(stderr, "does not find mirror with ID %u\n", mirror_id);
9859                 llapi_layout_free(layout);
9860
9861                 return -EINVAL;
9862         }
9863         llapi_layout_free(layout);
9864
9865         return 0;
9866 }
9867
9868 /**
9869  * Check whether two files are the same file
9870  * \retval      0  same file
9871  * \retval      1  not the same file
9872  * \retval      <0 error code
9873  */
9874 static inline int check_same_file(int fd, const char *f2)
9875 {
9876         struct stat stbuf1;
9877         struct stat stbuf2;
9878
9879         if (fstat(fd, &stbuf1) < 0)
9880                 return -errno;
9881
9882         if (stat(f2, &stbuf2) < 0)
9883                 return 1;
9884
9885         if (stbuf1.st_rdev == stbuf2.st_rdev &&
9886             stbuf1.st_ino == stbuf2.st_ino)
9887                 return 0;
9888
9889         return 1;
9890 }
9891
9892 static inline int lfs_mirror_read(int argc, char **argv)
9893 {
9894         int rc = CMD_HELP;
9895         __u16 mirror_id = 0;
9896         const char *outfile = NULL;
9897         char *fname;
9898         int fd = 0;
9899         int outfd;
9900         int c;
9901         void *buf;
9902         const size_t buflen = 4 << 20;
9903         off_t pos;
9904         struct option long_opts[] = {
9905         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
9906         { .val = 'o',   .name = "outfile",      .has_arg = required_argument },
9907         { .name = NULL } };
9908
9909         while ((c = getopt_long(argc, argv, "N:o:", long_opts, NULL)) >= 0) {
9910                 char *end;
9911
9912                 switch (c) {
9913                 case 'N':
9914                         mirror_id = strtoul(optarg, &end, 0);
9915                         if (*end != '\0' || mirror_id == 0) {
9916                                 fprintf(stderr,
9917                                         "%s %s: invalid mirror ID '%s'\n",
9918                                         progname, argv[0], optarg);
9919                                 return rc;
9920                         }
9921                         break;
9922                 case 'o':
9923                         outfile = optarg;
9924                         break;
9925                 default:
9926                         fprintf(stderr, "%s: option '%s' unrecognized.\n",
9927                                 progname, argv[optind - 1]);
9928                         return -EINVAL;
9929                 }
9930         }
9931
9932         if (argc == optind) {
9933                 fprintf(stderr, "%s %s: no mirrored file provided\n",
9934                         progname, argv[0]);
9935                 return rc;
9936         } else if (argc > optind + 1) {
9937                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
9938                 return rc;
9939         }
9940
9941         if (mirror_id == 0) {
9942                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
9943                         progname, argv[0]);
9944                 return rc;
9945         }
9946
9947         /* open mirror file */
9948         fname = argv[optind];
9949         fd = open(fname, O_DIRECT | O_RDONLY);
9950         if (fd < 0) {
9951                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
9952                         progname, argv[0], fname, strerror(errno));
9953                 return rc;
9954         }
9955
9956         /* verify mirror id */
9957         rc = verify_mirror_id_by_fd(fd, mirror_id);
9958         if (rc) {
9959                 fprintf(stderr,
9960                         "%s %s: cannot find mirror with ID %u in '%s'\n",
9961                         progname, argv[0], mirror_id, fname);
9962                 goto close_fd;
9963         }
9964
9965         /* open output file - O_EXCL ensures output is not the same as input */
9966         if (outfile) {
9967                 outfd = open(outfile, O_EXCL | O_WRONLY | O_CREAT, 0644);
9968                 if (outfd < 0) {
9969                         fprintf(stderr, "%s %s: cannot create file '%s': %s\n",
9970                                 progname, argv[0], outfile, strerror(errno));
9971                         rc = -errno;
9972                         goto close_fd;
9973                 }
9974         } else {
9975                 outfd = STDOUT_FILENO;
9976         }
9977
9978         /* allocate buffer */
9979         rc = posix_memalign(&buf, sysconf(_SC_PAGESIZE), buflen);
9980         if (rc) {
9981                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
9982                                 progname, argv[0], rc);
9983                 goto close_outfd;
9984         }
9985
9986         pos = 0;
9987         while (1) {
9988                 ssize_t bytes_read;
9989                 ssize_t written = 0;
9990
9991                 bytes_read = llapi_mirror_read(fd, mirror_id, buf, buflen, pos);
9992                 if (bytes_read < 0) {
9993                         rc = bytes_read;
9994                         fprintf(stderr,
9995                                 "%s %s: fail to read data from mirror %u: %s\n",
9996                                 progname, argv[0], mirror_id, strerror(-rc));
9997                         goto free_buf;
9998                 }
9999
10000                 /* EOF reached */
10001                 if (bytes_read == 0)
10002                         break;
10003
10004                 while (written < bytes_read) {
10005                         ssize_t written2;
10006
10007                         written2 = write(outfd, buf + written,
10008                                          bytes_read - written);
10009                         if (written2 < 0) {
10010                                 fprintf(stderr,
10011                                         "%s %s: fail to write %s: %s\n",
10012                                         progname, argv[0], outfile ? : "STDOUT",
10013                                         strerror(errno));
10014                                 rc = -errno;
10015                                 goto free_buf;
10016                         }
10017                         written += written2;
10018                 }
10019
10020                 if (written != bytes_read) {
10021                         fprintf(stderr,
10022                 "%s %s: written %ld bytes does not match with %ld read.\n",
10023                                 progname, argv[0], written, bytes_read);
10024                         rc = -EIO;
10025                         goto free_buf;
10026                 }
10027
10028                 pos += bytes_read;
10029         }
10030
10031         fsync(outfd);
10032         rc = 0;
10033
10034 free_buf:
10035         free(buf);
10036 close_outfd:
10037         if (outfile)
10038                 close(outfd);
10039 close_fd:
10040         close(fd);
10041
10042         return rc;
10043 }
10044
10045 static inline int lfs_mirror_write(int argc, char **argv)
10046 {
10047         int rc = CMD_HELP;
10048         __u16 mirror_id = 0;
10049         const char *inputfile = NULL;
10050         char *fname;
10051         int fd = 0;
10052         int inputfd;
10053         int c;
10054         void *buf;
10055         const size_t buflen = 4 << 20;
10056         off_t pos;
10057         size_t page_size = sysconf(_SC_PAGESIZE);
10058         struct ll_ioc_lease_id ioc;
10059
10060         struct option long_opts[] = {
10061         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
10062         { .val = 'i',   .name = "inputfile",    .has_arg = required_argument },
10063         { .name = NULL } };
10064
10065         while ((c = getopt_long(argc, argv, "N:i:", long_opts, NULL)) >= 0) {
10066                 char *end;
10067
10068                 switch (c) {
10069                 case 'N':
10070                         mirror_id = strtoul(optarg, &end, 0);
10071                         if (*end != '\0' || mirror_id == 0) {
10072                                 fprintf(stderr,
10073                                         "%s %s: invalid mirror ID '%s'\n",
10074                                         progname, argv[0], optarg);
10075                                 return rc;
10076                         }
10077                         break;
10078                 case 'i':
10079                         inputfile = optarg;
10080                         break;
10081                 default:
10082                         fprintf(stderr, "%s: option '%s' unrecognized\n",
10083                                 progname, argv[optind - 1]);
10084                         return -EINVAL;
10085                 }
10086         }
10087
10088         if (argc == optind) {
10089                 fprintf(stderr, "%s %s: no mirrored file provided\n",
10090                         progname, argv[0]);
10091                 return rc;
10092         } else if (argc > optind + 1) {
10093                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
10094                 return rc;
10095         }
10096
10097         if (mirror_id == 0) {
10098                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
10099                         progname, argv[0]);
10100                 return rc;
10101         }
10102
10103         /* open mirror file */
10104         fname = argv[optind];
10105         fd = open(fname, O_DIRECT | O_WRONLY);
10106         if (fd < 0) {
10107                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
10108                         progname, argv[0], fname, strerror(errno));
10109                 return rc;
10110         }
10111
10112         /* verify mirror id */
10113         rc = verify_mirror_id_by_fd(fd, mirror_id);
10114         if (rc) {
10115                 fprintf(stderr,
10116                         "%s %s: cannot find mirror with ID %u in '%s'\n",
10117                         progname, argv[0], mirror_id, fname);
10118                 goto close_fd;
10119         }
10120
10121         /* open input file */
10122         if (inputfile) {
10123                 rc = check_same_file(fd, inputfile);
10124                 if (rc == 0) {
10125                         fprintf(stderr,
10126                         "%s %s: input file cannot be the mirrored file\n",
10127                                 progname, argv[0]);
10128                         goto close_fd;
10129                 }
10130                 if (rc < 0)
10131                         goto close_fd;
10132
10133                 inputfd = open(inputfile, O_RDONLY, 0644);
10134                 if (inputfd < 0) {
10135                         fprintf(stderr, "%s %s: cannot open file '%s': %s\n",
10136                                 progname, argv[0], inputfile, strerror(errno));
10137                         rc = -errno;
10138                         goto close_fd;
10139                 }
10140         } else {
10141                 inputfd = STDIN_FILENO;
10142         }
10143
10144         /* allocate buffer */
10145         rc = posix_memalign(&buf, page_size, buflen);
10146         if (rc) {
10147                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
10148                         progname, argv[0], rc);
10149                 goto close_inputfd;
10150         }
10151
10152         /* prepare target mirror components instantiation */
10153         ioc.lil_mode = LL_LEASE_WRLCK;
10154         ioc.lil_flags = LL_LEASE_RESYNC;
10155         ioc.lil_mirror_id = mirror_id;
10156         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
10157         if (rc < 0) {
10158                 fprintf(stderr,
10159                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
10160                         progname, argv[0], fname, strerror(errno));
10161                 goto free_buf;
10162         }
10163
10164         pos = 0;
10165         while (1) {
10166                 ssize_t bytes_read;
10167                 ssize_t written;
10168                 size_t to_write;
10169
10170                 rc = llapi_lease_check(fd);
10171                 if (rc != LL_LEASE_WRLCK) {
10172                         fprintf(stderr, "%s %s: '%s' lost lease lock\n",
10173                                 progname, argv[0], fname);
10174                         goto free_buf;
10175                 }
10176
10177                 bytes_read = read(inputfd, buf, buflen);
10178                 if (bytes_read < 0) {
10179                         rc = bytes_read;
10180                         fprintf(stderr,
10181                                 "%s %s: fail to read data from '%s': %s\n",
10182                                 progname, argv[0], inputfile ? : "STDIN",
10183                                 strerror(errno));
10184                         rc = -errno;
10185                         goto free_buf;
10186                 }
10187
10188                 /* EOF reached */
10189                 if (bytes_read == 0)
10190                         break;
10191
10192                 /* round up to page align to make direct IO happy. */
10193                 to_write = (bytes_read + page_size - 1) & ~(page_size - 1);
10194
10195                 written = llapi_mirror_write(fd, mirror_id, buf, to_write,
10196                                              pos);
10197                 if (written < 0) {
10198                         rc = written;
10199                         fprintf(stderr,
10200                               "%s %s: fail to write to mirror %u: %s\n",
10201                                 progname, argv[0], mirror_id,
10202                                 strerror(-rc));
10203                         goto free_buf;
10204                 }
10205
10206                 pos += bytes_read;
10207         }
10208
10209         if (pos & (page_size - 1)) {
10210                 rc = llapi_mirror_truncate(fd, mirror_id, pos);
10211                 if (rc < 0)
10212                         goto free_buf;
10213         }
10214
10215         ioc.lil_mode = LL_LEASE_UNLCK;
10216         ioc.lil_flags = LL_LEASE_RESYNC_DONE;
10217         ioc.lil_count = 0;
10218         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
10219         if (rc <= 0) {
10220                 if (rc == 0)
10221                         rc = -EBUSY;
10222                 fprintf(stderr,
10223                         "%s %s: release lease lock of '%s' failed: %s\n",
10224                         progname, argv[0], fname, strerror(errno));
10225                 goto free_buf;
10226         }
10227
10228         rc = 0;
10229
10230 free_buf:
10231         free(buf);
10232 close_inputfd:
10233         if (inputfile)
10234                 close(inputfd);
10235 close_fd:
10236         close(fd);
10237
10238         return rc;
10239 }
10240
10241 static inline int get_other_mirror_ids(int fd, __u16 *ids, __u16 exclude_id)
10242 {
10243         struct llapi_layout *layout;
10244         struct collect_ids_data cid = { .cid_ids = ids,
10245                                         .cid_count = 0,
10246                                         .cid_exclude = exclude_id, };
10247         int rc;
10248
10249         layout = llapi_layout_get_by_fd(fd, 0);
10250         if (!layout) {
10251                 fprintf(stderr, "could not get layout\n");
10252                 return -EINVAL;
10253         }
10254
10255         rc = llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
10256         if (rc < 0) {
10257                 fprintf(stderr, "failed to iterate layout\n");
10258                 llapi_layout_free(layout);
10259
10260                 return rc;
10261         }
10262         llapi_layout_free(layout);
10263
10264         return cid.cid_count;
10265 }
10266
10267 static inline int lfs_mirror_copy(int argc, char **argv)
10268 {
10269         int rc = CMD_HELP;
10270         __u16 read_mirror_id = 0;
10271         __u16 ids[128] = { 0 };
10272         int count = 0;
10273         struct llapi_layout *layout = NULL;
10274         struct llapi_resync_comp comp_array[1024] = { { 0 } };
10275         int comp_size = 0;
10276         char *fname;
10277         int fd = 0;
10278         int c;
10279         int i;
10280         ssize_t copied;
10281         struct ll_ioc_lease *ioc = NULL;
10282         struct ll_ioc_lease_id *resync_ioc;
10283
10284         struct option long_opts[] = {
10285         { .val = 'i',   .name = "read-mirror",  .has_arg = required_argument },
10286         { .val = 'o',   .name = "write-mirror", .has_arg = required_argument },
10287         { .name = NULL } };
10288
10289         while ((c = getopt_long(argc, argv, "i:o:", long_opts, NULL)) >= 0) {
10290                 char *end;
10291
10292                 switch (c) {
10293                 case 'i':
10294                         read_mirror_id = strtoul(optarg, &end, 0);
10295                         if (*end != '\0' || read_mirror_id == 0) {
10296                                 fprintf(stderr,
10297                                         "%s %s: invalid read mirror ID '%s'\n",
10298                                         progname, argv[0], optarg);
10299                                 return rc;
10300                         }
10301                         break;
10302                 case 'o':
10303                         if (!strcmp(optarg, "-1")) {
10304                                 /* specify all other mirrors */
10305                                 ids[0] = (__u16)-1;
10306                                 count = 1;
10307                         } else {
10308                                 count = parse_mirror_ids((__u16 *)ids,
10309                                                          ARRAY_SIZE(ids),
10310                                                          optarg);
10311                                 if (count < 0)
10312                                         return rc;
10313                         }
10314                         break;
10315                 default:
10316                         fprintf(stderr, "%s: option '%s' unrecognized\n",
10317                                 progname, argv[optind - 1]);
10318                         return -EINVAL;
10319                 }
10320         }
10321
10322         if (argc == optind) {
10323                 fprintf(stderr, "%s %s: no mirrored file provided\n",
10324                         progname, argv[0]);
10325                 return rc;
10326         } else if (argc > optind + 1) {
10327                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
10328                 return rc;
10329         }
10330
10331         if (read_mirror_id == 0) {
10332                 fprintf(stderr,
10333                         "%s %s: no valid read mirror ID %d is provided\n",
10334                         progname, argv[0], read_mirror_id);
10335                 return rc;
10336         }
10337
10338         if (count == 0) {
10339                 fprintf(stderr,
10340                         "%s %s: no write mirror ID is provided\n",
10341                         progname, argv[0]);
10342                 return rc;
10343         }
10344
10345         for (i = 0; i < count; i++) {
10346                 if (read_mirror_id == ids[i]) {
10347                         fprintf(stderr,
10348                         "%s %s: read and write mirror ID cannot be the same\n",
10349                                 progname, argv[0]);
10350                         return rc;
10351                 }
10352         }
10353
10354         /* open mirror file */
10355         fname = argv[optind];
10356
10357         fd = open(fname, O_DIRECT | O_RDWR);
10358         if (fd < 0) {
10359                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
10360                         progname, argv[0], fname, strerror(errno));
10361                 return rc;
10362         }
10363
10364         /* write to all other mirrors */
10365         if (ids[0] == (__u16)-1) {
10366                 count = get_other_mirror_ids(fd, ids, read_mirror_id);
10367                 if (count <= 0) {
10368                         rc = count;
10369                         fprintf(stderr,
10370                         "%s %s: failed to get other mirror ids in '%s': %d\n",
10371                                 progname, argv[0], fname, rc);
10372                         goto close_fd;
10373                 }
10374         }
10375
10376         /* verify mirror id */
10377         rc = verify_mirror_id_by_fd(fd, read_mirror_id);
10378         if (rc) {
10379                 fprintf(stderr,
10380                         "%s %s: cannot find mirror with ID %u in '%s'\n",
10381                         progname, argv[0], read_mirror_id, fname);
10382                 goto close_fd;
10383         }
10384
10385         for (i = 0; i < count; i++) {
10386                 rc = verify_mirror_id_by_fd(fd, ids[i]);
10387                 if (rc) {
10388                         fprintf(stderr,
10389                         "%s %s: cannot find mirror with ID %u in '%s'\n",
10390                                 progname, argv[0], ids[i], fname);
10391                         goto close_fd;
10392                 }
10393         }
10394
10395         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
10396         if (!ioc) {
10397                 fprintf(stderr,
10398                         "%s %s: cannot alloc comp id array for ioc: %s\n",
10399                         progname, argv[0], strerror(errno));
10400                 rc = -errno;
10401                 goto close_fd;
10402         }
10403
10404         /* get stale component info */
10405         layout = llapi_layout_get_by_fd(fd, 0);
10406         if (!layout) {
10407                 fprintf(stderr, "%s %s: failed to get layout of '%s': %s\n",
10408                         progname, argv[0], fname, strerror(errno));
10409                 rc = -errno;
10410                 goto free_ioc;
10411         }
10412         comp_size = llapi_mirror_find_stale(layout, comp_array,
10413                                             ARRAY_SIZE(comp_array),
10414                                             ids, count);
10415         llapi_layout_free(layout);
10416         if (comp_size < 0) {
10417                 rc = comp_size;
10418                 goto free_ioc;
10419         }
10420
10421         /* prepare target mirror components instantiation */
10422         resync_ioc = (struct ll_ioc_lease_id *)ioc;
10423         resync_ioc->lil_mode = LL_LEASE_WRLCK;
10424         resync_ioc->lil_flags = LL_LEASE_RESYNC;
10425         if (count == 1)
10426                 resync_ioc->lil_mirror_id = ids[0];
10427         else
10428                 resync_ioc->lil_mirror_id = read_mirror_id | MIRROR_ID_NEG;
10429         rc = llapi_lease_set(fd, ioc);
10430         if (rc < 0) {
10431                 fprintf(stderr,
10432                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
10433                         progname, argv[0], fname, strerror(errno));
10434                 goto free_ioc;
10435         }
10436
10437         copied = llapi_mirror_copy_many(fd, read_mirror_id, ids, count);
10438         if (copied < 0) {
10439                 rc = copied;
10440                 fprintf(stderr, "%s %s: copy error: %d\n",
10441                         progname, argv[0], rc);
10442                 goto free_ioc;
10443         }
10444
10445         fprintf(stdout, "mirror copied successfully: ");
10446         for (i = 0; i < copied; i++)
10447                 fprintf(stdout, "%d ", ids[i]);
10448         fprintf(stdout, "\n");
10449
10450         ioc->lil_mode = LL_LEASE_UNLCK;
10451         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
10452         ioc->lil_count = 0;
10453         for (i = 0; i < comp_size; i++) {
10454                 int j;
10455
10456                 for (j = 0; j < copied; j++) {
10457                         if (comp_array[i].lrc_mirror_id != ids[j])
10458                                 continue;
10459
10460                         ioc->lil_ids[ioc->lil_count] = comp_array[i].lrc_id;
10461                         ioc->lil_count++;
10462                 }
10463         }
10464         rc = llapi_lease_set(fd, ioc);
10465         if (rc <= 0) {
10466                 if (rc == 0)
10467                         rc = -EBUSY;
10468                 fprintf(stderr,
10469                         "%s %s: release lease lock of '%s' failed: %s\n",
10470                         progname, argv[0], fname, strerror(errno));
10471                 goto free_ioc;
10472         }
10473
10474         rc = 0;
10475
10476 free_ioc:
10477         free(ioc);
10478 close_fd:
10479         close(fd);
10480
10481         return rc;
10482 }
10483
10484 /**
10485  * struct verify_chunk - Mirror chunk to be verified.
10486  * @chunk:        [start, end) of the chunk.
10487  * @mirror_count: Number of mirror ids in @mirror_id array.
10488  * @mirror_id:    Array of valid mirror ids that cover the chunk.
10489  */
10490 struct verify_chunk {
10491         struct lu_extent chunk;
10492         unsigned int mirror_count;
10493         __u16 mirror_id[LUSTRE_MIRROR_COUNT_MAX];
10494 };
10495
10496 /**
10497  * print_chunks() - Print chunk information.
10498  * @fname:       Mirrored file name.
10499  * @chunks:      Array of chunks.
10500  * @chunk_count: Number of chunks in @chunks array.
10501  *
10502  * This function prints [start, end) of each chunk in @chunks
10503  * for mirrored file @fname, and also prints the valid mirror ids
10504  * that cover the chunk.
10505  *
10506  * Return: void.
10507  */
10508 static inline
10509 void print_chunks(const char *fname, struct verify_chunk *chunks,
10510                   int chunk_count)
10511 {
10512         int i;
10513         int j;
10514
10515         fprintf(stdout, "Chunks to be verified in %s:\n", fname);
10516         for (i = 0; i < chunk_count; i++) {
10517                 fprintf(stdout, DEXT, PEXT(&chunks[i].chunk));
10518
10519                 if (chunks[i].mirror_count == 0)
10520                         fprintf(stdout, "\t[");
10521                 else {
10522                         fprintf(stdout, "\t[%u", chunks[i].mirror_id[0]);
10523                         for (j = 1; j < chunks[i].mirror_count; j++)
10524                                 fprintf(stdout, ", %u", chunks[i].mirror_id[j]);
10525                 }
10526                 fprintf(stdout, "]\t%u\n", chunks[i].mirror_count);
10527         }
10528         fprintf(stdout, "\n");
10529 }
10530
10531 /**
10532  * print_checksums() - Print CRC-32 checksum values.
10533  * @chunk: A chunk and its corresponding valid mirror ids.
10534  * @crc:   CRC-32 checksum values on the chunk for each valid mirror.
10535  *
10536  * This function prints CRC-32 checksum values on @chunk for
10537  * each valid mirror that covers it.
10538  *
10539  * Return: void.
10540  */
10541 static inline
10542 void print_checksums(struct verify_chunk *chunk, unsigned long *crc)
10543 {
10544         int i;
10545
10546         fprintf(stdout,
10547                 "CRC-32 checksum value for chunk "DEXT":\n",
10548                 PEXT(&chunk->chunk));
10549         for (i = 0; i < chunk->mirror_count; i++)
10550                 fprintf(stdout, "Mirror %u:\t%#lx\n",
10551                         chunk->mirror_id[i], crc[i]);
10552         fprintf(stdout, "\n");
10553 }
10554
10555 /**
10556  * filter_mirror_id() - Filter specified mirror ids.
10557  * @chunks:      Array of chunks.
10558  * @chunk_count: Number of chunks in @chunks array.
10559  * @mirror_ids:  Specified mirror ids to be verified.
10560  * @ids_nr:      Number of specified mirror ids.
10561  *
10562  * This function scans valid mirror ids that cover each chunk in @chunks
10563  * and filters specified mirror ids.
10564  *
10565  * Return: void.
10566  */
10567 static inline
10568 void filter_mirror_id(struct verify_chunk *chunks, int chunk_count,
10569                       __u16 *mirror_ids, int ids_nr)
10570 {
10571         int i;
10572         int j;
10573         int k;
10574         __u16 valid_id[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
10575         unsigned int valid_count = 0;
10576
10577         for (i = 0; i < chunk_count; i++) {
10578                 if (chunks[i].mirror_count == 0)
10579                         continue;
10580
10581                 valid_count = 0;
10582                 for (j = 0; j < ids_nr; j++) {
10583                         for (k = 0; k < chunks[i].mirror_count; k++) {
10584                                 if (chunks[i].mirror_id[k] == mirror_ids[j]) {
10585                                         valid_id[valid_count] = mirror_ids[j];
10586                                         valid_count++;
10587                                         break;
10588                                 }
10589                         }
10590                 }
10591
10592                 memcpy(chunks[i].mirror_id, valid_id,
10593                        sizeof(__u16) * valid_count);
10594                 chunks[i].mirror_count = valid_count;
10595         }
10596 }
10597
10598 /**
10599  * lfs_mirror_prepare_chunk() - Find mirror chunks to be verified.
10600  * @layout:      Mirror component list.
10601  * @chunks:      Array of chunks.
10602  * @chunks_size: Array size of @chunks.
10603  *
10604  * This function scans the components in @layout from offset 0 to LUSTRE_EOF
10605  * to find out chunk segments and store them in @chunks array.
10606  *
10607  * The @mirror_id array in each element of @chunks will store the valid
10608  * mirror ids that cover the chunk. If a mirror component covering the
10609  * chunk has LCME_FL_STALE or LCME_FL_OFFLINE flag, then the mirror id
10610  * will not be stored into the @mirror_id array, and the chunk for that
10611  * mirror will not be verified.
10612  *
10613  * The @mirror_count in each element of @chunks will store the number of
10614  * mirror ids in @mirror_id array. If @mirror_count is 0, it indicates the
10615  * chunk is invalid in all of the mirrors. And if @mirror_count is 1, it
10616  * indicates the chunk is valid in only one mirror. In both cases, the
10617  * chunk will not be verified.
10618  *
10619  * Here is an example:
10620  *
10621  *  0      1M     2M     3M     4M           EOF
10622  *  +------+-------------+--------------------+
10623  *  |      |             |      S             |       mirror1
10624  *  +------+------+------+------+-------------+
10625  *  |             |   S  |   S  |             |       mirror2
10626  *  +-------------+------+------+-------------+
10627  *
10628  * prepared @chunks array will contain 5 elements:
10629  * (([0, 1M), [1, 2], 2),
10630  *  ([1M, 2M), [1, 2], 2),
10631  *  ([2M, 3M), [1], 1),
10632  *  ([3M, 4M], [], 0),
10633  *  ([4M, EOF), [2], 1))
10634  *
10635  * Return: the actual array size of @chunks on success
10636  *         or a negative error code on failure.
10637  */
10638 static inline
10639 int lfs_mirror_prepare_chunk(struct llapi_layout *layout,
10640                              struct verify_chunk *chunks,
10641                              size_t chunks_size)
10642 {
10643         uint64_t start;
10644         uint64_t end;
10645         uint32_t mirror_id;
10646         uint32_t flags;
10647         int idx = 0;
10648         int i = 0;
10649         int rc = 0;
10650
10651         memset(chunks, 0, sizeof(*chunks) * chunks_size);
10652
10653         while (1) {
10654                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
10655                 if (rc < 0) {
10656                         fprintf(stderr,
10657                                 "%s: move to the first layout component: %s.\n",
10658                                 progname, strerror(errno));
10659                         goto error;
10660                 }
10661
10662                 i = 0;
10663                 rc = 0;
10664                 chunks[idx].chunk.e_end = LUSTRE_EOF;
10665                 while (rc == 0) {
10666                         rc = llapi_layout_comp_extent_get(layout, &start, &end);
10667                         if (rc < 0) {
10668                                 fprintf(stderr,
10669                                         "%s: llapi_layout_comp_extent_get failed: %s.\n",
10670                                         progname, strerror(errno));
10671                                 goto error;
10672                         }
10673
10674                         if (start > chunks[idx].chunk.e_start ||
10675                             end <= chunks[idx].chunk.e_start)
10676                                 goto next;
10677
10678                         if (end < chunks[idx].chunk.e_end)
10679                                 chunks[idx].chunk.e_end = end;
10680
10681                         rc = llapi_layout_comp_flags_get(layout, &flags);
10682                         if (rc < 0) {
10683                                 fprintf(stderr,
10684                                         "%s: llapi_layout_comp_flags_get failed: %s.\n",
10685                                         progname, strerror(errno));
10686                                 goto error;
10687                         }
10688
10689                         if (flags & LCME_FL_STALE || flags & LCME_FL_OFFLINE)
10690                                 goto next;
10691
10692                         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
10693                         if (rc < 0) {
10694                                 fprintf(stderr,
10695                                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
10696                                         progname, strerror(errno));
10697                                 goto error;
10698                         }
10699
10700                         chunks[idx].mirror_id[i] = mirror_id;
10701                         i++;
10702                         if (i >= ARRAY_SIZE(chunks[idx].mirror_id)) {
10703                                 fprintf(stderr,
10704                                         "%s: mirror_id array is too small.\n",
10705                                         progname);
10706                                 rc = -EINVAL;
10707                                 goto error;
10708                         }
10709
10710 next:
10711                         rc = llapi_layout_comp_use(layout,
10712                                                    LLAPI_LAYOUT_COMP_USE_NEXT);
10713                         if (rc < 0) {
10714                                 fprintf(stderr,
10715                                         "%s: move to the next layout component: %s.\n",
10716                                         progname, strerror(errno));
10717                                 goto error;
10718                         }
10719                 } /* loop through all components */
10720
10721                 chunks[idx].mirror_count = i;
10722
10723                 if (chunks[idx].chunk.e_end == LUSTRE_EOF)
10724                         break;
10725
10726                 idx++;
10727                 if (idx >= chunks_size) {
10728                         fprintf(stderr, "%s: chunks array is too small.\n",
10729                                 progname);
10730                         rc = -EINVAL;
10731                         goto error;
10732                 }
10733
10734                 chunks[idx].chunk.e_start = chunks[idx - 1].chunk.e_end;
10735         }
10736
10737 error:
10738         return rc < 0 ? rc : idx + 1;
10739 }
10740
10741 /**
10742  * lfs_mirror_verify_chunk() - Verify a chunk.
10743  * @fd:        File descriptor of the mirrored file.
10744  * @file_size: Size of the mirrored file.
10745  * @chunk:     A chunk and its corresponding valid mirror ids.
10746  * @verbose:   Verbose mode.
10747  *
10748  * This function verifies a @chunk contains exactly the same data
10749  * ammong the mirrors that cover it.
10750  *
10751  * If @verbose is specified, then the function will print where the
10752  * differences are if the data do not match. Otherwise, it will
10753  * just return an error in that case.
10754  *
10755  * Return: 0 on success or a negative error code on failure.
10756  */
10757 static inline
10758 int lfs_mirror_verify_chunk(int fd, size_t file_size,
10759                             struct verify_chunk *chunk, int verbose)
10760 {
10761         const size_t buflen = 4 * 1024 * 1024; /* 4M */
10762         void *buf;
10763         size_t page_size = sysconf(_SC_PAGESIZE);
10764         ssize_t bytes_read;
10765         ssize_t bytes_done;
10766         size_t count;
10767         off_t pos;
10768         unsigned long crc;
10769         unsigned long crc_array[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
10770         int i;
10771         int rc = 0;
10772
10773         if (file_size == 0)
10774                 return 0;
10775
10776         rc = posix_memalign(&buf, page_size, buflen);
10777         if (rc) /* error code is returned directly */
10778                 return -rc;
10779
10780         if (verbose > 1) {
10781                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
10782                         PEXT(&chunk->chunk));
10783                 for (i = 0; i < chunk->mirror_count; i++)
10784                         fprintf(stdout, " %u", chunk->mirror_id[i]);
10785                 fprintf(stdout, "\n");
10786         }
10787
10788         bytes_done = 0;
10789         count = MIN(chunk->chunk.e_end, file_size) - chunk->chunk.e_start;
10790         pos = chunk->chunk.e_start;
10791         while (bytes_done < count) {
10792                 /* compute initial CRC-32 checksum */
10793                 crc = crc32(0L, Z_NULL, 0);
10794                 memset(crc_array, 0, sizeof(crc_array));
10795
10796                 bytes_read = 0;
10797                 for (i = 0; i < chunk->mirror_count; i++) {
10798                         bytes_read = llapi_mirror_read(fd, chunk->mirror_id[i],
10799                                                        buf, buflen, pos);
10800                         if (bytes_read < 0) {
10801                                 rc = bytes_read;
10802                                 fprintf(stderr,
10803                                         "%s: failed to read data from mirror %u: %s.\n",
10804                                         progname, chunk->mirror_id[i],
10805                                         strerror(-rc));
10806                                 goto error;
10807                         }
10808
10809                         /* compute new CRC-32 checksum */
10810                         crc_array[i] = crc32(crc, buf, bytes_read);
10811                 }
10812
10813                 if (verbose)
10814                         print_checksums(chunk, crc_array);
10815
10816                 /* compare CRC-32 checksum values */
10817                 for (i = 1; i < chunk->mirror_count; i++) {
10818                         if (crc_array[i] != crc_array[0]) {
10819                                 rc = -EINVAL;
10820
10821                                 fprintf(stderr,
10822                                         "%s: chunk "DEXT" has different checksum value on mirror %u and mirror %u.\n",
10823                                         progname, PEXT(&chunk->chunk),
10824                                         chunk->mirror_id[0],
10825                                         chunk->mirror_id[i]);
10826                         }
10827                 }
10828
10829                 pos += bytes_read;
10830                 bytes_done += bytes_read;
10831         }
10832
10833         if (verbose > 1 && rc == 0) {
10834                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
10835                         PEXT(&chunk->chunk));
10836                 for (i = 0; i < chunk->mirror_count; i++)
10837                         fprintf(stdout, " %u", chunk->mirror_id[i]);
10838                 fprintf(stdout, " PASS\n\n");
10839         }
10840
10841 error:
10842         free(buf);
10843         return rc;
10844 }
10845
10846 /**
10847  * lfs_mirror_verify_file() - Verify a mirrored file.
10848  * @fname:      Mirrored file name.
10849  * @mirror_ids: Specified mirror ids to be verified.
10850  * @ids_nr:     Number of specified mirror ids.
10851  * @verbose:    Verbose mode.
10852  *
10853  * This function verifies that each SYNC mirror of a mirrored file
10854  * specified by @fname contains exactly the same data.
10855  *
10856  * If @mirror_ids is specified, then the function will verify the
10857  * mirrors specified by @mirror_ids contain exactly the same data.
10858  *
10859  * If @verbose is specified, then the function will print where the
10860  * differences are if the data do not match. Otherwise, it will
10861  * just return an error in that case.
10862  *
10863  * Return: 0 on success or a negative error code on failure.
10864  */
10865 static inline
10866 int lfs_mirror_verify_file(const char *fname, __u16 *mirror_ids, int ids_nr,
10867                            int verbose)
10868 {
10869         struct verify_chunk chunks_array[1024] = { };
10870         struct llapi_layout *layout = NULL;
10871         struct stat stbuf;
10872         uint32_t flr_state;
10873         int fd;
10874         int chunk_count = 0;
10875         int idx = 0;
10876         int rc = 0;
10877         int rc1 = 0;
10878         int rc2 = 0;
10879
10880         if (stat(fname, &stbuf) < 0) {
10881                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
10882                         progname, fname, strerror(errno));
10883                 rc = -errno;
10884                 goto error;
10885         }
10886
10887         if (!S_ISREG(stbuf.st_mode)) {
10888                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
10889                         progname, fname);
10890                 rc = -EINVAL;
10891                 goto error;
10892         }
10893
10894         if (stbuf.st_size == 0) {
10895                 if (verbose)
10896                         fprintf(stdout, "%s: '%s' file size is 0.\n",
10897                                 progname, fname);
10898                 rc = 0;
10899                 goto error;
10900         }
10901
10902         fd = open(fname, O_DIRECT | O_RDONLY);
10903         if (fd < 0) {
10904                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
10905                         progname, fname, strerror(errno));
10906                 rc = -errno;
10907                 goto error;
10908         }
10909
10910         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
10911         if (rc < 0) {
10912                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
10913                         progname, fname, strerror(errno));
10914                 goto close_fd;
10915         }
10916
10917         layout = llapi_layout_get_by_fd(fd, 0);
10918         if (!layout) {
10919                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
10920                         progname, fname, strerror(errno));
10921                 rc = -errno;
10922                 llapi_lease_release(fd);
10923                 goto close_fd;
10924         }
10925
10926         rc = llapi_layout_flags_get(layout, &flr_state);
10927         if (rc < 0) {
10928                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
10929                         progname, fname, strerror(errno));
10930                 rc = -errno;
10931                 goto free_layout;
10932         }
10933
10934         flr_state &= LCM_FL_FLR_MASK;
10935         switch (flr_state) {
10936         case LCM_FL_NONE:
10937                 rc = -EINVAL;
10938                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
10939                         progname, fname, llapi_layout_flags_string(flr_state));
10940                 goto free_layout;
10941         default:
10942                 break;
10943         }
10944
10945         /* find out mirror chunks to be verified */
10946         chunk_count = lfs_mirror_prepare_chunk(layout, chunks_array,
10947                                                ARRAY_SIZE(chunks_array));
10948         if (chunk_count < 0) {
10949                 rc = chunk_count;
10950                 goto free_layout;
10951         }
10952
10953         if (ids_nr > 0)
10954                 /* filter specified mirror ids */
10955                 filter_mirror_id(chunks_array, chunk_count, mirror_ids, ids_nr);
10956
10957         if (verbose > 2)
10958                 print_chunks(fname, chunks_array, chunk_count);
10959
10960         for (idx = 0; idx < chunk_count; idx++) {
10961                 if (chunks_array[idx].chunk.e_start >= stbuf.st_size) {
10962                         if (verbose)
10963                                 fprintf(stdout,
10964                                         "%s: '%s' chunk "DEXT" exceeds file size %#llx: skipped\n",
10965                                         progname, fname,
10966                                         PEXT(&chunks_array[idx].chunk),
10967                                         (unsigned long long)stbuf.st_size);
10968                         break;
10969                 }
10970
10971                 if (chunks_array[idx].mirror_count == 0) {
10972                         fprintf(stderr,
10973                                 "%s: '%s' chunk "DEXT" is invalid in all of the mirrors: ",
10974                                 progname, fname,
10975                                 PEXT(&chunks_array[idx].chunk));
10976                         if (verbose) {
10977                                 fprintf(stderr, "skipped\n");
10978                                 continue;
10979                         }
10980                         rc = -EINVAL;
10981                         fprintf(stderr, "failed\n");
10982                         goto free_layout;
10983                 }
10984
10985                 if (chunks_array[idx].mirror_count == 1) {
10986                         if (verbose)
10987                                 fprintf(stdout,
10988                                         "%s: '%s' chunk "DEXT" is only valid in mirror %u: skipped\n",
10989                                         progname, fname,
10990                                         PEXT(&chunks_array[idx].chunk),
10991                                         chunks_array[idx].mirror_id[0]);
10992                         continue;
10993                 }
10994
10995                 rc = llapi_lease_check(fd);
10996                 if (rc != LL_LEASE_RDLCK) {
10997                         fprintf(stderr, "%s: '%s' lost lease lock.\n",
10998                                 progname, fname);
10999                         goto free_layout;
11000                 }
11001
11002                 /* verify one chunk */
11003                 rc1 = lfs_mirror_verify_chunk(fd, stbuf.st_size,
11004                                               &chunks_array[idx], verbose);
11005                 if (rc1 < 0) {
11006                         rc2 = rc1;
11007                         if (!verbose) {
11008                                 rc = rc1;
11009                                 goto free_layout;
11010                         }
11011                 }
11012         }
11013
11014         if (rc2 < 0)
11015                 rc = rc2;
11016
11017 free_layout:
11018         llapi_layout_free(layout);
11019         llapi_lease_release(fd);
11020 close_fd:
11021         close(fd);
11022 error:
11023         return rc;
11024 }
11025
11026 /**
11027  * lfs_mirror_verify() - Parse and execute lfs mirror verify command.
11028  * @argc: The count of lfs mirror verify command line arguments.
11029  * @argv: Array of strings for lfs mirror verify command line arguments.
11030  *
11031  * This function parses lfs mirror verify command and verifies the
11032  * specified mirrored file(s).
11033  *
11034  * Return: 0 on success or a negative error code on failure.
11035  */
11036 static inline int lfs_mirror_verify(int argc, char **argv)
11037 {
11038         __u16 mirror_ids[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
11039         int ids_nr = 0;
11040         int c;
11041         int verbose = 0;
11042         int rc = 0;
11043         int rc1 = 0;
11044         char cmd[PATH_MAX];
11045
11046         struct option long_opts[] = {
11047         { .val = 'o',   .name = "only",         .has_arg = required_argument },
11048         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
11049         { .name = NULL } };
11050
11051         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
11052         progname = cmd;
11053         while ((c = getopt_long(argc, argv, "o:v", long_opts, NULL)) >= 0) {
11054                 switch (c) {
11055                 case 'o':
11056                         rc = parse_mirror_ids(mirror_ids,
11057                                               ARRAY_SIZE(mirror_ids),
11058                                               optarg);
11059                         if (rc < 0) {
11060                                 fprintf(stderr,
11061                                         "%s: bad mirror ids '%s'.\n",
11062                                         progname, optarg);
11063                                 goto error;
11064                         }
11065                         ids_nr = rc;
11066                         if (ids_nr < 2) {
11067                                 fprintf(stderr,
11068                                         "%s: at least 2 mirror ids needed with '--only' option.\n",
11069                                         progname);
11070                                 rc = CMD_HELP;
11071                                 goto error;
11072                         }
11073                         break;
11074                 case 'v':
11075                         verbose++;
11076                         break;
11077                 default:
11078                         fprintf(stderr, "%s: option '%s' unrecognized.\n",
11079                                 progname, argv[optind - 1]);
11080                         rc = -EINVAL;
11081                         goto error;
11082                 }
11083         }
11084
11085         if (argc == optind) {
11086                 fprintf(stderr, "%s: no file name given.\n", progname);
11087                 rc = CMD_HELP;
11088                 goto error;
11089         }
11090
11091         if (ids_nr > 0 && argc > optind + 1) {
11092                 fprintf(stderr,
11093                         "%s: '--only' cannot be used upon multiple files.\n",
11094                         progname);
11095                 rc = CMD_HELP;
11096                 goto error;
11097         }
11098
11099         if (ids_nr > 0) {
11100                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
11101                 if (rc < 0)
11102                         goto error;
11103         }
11104
11105         rc = 0;
11106         for (; optind < argc; optind++) {
11107                 rc1 = lfs_mirror_verify_file(argv[optind], mirror_ids, ids_nr,
11108                                              verbose);
11109                 if (rc1 < 0)
11110                         rc = rc1;
11111         }
11112 error:
11113         return rc;
11114 }
11115
11116 /**
11117  * lfs_mirror() - Parse and execute lfs mirror commands.
11118  * @argc: The count of lfs mirror command line arguments.
11119  * @argv: Array of strings for lfs mirror command line arguments.
11120  *
11121  * This function parses lfs mirror commands and performs the
11122  * corresponding functions specified in mirror_cmdlist[].
11123  *
11124  * Return: 0 on success or an error code on failure.
11125  */
11126 static int lfs_mirror(int argc, char **argv)
11127 {
11128         char cmd[PATH_MAX];
11129         int rc = 0;
11130
11131         setlinebuf(stdout);
11132
11133         Parser_init("lfs-mirror > ", mirror_cmdlist);
11134
11135         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
11136         progname = cmd;
11137         program_invocation_short_name = cmd;
11138         if (argc > 1)
11139                 rc = Parser_execarg(argc - 1, argv + 1, mirror_cmdlist);
11140         else
11141                 rc = Parser_commands();
11142
11143         return rc < 0 ? -rc : rc;
11144 }
11145
11146 static void lustre_som_swab(struct lustre_som_attrs *attrs)
11147 {
11148 #if __BYTE_ORDER == __BIG_ENDIAN
11149         __swab16s(&attrs->lsa_valid);
11150         __swab64s(&attrs->lsa_size);
11151         __swab64s(&attrs->lsa_blocks);
11152 #endif
11153 }
11154
11155 enum lfs_som_type {
11156         LFS_SOM_SIZE = 0x1,
11157         LFS_SOM_BLOCKS = 0x2,
11158         LFS_SOM_FLAGS = 0x4,
11159         LFS_SOM_ATTR_ALL = LFS_SOM_SIZE | LFS_SOM_BLOCKS |
11160                            LFS_SOM_FLAGS,
11161 };
11162
11163 static int lfs_getsom(int argc, char **argv)
11164 {
11165         const char *path;
11166         struct lustre_som_attrs *attrs;
11167         char buf[sizeof(*attrs) + 64];
11168         enum lfs_som_type type = LFS_SOM_ATTR_ALL;
11169         int rc = 0, c;
11170
11171         while ((c = getopt(argc, argv, "sbf")) != -1) {
11172                 switch (c) {
11173                 case 's':
11174                         type = LFS_SOM_SIZE;
11175                         break;
11176                 case 'b':
11177                         type = LFS_SOM_BLOCKS;
11178                         break;
11179                 case 'f':
11180                         type = LFS_SOM_FLAGS;
11181                         break;
11182                 default:
11183                         fprintf(stderr, "%s: invalid option '%c'\n",
11184                                 progname, optopt);
11185                         return CMD_HELP;
11186                 }
11187         }
11188
11189         argc -= optind;
11190         argv += optind;
11191
11192         if (argc != 1) {
11193                 fprintf(stderr, "%s: %s\n",
11194                         progname, argc == 0 ? "miss file target" :
11195                         "input more than 2 files");
11196                 return CMD_HELP;
11197         }
11198
11199         path = argv[0];
11200         attrs = (void *)buf;
11201         rc = lgetxattr(path, "trusted.som", attrs, sizeof(buf));
11202         if (rc < 0) {
11203                 rc = -errno;
11204                 fprintf(stderr, "%s failed to get som xattr: %s (%d)\n",
11205                         argv[0], strerror(errno), errno);
11206                 return rc;
11207         }
11208
11209         lustre_som_swab(attrs);
11210
11211         switch (type) {
11212         case LFS_SOM_ATTR_ALL:
11213                 printf("file: %s size: %llu blocks: %llu flags: %x\n",
11214                        path, (unsigned long long)attrs->lsa_size,
11215                        (unsigned long long)attrs->lsa_blocks,
11216                        attrs->lsa_valid);
11217                 break;
11218         case LFS_SOM_SIZE:
11219                 printf("%llu\n", (unsigned long long)attrs->lsa_size);
11220                 break;
11221         case LFS_SOM_BLOCKS:
11222                 printf("%llu\n", (unsigned long long)attrs->lsa_blocks);
11223                 break;
11224         case LFS_SOM_FLAGS:
11225                 printf("%x\n", attrs->lsa_valid);
11226                 break;
11227         default:
11228                 fprintf(stderr, "%s: unknown option\n", progname);
11229                 return CMD_HELP;
11230         }
11231
11232         return 0;
11233 }
11234
11235 /**
11236  * lfs_mirror_list_commands() - List lfs mirror commands.
11237  * @argc: The count of command line arguments.
11238  * @argv: Array of strings for command line arguments.
11239  *
11240  * This function lists lfs mirror commands defined in mirror_cmdlist[].
11241  *
11242  * Return: 0 on success.
11243  */
11244 static int lfs_mirror_list_commands(int argc, char **argv)
11245 {
11246         char buffer[81] = "";
11247
11248         Parser_list_commands(mirror_cmdlist, buffer, sizeof(buffer),
11249                              NULL, 0, 4);
11250
11251         return 0;
11252 }
11253
11254 static int lfs_pcc_attach(int argc, char **argv)
11255 {
11256         struct option long_opts[] = {
11257         { .val = 'i',   .name = "id",   .has_arg = required_argument },
11258         { .name = NULL } };
11259         int c;
11260         int rc = 0;
11261         __u32 archive_id = 0;
11262         const char *path;
11263         char *end;
11264         char fullpath[PATH_MAX];
11265         enum lu_pcc_type type = LU_PCC_READWRITE;
11266
11267         optind = 0;
11268         while ((c = getopt_long(argc, argv, "i:",
11269                                 long_opts, NULL)) != -1) {
11270                 switch (c) {
11271                 case 'i':
11272                         archive_id = strtoul(optarg, &end, 0);
11273                         if (*end != '\0' || archive_id == 0) {
11274                                 fprintf(stderr,
11275                                         "error: %s: bad archive ID '%s'\n",
11276                                         argv[0], optarg);
11277                                 return CMD_HELP;
11278                         }
11279                         break;
11280                 case '?':
11281                         return CMD_HELP;
11282                 default:
11283                         fprintf(stderr, "%s: option '%s' unrecognized\n",
11284                                 argv[0], argv[optind - 1]);
11285                         return CMD_HELP;
11286                 }
11287         }
11288
11289         if (archive_id == 0) {
11290                 fprintf(stderr, "%s: must specify attach ID\n", argv[0]);
11291                 return CMD_HELP;
11292         }
11293
11294         if (argc <= optind) {
11295                 fprintf(stderr, "%s: must specify one or more file names\n",
11296                         argv[0]);
11297                 return CMD_HELP;
11298         }
11299
11300         while (optind < argc) {
11301                 int rc2;
11302
11303                 path = argv[optind++];
11304                 if (!realpath(path, fullpath)) {
11305                         fprintf(stderr, "%s: could not find path '%s': %s\n",
11306                                 argv[0], path, strerror(errno));
11307                         if (rc == 0)
11308                                 rc = -EINVAL;
11309                         continue;
11310                 }
11311
11312                 rc2 = llapi_pcc_attach(fullpath, archive_id, type);
11313                 if (rc2 < 0) {
11314                         fprintf(stderr,
11315                                 "%s: cannot attach '%s' to PCC with archive ID '%u': %s\n",
11316                                 argv[0], path, archive_id, strerror(-rc2));
11317                         if (rc == 0)
11318                                 rc = rc2;
11319                 }
11320         }
11321         return rc;
11322 }
11323
11324 static int lfs_pcc_attach_fid(int argc, char **argv)
11325 {
11326         struct option long_opts[] = {
11327         { .val = 'i',   .name = "id",   .has_arg = required_argument },
11328         { .val = 'm',   .name = "mnt",  .has_arg = required_argument },
11329         { .name = NULL } };
11330         char                     short_opts[] = "i:m:";
11331         int                      c;
11332         int                      rc = 0;
11333         __u32                    archive_id = 0;
11334         char                    *end;
11335         const char              *mntpath = NULL;
11336         const char              *fidstr;
11337         enum lu_pcc_type         type = LU_PCC_READWRITE;
11338
11339         optind = 0;
11340         while ((c = getopt_long(argc, argv, short_opts,
11341                                 long_opts, NULL)) != -1) {
11342                 switch (c) {
11343                 case 'i':
11344                         archive_id = strtoul(optarg, &end, 0);
11345                         if (*end != '\0') {
11346                                 fprintf(stderr,
11347                                         "error: %s: bad archive ID '%s'\n",
11348                                         argv[0], optarg);
11349                                 return CMD_HELP;
11350                         }
11351                         break;
11352                 case 'm':
11353                         mntpath = optarg;
11354                         break;
11355                 case '?':
11356                         return CMD_HELP;
11357                 default:
11358                         fprintf(stderr, "%s: option '%s' unrecognized\n",
11359                                 argv[0], argv[optind - 1]);
11360                         return CMD_HELP;
11361                 }
11362         }
11363
11364         if (archive_id == 0) {
11365                 fprintf(stderr, "%s: must specify an archive ID\n", argv[0]);
11366                 return CMD_HELP;
11367         }
11368
11369         if (!mntpath) {
11370                 fprintf(stderr, "%s: must specify Lustre mount point\n",
11371                         argv[0]);
11372                 return CMD_HELP;
11373         }
11374
11375         if (argc <= optind) {
11376                 fprintf(stderr, "%s: must specify one or more fids\n", argv[0]);
11377                 return CMD_HELP;
11378         }
11379
11380         while (optind < argc) {
11381                 int rc2;
11382
11383                 fidstr = argv[optind++];
11384
11385                 rc2 = llapi_pcc_attach_fid_str(mntpath, fidstr,
11386                                                archive_id, type);
11387                 if (rc2 < 0) {
11388                         fprintf(stderr,
11389                                 "%s: cannot attach '%s' on '%s' to PCC with archive ID '%u': %s\n",
11390                                 argv[0], fidstr, mntpath, archive_id,
11391                                 strerror(rc2));
11392                 }
11393                 if (rc == 0 && rc2 < 0)
11394                         rc = rc2;
11395         }
11396         return rc;
11397 }
11398
11399 static int lfs_pcc_detach(int argc, char **argv)
11400 {
11401         struct option long_opts[] = {
11402         { .val = 'k',   .name = "keep", .has_arg = no_argument },
11403         { .name = NULL } };
11404         char                     short_opts[] = "k";
11405         int                      c;
11406         int                      rc = 0;
11407         const char              *path;
11408         char                     fullpath[PATH_MAX];
11409         __u32                    detach_opt = PCC_DETACH_OPT_UNCACHE;
11410
11411         optind = 0;
11412         while ((c = getopt_long(argc, argv, short_opts,
11413                                 long_opts, NULL)) != -1) {
11414                 switch (c) {
11415                 case 'k':
11416                         detach_opt = PCC_DETACH_OPT_NONE;
11417                         break;
11418                 case '?':
11419                         return CMD_HELP;
11420                 default:
11421                         fprintf(stderr, "%s: option '%s' unrecognized\n",
11422                                 argv[0], argv[optind - 1]);
11423                         return CMD_HELP;
11424                 }
11425         }
11426
11427         while (optind < argc) {
11428                 int rc2;
11429
11430                 path = argv[optind++];
11431                 if (!realpath(path, fullpath)) {
11432                         fprintf(stderr, "%s: could not find path '%s': %s\n",
11433                                 argv[0], path, strerror(errno));
11434                         if (rc == 0)
11435                                 rc = -EINVAL;
11436                         continue;
11437                 }
11438
11439                 rc2 = llapi_pcc_detach_file(fullpath, detach_opt);
11440                 if (rc2 < 0) {
11441                         rc2 = -errno;
11442                         fprintf(stderr,
11443                                 "%s: cannot detach '%s' from PCC: %s\n",
11444                                 argv[0], path, strerror(errno));
11445                         if (rc == 0)
11446                                 rc = rc2;
11447                 }
11448         }
11449         return rc;
11450 }
11451
11452 static int lfs_pcc_detach_fid(int argc, char **argv)
11453 {
11454         struct option long_opts[] = {
11455         { .val = 'k',   .name = "keep", .has_arg = no_argument },
11456         { .name = NULL } };
11457         char             short_opts[] = "k";
11458         int              c;
11459         int              rc = 0;
11460         const char      *fid;
11461         const char      *mntpath;
11462         __u32            detach_opt = PCC_DETACH_OPT_UNCACHE;
11463
11464         optind = 0;
11465         while ((c = getopt_long(argc, argv, short_opts,
11466                                 long_opts, NULL)) != -1) {
11467                 switch (c) {
11468                 case 'k':
11469                         detach_opt = PCC_DETACH_OPT_NONE;
11470                         break;
11471                 case '?':
11472                         return CMD_HELP;
11473                 default:
11474                         fprintf(stderr, "%s: option '%s' unrecognized\n",
11475                                 argv[0], argv[optind - 1]);
11476                         return CMD_HELP;
11477                 }
11478         }
11479
11480         mntpath = argv[optind++];
11481
11482         while (optind < argc) {
11483                 int rc2;
11484
11485                 fid = argv[optind++];
11486
11487                 rc2 = llapi_pcc_detach_fid_str(mntpath, fid, detach_opt);
11488                 if (rc2 < 0) {
11489                         fprintf(stderr,
11490                                 "%s: cannot detach '%s' on '%s' from PCC: %s\n",
11491                                 argv[0], fid, mntpath, strerror(-rc2));
11492                         if (rc == 0)
11493                                 rc = rc2;
11494                 }
11495         }
11496         return rc;
11497 }
11498
11499 static int lfs_pcc_state(int argc, char **argv)
11500 {
11501         int                      rc = 0;
11502         const char              *path;
11503         char                     fullpath[PATH_MAX];
11504         struct lu_pcc_state      state;
11505
11506         optind = 1;
11507
11508         if (argc <= 1) {
11509                 fprintf(stderr, "%s: must specify one or more file names\n",
11510                         argv[0]);
11511                 return CMD_HELP;
11512         }
11513
11514         while (optind < argc) {
11515                 int rc2;
11516
11517                 path = argv[optind++];
11518                 if (!realpath(path, fullpath)) {
11519                         fprintf(stderr, "%s: could not find path '%s': %s\n",
11520                                 argv[0], path, strerror(errno));
11521                         if (rc == 0)
11522                                 rc = -EINVAL;
11523                         continue;
11524                 }
11525
11526                 rc2 = llapi_pcc_state_get(fullpath, &state);
11527                 if (rc2 < 0) {
11528                         if (rc == 0)
11529                                 rc = rc2;
11530                         fprintf(stderr,
11531                                 "%s: cannot get PCC state of '%s': %s\n",
11532                                 argv[0], path, strerror(-rc2));
11533                         continue;
11534                 }
11535
11536                 printf("file: %s", path);
11537                 printf(", type: %s", pcc_type2string(state.pccs_type));
11538                 if (state.pccs_type == LU_PCC_NONE &&
11539                     state.pccs_open_count == 0) {
11540                         printf("\n");
11541                         continue;
11542                 }
11543
11544                 printf(", PCC file: %s", state.pccs_path);
11545                 printf(", user number: %u", state.pccs_open_count);
11546                 printf(", flags: %x", state.pccs_flags);
11547                 printf("\n");
11548         }
11549         return rc;
11550 }
11551
11552 /**
11553  * lfs_pcc_list_commands() - List lfs pcc commands.
11554  * @argc: The count of command line arguments.
11555  * @argv: Array of strings for command line arguments.
11556  *
11557  * This function lists lfs pcc commands defined in pcc_cmdlist[].
11558  *
11559  * Return: 0 on success.
11560  */
11561 static int lfs_pcc_list_commands(int argc, char **argv)
11562 {
11563         char buffer[81] = "";
11564
11565         Parser_list_commands(pcc_cmdlist, buffer, sizeof(buffer),
11566                              NULL, 0, 4);
11567
11568         return 0;
11569 }
11570
11571 /**
11572  * lfs_pcc() - Parse and execute lfs pcc commands.
11573  * @argc: The count of lfs pcc command line arguments.
11574  * @argv: Array of strings for lfs pcc command line arguments.
11575  *
11576  * This function parses lfs pcc commands and performs the
11577  * corresponding functions specified in pcc_cmdlist[].
11578  *
11579  * Return: 0 on success or an error code on failure.
11580  */
11581 static int lfs_pcc(int argc, char **argv)
11582 {
11583         char cmd[PATH_MAX];
11584         int rc = 0;
11585
11586         setlinebuf(stdout);
11587
11588         Parser_init("lfs-pcc > ", pcc_cmdlist);
11589
11590         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
11591         progname = cmd;
11592         program_invocation_short_name = cmd;
11593         if (argc > 1)
11594                 rc = Parser_execarg(argc - 1, argv + 1, pcc_cmdlist);
11595         else
11596                 rc = Parser_commands();
11597
11598         return rc < 0 ? -rc : rc;
11599 }
11600
11601 static int lfs_list_commands(int argc, char **argv)
11602 {
11603         char buffer[81] = ""; /* 80 printable chars + terminating NUL */
11604
11605         Parser_list_commands(cmdlist, buffer, sizeof(buffer), NULL, 0, 4);
11606
11607         return 0;
11608 }
11609
11610 int main(int argc, char **argv)
11611 {
11612         int rc;
11613
11614         /* Ensure that liblustreapi constructor has run */
11615         if (!llapi_liblustreapi_initialized())
11616                 fprintf(stderr, "liblustreapi was not properly initialized\n");
11617
11618         setlinebuf(stdout);
11619         opterr = 0;
11620
11621         Parser_init("lfs > ", cmdlist);
11622
11623         progname = program_invocation_short_name; /* Used in error messages */
11624         if (argc > 1) {
11625                 llapi_set_command_name(argv[1]);
11626                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
11627                 llapi_clear_command_name();
11628         } else {
11629                 rc = Parser_commands();
11630         }
11631
11632         return rc < 0 ? -rc : rc;
11633 }
11634
11635 #ifdef _LUSTRE_IDL_H_
11636 /* Everything we need here should be included by lustreapi.h. */
11637 # error "lfs should not depend on lustre_idl.h"
11638 #endif /* _LUSTRE_IDL_H_ */