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