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