Whamcloud - gitweb
LU-14521 flr: delete mirror without volatile file
[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 (lsa.lsa_nr_tgts > 1) {
6606                 if (lsa.lsa_stripe_count > 0 &&
6607                     lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
6608                     lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
6609                         fprintf(stderr,
6610                                 "error: %s: stripe count %lld doesn't match the number of MDTs: %d\n",
6611                                 argv[0], lsa.lsa_stripe_count,
6612                                 lsa.lsa_nr_tgts);
6613                         free(param);
6614                         return CMD_HELP;
6615                 }
6616
6617                 param->lsp_is_specific = true;
6618                 param->lsp_stripe_count = lsa.lsa_nr_tgts;
6619                 memcpy(param->lsp_tgts, mdts, sizeof(*mdts) * lsa.lsa_nr_tgts);
6620         }
6621
6622         dname = argv[optind];
6623         do {
6624                 if (default_stripe) {
6625                         result = llapi_dir_set_default_lmv(dname, param);
6626                         if (result)
6627                                 fprintf(stderr,
6628                                         "%s setdirstripe: cannot set default stripe on dir '%s': %s\n",
6629                                         progname, dname, strerror(-result));
6630                         continue;
6631                 }
6632
6633                 result = llapi_dir_create(dname, mode, param);
6634                 if (result)
6635                         fprintf(stderr,
6636                                 "%s setdirstripe: cannot create dir '%s': %s\n",
6637                                 progname, dname, strerror(-result));
6638         } while (!result && (dname = argv[++optind]));
6639
6640         if (mode_opt)
6641                 umask(previous_mode);
6642
6643         free(param);
6644         return result;
6645 }
6646
6647 /* functions */
6648 static int lfs_rmentry(int argc, char **argv)
6649 {
6650         char *dname;
6651         int   index;
6652         int   result = 0;
6653
6654         if (argc <= 1) {
6655                 fprintf(stderr, "error: %s: missing dirname\n",
6656                         argv[0]);
6657                 return CMD_HELP;
6658         }
6659
6660         index = 1;
6661         dname = argv[index];
6662         while (dname) {
6663                 result = llapi_direntry_remove(dname);
6664                 if (result) {
6665                         fprintf(stderr,
6666                                 "error: %s: remove dir entry '%s' failed\n",
6667                                 argv[0], dname);
6668                         break;
6669                 }
6670                 dname = argv[++index];
6671         }
6672         return result;
6673 }
6674
6675 static int lfs_unlink_foreign(int argc, char **argv)
6676 {
6677         char *name;
6678         int   index;
6679         int   result = 0;
6680
6681         if (argc <= 1) {
6682                 fprintf(stderr, "error: %s: missing pathname\n",
6683                         argv[0]);
6684                 return CMD_HELP;
6685         }
6686
6687         index = 1;
6688         name = argv[index];
6689         while (name != NULL) {
6690                 result = llapi_unlink_foreign(name);
6691                 if (result) {
6692                         fprintf(stderr,
6693                                 "error: %s: unlink foreign entry '%s' failed\n",
6694                                 argv[0], name);
6695                         break;
6696                 }
6697                 name = argv[++index];
6698         }
6699         return result;
6700 }
6701
6702 static int lfs_mv(int argc, char **argv)
6703 {
6704         struct lmv_user_md lmu = { LMV_USER_MAGIC };
6705         struct find_param param = {
6706                 .fp_max_depth = -1,
6707                 .fp_mdt_index = -1,
6708         };
6709         char *end;
6710         int c;
6711         int rc = 0;
6712         struct option long_opts[] = {
6713         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
6714         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
6715         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
6716         { .name = NULL } };
6717
6718         while ((c = getopt_long(argc, argv, "m:M:v", long_opts, NULL)) != -1) {
6719                 switch (c) {
6720 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
6721                 case 'M':
6722                         fprintf(stderr,
6723                                 "warning: '-M' deprecated, use '--mdt-index' or '-m' instead\n");
6724 #endif
6725                 case 'm':
6726                         errno = 0;
6727                         lmu.lum_stripe_offset = strtoul(optarg, &end, 0);
6728                         if (errno != 0 || *end != '\0' ||
6729                             lmu.lum_stripe_offset >= UINT32_MAX) {
6730                                 fprintf(stderr, "%s mv: bad MDT index '%s'\n",
6731                                         progname, optarg);
6732                                 return CMD_HELP;
6733                         }
6734                         break;
6735                 case 'v':
6736                         param.fp_verbose = VERBOSE_DETAIL;
6737                         break;
6738                 default:
6739                         fprintf(stderr, "%s mv: unrecognized option '%s'\n",
6740                                 progname, argv[optind - 1]);
6741                         return CMD_HELP;
6742                 }
6743         }
6744
6745         if (lmu.lum_stripe_offset == LMV_OFFSET_DEFAULT) {
6746                 fprintf(stderr, "%s mv: MDT index must be specified\n",
6747                         progname);
6748                 return CMD_HELP;
6749         }
6750
6751         if (optind >= argc) {
6752                 fprintf(stderr, "%s mv: DIR must be specified\n", progname);
6753                 return CMD_HELP;
6754         }
6755
6756         lmu.lum_hash_type = LMV_HASH_TYPE_UNKNOWN;
6757
6758         /* initialize migrate mdt parameters */
6759         param.fp_lmv_md = &lmu;
6760         param.fp_migrate = 1;
6761         rc = llapi_migrate_mdt(argv[optind], &param);
6762         if (rc != 0)
6763                 fprintf(stderr, "%s mv: cannot migrate '%s' to MDT%04x: %s\n",
6764                         progname, argv[optind], lmu.lum_stripe_offset,
6765                         strerror(-rc));
6766         return rc;
6767 }
6768
6769 static int lfs_osts(int argc, char **argv)
6770 {
6771         return lfs_tgts(argc, argv);
6772 }
6773
6774 static int lfs_mdts(int argc, char **argv)
6775 {
6776         return lfs_tgts(argc, argv);
6777 }
6778
6779 static int lfs_df(int argc, char **argv)
6780 {
6781         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
6782         enum mntdf_flags flags = MNTDF_SHOW;
6783         int ops = LL_STATFS_LMV | LL_STATFS_LOV;
6784         int c, rc = 0, index = 0;
6785         char fsname[PATH_MAX] = "", *pool_name = NULL;
6786         struct option long_opts[] = {
6787         { .val = 'h',   .name = "human-readable", .has_arg = no_argument },
6788         { .val = 'H',   .name = "si",           .has_arg = no_argument },
6789         { .val = 'i',   .name = "inodes",       .has_arg = no_argument },
6790         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
6791         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
6792         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
6793         { .name = NULL} };
6794
6795         while ((c = getopt_long(argc, argv, "hHilp:v", long_opts, NULL)) != -1) {
6796                 switch (c) {
6797                 case 'h':
6798                         flags = (flags & ~MNTDF_DECIMAL) | MNTDF_COOKED;
6799                         break;
6800                 case 'H':
6801                         flags |= MNTDF_COOKED | MNTDF_DECIMAL;
6802                         break;
6803                 case 'i':
6804                         flags |= MNTDF_INODES;
6805                         break;
6806                 case 'l':
6807                         flags |= MNTDF_LAZY;
6808                         break;
6809                 case 'p':
6810                         pool_name = optarg;
6811                         break;
6812                 case 'v':
6813                         flags |= MNTDF_VERBOSE;
6814                         break;
6815                 default:
6816                         return CMD_HELP;
6817                 }
6818         }
6819         if (optind < argc && !realpath(argv[optind], path)) {
6820                 rc = -errno;
6821                 fprintf(stderr, "error: invalid path '%s': %s\n",
6822                         argv[optind], strerror(-rc));
6823                 return rc;
6824         }
6825
6826         while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
6827                 /* Check if we have a mount point */
6828                 if (mntdir[0] == '\0')
6829                         continue;
6830
6831                 rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
6832                 if (rc || path[0] != '\0')
6833                         break;
6834                 fsname[0] = '\0'; /* avoid matching in next loop */
6835                 mntdir[0] = '\0'; /* avoid matching in next loop */
6836         }
6837
6838         return rc;
6839 }
6840
6841 static int print_instance(const char *mntdir, char *buf, size_t buflen,
6842                           bool opt_instance, bool opt_fsname, bool opt_mntdir)
6843 {
6844         int rc = 0;
6845
6846         if (opt_fsname == opt_instance) { /* both true or both false */
6847                 rc = llapi_getname(mntdir, buf, buflen);
6848         } else if (opt_fsname) {
6849                 /*
6850                  * llapi_search_mounts() fills @buf with fsname, but that is not
6851                  * called if explicit paths are specified on the command-line
6852                  */
6853                 if (buf[0] == '\0')
6854                         rc = llapi_get_fsname(mntdir, buf, buflen);
6855         } else /* if (opt_instance) */ {
6856                 rc = llapi_get_instance(mntdir, buf, buflen);
6857         }
6858
6859         if (rc < 0) {
6860                 fprintf(stderr, "cannot get instance for '%s': %s\n",
6861                         mntdir, strerror(-rc));
6862                 return rc;
6863         }
6864
6865         if (opt_mntdir)
6866                 printf("%s %s\n", buf, mntdir);
6867         else
6868                 printf("%s\n", buf);
6869
6870         return 0;
6871 }
6872
6873 static int lfs_getname(int argc, char **argv)
6874 {
6875         struct option long_opts[] = {
6876         { .val = 'h',   .name = "help",         .has_arg = no_argument },
6877         { .val = 'i',   .name = "instance",     .has_arg = no_argument },
6878         { .val = 'n',   .name = "fsname",       .has_arg = no_argument },
6879         { .name = NULL} };
6880         bool opt_instance = false, opt_fsname = false;
6881         char fsname[PATH_MAX] = "";
6882         int rc = 0, rc2, c;
6883
6884         while ((c = getopt_long(argc, argv, "hin", long_opts, NULL)) != -1) {
6885                 switch (c) {
6886                 case 'i':
6887                         opt_instance = true;
6888                         break;
6889                 case 'n':
6890                         opt_fsname = true;
6891                         break;
6892                 case 'h':
6893                 default:
6894                         return CMD_HELP;
6895                 }
6896         }
6897
6898         if (optind == argc) { /* no paths specified, get all paths. */
6899                 char mntdir[PATH_MAX] = "", path[PATH_MAX] = "";
6900                 int index = 0;
6901
6902                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
6903                         rc2 = print_instance(mntdir, fsname, sizeof(fsname),
6904                                              opt_instance, opt_fsname, true);
6905                         if (!rc)
6906                                 rc = rc2;
6907                         path[0] = fsname[0] = mntdir[0] = '\0';
6908                 }
6909         } else { /* paths specified, only attempt to search these. */
6910                 bool opt_mntdir;
6911
6912                 /* if only one path is given, print only requested info */
6913                 opt_mntdir = argc - optind > 1 || (opt_instance == opt_fsname);
6914
6915                 for (; optind < argc; optind++) {
6916                         rc2 = print_instance(argv[optind], fsname,
6917                                              sizeof(fsname), opt_instance,
6918                                              opt_fsname, opt_mntdir);
6919                         if (!rc)
6920                                 rc = rc2;
6921                         fsname[0] = '\0';
6922                 }
6923         }
6924
6925         return rc;
6926 }
6927
6928 static int lfs_check(int argc, char **argv)
6929 {
6930         char mntdir[PATH_MAX] = {'\0'};
6931         int num_types = 1;
6932         char *obd_types[3];
6933         char obd_type1[4];
6934         char obd_type2[4];
6935         char obd_type3[4];
6936         int rc;
6937
6938         if (argc != 2) {
6939                 fprintf(stderr, "%s check: server type must be specified\n",
6940                         progname);
6941                 return CMD_HELP;
6942         }
6943
6944         obd_types[0] = obd_type1;
6945         obd_types[1] = obd_type2;
6946         obd_types[2] = obd_type3;
6947
6948         if (strcmp(argv[1], "osts") == 0) {
6949                 strcpy(obd_types[0], "osc");
6950         } else if (strcmp(argv[1], "mdts") == 0 ||
6951                    strcmp(argv[1], "mds") == 0) {
6952                 strcpy(obd_types[0], "mdc");
6953         } else if (strcmp(argv[1], "mgts") == 0) {
6954                 strcpy(obd_types[0], "mgc");
6955         } else if (strcmp(argv[1], "all") == 0 ||
6956                    strcmp(argv[1], "servers") == 0) {
6957                 num_types = 3;
6958                 strcpy(obd_types[0], "osc");
6959                 strcpy(obd_types[1], "mdc");
6960                 strcpy(obd_types[2], "mgc");
6961         } else {
6962                 fprintf(stderr, "%s check: unrecognized option '%s'\n",
6963                         progname, argv[1]);
6964                 return CMD_HELP;
6965         }
6966
6967         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
6968         if (rc < 0 || mntdir[0] == '\0') {
6969                 fprintf(stderr,
6970                         "%s check: cannot find mounted Lustre filesystem: %s\n",
6971                         progname, (rc < 0) ? strerror(-rc) : strerror(ENODEV));
6972                 return rc;
6973         }
6974
6975         rc = llapi_target_check(num_types, obd_types, mntdir);
6976         if (rc)
6977                 fprintf(stderr, "%s check: cannot check target '%s': %s\n",
6978                         progname, argv[1], strerror(-rc));
6979
6980         return rc;
6981 }
6982
6983 #ifdef HAVE_SYS_QUOTA_H
6984 #define ADD_OVERFLOW(a, b) \
6985                      ((((a) + (b)) < (a)) ? \
6986                       ((a) = ULONG_MAX) : ((a) = (a) + (b)))
6987
6988 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
6989  * returns the value or ULONG_MAX on integer overflow or incorrect format
6990  * Notes:
6991  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
6992  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
6993  *        3. empty integer value is interpreted as 0
6994  */
6995 static unsigned long str2sec(const char *timestr)
6996 {
6997         const char spec[] = "smhdw";
6998         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
6999         unsigned long val = 0;
7000         char *tail;
7001
7002         if (strpbrk(timestr, spec) == NULL) {
7003                 /*
7004                  * no specifiers inside the time string,
7005                  * should treat it as an integer value
7006                  */
7007                 val = strtoul(timestr, &tail, 10);
7008                 return *tail ? ULONG_MAX : val;
7009         }
7010
7011         /* format string is XXwXXdXXhXXmXXs */
7012         while (*timestr) {
7013                 unsigned long v;
7014                 int ind;
7015                 char *ptr;
7016
7017                 v = strtoul(timestr, &tail, 10);
7018                 if (v == ULONG_MAX || *tail == '\0')
7019                         /*
7020                          * value too large (ULONG_MAX or more)
7021                          * or missing specifier
7022                          */
7023                         goto error;
7024
7025                 ptr = strchr(spec, *tail);
7026                 if (!ptr)
7027                         /* unknown specifier */
7028                         goto error;
7029
7030                 ind = ptr - spec;
7031
7032                 /* check if product will overflow the type */
7033                 if (!(v < ULONG_MAX / mult[ind]))
7034                         goto error;
7035
7036                 ADD_OVERFLOW(val, mult[ind] * v);
7037                 if (val == ULONG_MAX)
7038                         goto error;
7039
7040                 timestr = tail + 1;
7041         }
7042
7043         return val;
7044
7045 error:
7046         return ULONG_MAX;
7047 }
7048
7049 #define ARG2ULL(nr, str, def_units)                                     \
7050 do {                                                                    \
7051         unsigned long long limit, units = def_units;                    \
7052         int rc;                                                         \
7053                                                                         \
7054         rc = llapi_parse_size(str, &limit, &units, 1);                  \
7055         if (rc < 0) {                                                   \
7056                 fprintf(stderr, "%s: invalid limit '%s'\n",             \
7057                         progname, str);                                 \
7058                 return CMD_HELP;                                        \
7059         }                                                               \
7060         nr = limit;                                                     \
7061 } while (0)
7062
7063 static inline int has_times_option(int argc, char **argv)
7064 {
7065         int i;
7066
7067         for (i = 1; i < argc; i++)
7068                 if (!strcmp(argv[i], "-t"))
7069                         return 1;
7070
7071         return 0;
7072 }
7073
7074 static inline int lfs_verify_poolarg(char *pool)
7075 {
7076         if (strnlen(optarg, LOV_MAXPOOLNAME + 1) > LOV_MAXPOOLNAME) {
7077                 fprintf(stderr,
7078                         "Pool name '%.*s' is longer than %d\n",
7079                         LOV_MAXPOOLNAME, pool, LOV_MAXPOOLNAME);
7080                 return 1;
7081         }
7082         return 0;
7083 }
7084
7085 int lfs_setquota_times(int argc, char **argv, struct if_quotactl *qctl)
7086 {
7087         int c, rc;
7088         char *mnt, *obd_type = (char *)qctl->obd_type;
7089         struct obd_dqblk *dqb = &qctl->qc_dqblk;
7090         struct obd_dqinfo *dqi = &qctl->qc_dqinfo;
7091         struct option long_opts[] = {
7092         { .val = 'b',   .name = "block-grace",  .has_arg = required_argument },
7093         { .val = 'g',   .name = "group",        .has_arg = no_argument },
7094         { .val = 'i',   .name = "inode-grace",  .has_arg = required_argument },
7095         { .val = 'p',   .name = "projid",       .has_arg = no_argument },
7096         { .val = 't',   .name = "times",        .has_arg = no_argument },
7097         { .val = 'u',   .name = "user",         .has_arg = no_argument },
7098         { .val = LFS_POOL_OPT,
7099                         .name = "pool",         .has_arg = required_argument },
7100         { .name = NULL } };
7101         int qtype;
7102
7103         qctl->qc_cmd  = LUSTRE_Q_SETINFO;
7104         qctl->qc_type = ALLQUOTA;
7105
7106         while ((c = getopt_long(argc, argv, "b:gi:ptu",
7107                                 long_opts, NULL)) != -1) {
7108                 switch (c) {
7109                 case 'u':
7110                         qtype = USRQUOTA;
7111                         goto quota_type;
7112                 case 'g':
7113                         qtype = GRPQUOTA;
7114                         goto quota_type;
7115                 case 'p':
7116                         qtype = PRJQUOTA;
7117 quota_type:
7118                         if (qctl->qc_type != ALLQUOTA) {
7119                                 fprintf(stderr,
7120                                         "error: -u/g/p can't be used more than once\n");
7121                                 return CMD_HELP;
7122                         }
7123                         qctl->qc_type = qtype;
7124                         break;
7125                 case 'b':
7126                         if (strncmp(optarg, NOTIFY_GRACE,
7127                                     strlen(NOTIFY_GRACE)) == 0) {
7128                                 dqi->dqi_bgrace = NOTIFY_GRACE_TIME;
7129                         } else {
7130                                 dqi->dqi_bgrace = str2sec(optarg);
7131                                 if (dqi->dqi_bgrace >= NOTIFY_GRACE_TIME) {
7132                                         fprintf(stderr,
7133                                                 "error: bad block-grace: %s\n",
7134                                                 optarg);
7135                                         return CMD_HELP;
7136                                 }
7137                         }
7138                         dqb->dqb_valid |= QIF_BTIME;
7139                         break;
7140                 case 'i':
7141                         if (strncmp(optarg, NOTIFY_GRACE,
7142                                     strlen(NOTIFY_GRACE)) == 0) {
7143                                 dqi->dqi_igrace = NOTIFY_GRACE_TIME;
7144                         } else {
7145                                 dqi->dqi_igrace = str2sec(optarg);
7146                                 if (dqi->dqi_igrace >= NOTIFY_GRACE_TIME) {
7147                                         fprintf(stderr,
7148                                                 "error: bad inode-grace: %s\n",
7149                                                 optarg);
7150                                         return CMD_HELP;
7151                                 }
7152                         }
7153                         dqb->dqb_valid |= QIF_ITIME;
7154                         break;
7155                 case 't': /* Yes, of course! */
7156                         break;
7157                 case LFS_POOL_OPT:
7158                         if (lfs_verify_poolarg(optarg))
7159                                 return -1;
7160                         fprintf(stdout,
7161                                 "Trying to set grace for pool %s\n", optarg);
7162                         strncpy(qctl->qc_poolname, optarg, LOV_MAXPOOLNAME);
7163                         qctl->qc_cmd  = LUSTRE_Q_SETINFOPOOL;
7164                         break;
7165                 /* getopt prints error message for us when opterr != 0 */
7166                 default:
7167                         return CMD_HELP;
7168                 }
7169         }
7170
7171         if (qctl->qc_type == ALLQUOTA) {
7172                 fprintf(stderr, "error: neither -u, -g nor -p specified\n");
7173                 return CMD_HELP;
7174         }
7175
7176         if (optind != argc - 1) {
7177                 fprintf(stderr, "error: unexpected parameters encountered\n");
7178                 return CMD_HELP;
7179         }
7180
7181         mnt = argv[optind];
7182         rc = llapi_quotactl(mnt, qctl);
7183         if (rc) {
7184                 if (*obd_type)
7185                         fprintf(stderr, "%s %s ", obd_type,
7186                                 obd_uuid2str(&qctl->obd_uuid));
7187                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
7188                 return rc;
7189         }
7190
7191         return 0;
7192 }
7193
7194 #define BSLIMIT (1 << 0)
7195 #define BHLIMIT (1 << 1)
7196 #define ISLIMIT (1 << 2)
7197 #define IHLIMIT (1 << 3)
7198
7199 int lfs_setquota(int argc, char **argv)
7200 {
7201         int c, rc = 0;
7202         struct if_quotactl *qctl;
7203         char *mnt, *obd_type;
7204         struct obd_dqblk *dqb;
7205         struct option long_opts[] = {
7206         { .val = 'b',   .name = "block-softlimit",
7207                                                 .has_arg = required_argument },
7208         { .val = 'B',   .name = "block-hardlimit",
7209                                                 .has_arg = required_argument },
7210         { .val = 'd',   .name = "default",      .has_arg = no_argument },
7211         { .val = 'g',   .name = "group",        .has_arg = required_argument },
7212         { .val = 'G',   .name = "default-grp",  .has_arg = no_argument },
7213         { .val = 'i',   .name = "inode-softlimit",
7214                                                 .has_arg = required_argument },
7215         { .val = 'I',   .name = "inode-hardlimit",
7216                                                 .has_arg = required_argument },
7217         { .val = 'p',   .name = "projid",       .has_arg = required_argument },
7218         { .val = 'P',   .name = "default-prj",  .has_arg = no_argument },
7219         { .val = 'u',   .name = "user",         .has_arg = required_argument },
7220         { .val = 'U',   .name = "default-usr",  .has_arg = no_argument },
7221         { .val = LFS_POOL_OPT,
7222                         .name = "pool",         .has_arg = required_argument },
7223         { .name = NULL } };
7224         unsigned int limit_mask = 0;
7225         bool use_default = false;
7226         int qtype, qctl_len;
7227
7228         qctl_len = sizeof(*qctl) + LOV_MAXPOOLNAME + 1;
7229         qctl = malloc(qctl_len);
7230         if (!qctl)
7231                 return -ENOMEM;
7232
7233         memset(qctl, 0, qctl_len);
7234         obd_type = (char *)qctl->obd_type;
7235         dqb = &qctl->qc_dqblk;
7236
7237         if (has_times_option(argc, argv)) {
7238                 rc = lfs_setquota_times(argc, argv, qctl);
7239                 goto out;
7240         }
7241
7242         qctl->qc_cmd  = LUSTRE_Q_SETQUOTA;
7243         qctl->qc_type = ALLQUOTA; /* ALLQUOTA makes no sense for setquota,
7244                                    * so it can be used as a marker that qc_type
7245                                    * isn't reinitialized from command line
7246                                    */
7247
7248         while ((c = getopt_long(argc, argv, "b:B:dg:Gi:I:p:Pu:U",
7249                 long_opts, NULL)) != -1) {
7250                 switch (c) {
7251                 case 'U':
7252                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7253                         qtype = USRQUOTA;
7254                         qctl->qc_id = 0;
7255                         goto quota_type_def;
7256                 case 'u':
7257                         qtype = USRQUOTA;
7258                         rc = name2uid(&qctl->qc_id, optarg);
7259                         goto quota_type;
7260                 case 'G':
7261                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7262                         qtype = GRPQUOTA;
7263                         qctl->qc_id = 0;
7264                         goto quota_type_def;
7265                 case 'g':
7266                         qtype = GRPQUOTA;
7267                         rc = name2gid(&qctl->qc_id, optarg);
7268                         goto quota_type;
7269                 case 'P':
7270                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7271                         qtype = PRJQUOTA;
7272                         qctl->qc_id = 0;
7273                         goto quota_type_def;
7274                 case 'p':
7275                         qtype = PRJQUOTA;
7276                         rc = name2projid(&qctl->qc_id, optarg);
7277 quota_type:
7278                         if (rc) {
7279                                 if (str2quotaid(&qctl->qc_id, optarg)) {
7280                                         fprintf(stderr,
7281                                                 "%s setquota: invalid id '%s'\n",
7282                                                 progname, optarg);
7283                                         rc = -1;
7284                                         goto out;
7285                                 }
7286                         }
7287
7288                         if (qctl->qc_id == 0) {
7289                                 fprintf(stderr,
7290                                         "%s setquota: can't set quota for root usr/group/project.\n",
7291                                         progname);
7292                                 rc = -1;
7293                                 goto out;
7294                         }
7295
7296 quota_type_def:
7297                         if (qctl->qc_type != ALLQUOTA) {
7298                                 fprintf(stderr,
7299                                         "%s setquota: only one of -u, -U, -g, -G, -p or -P may be specified\n",
7300                                         progname);
7301                                 rc = CMD_HELP;
7302                                 goto out;
7303                         }
7304                         qctl->qc_type = qtype;
7305                         break;
7306                 case 'd':
7307                         qctl->qc_cmd = LUSTRE_Q_SETDEFAULT;
7308                         use_default = true;
7309                         break;
7310                 case 'b':
7311                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
7312                         dqb->dqb_bsoftlimit >>= 10;
7313                         limit_mask |= BSLIMIT;
7314                         if (dqb->dqb_bsoftlimit &&
7315                             dqb->dqb_bsoftlimit <= 1024) /* <= 1M? */
7316                                 fprintf(stderr,
7317                                         "%s setquota: warning: block softlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
7318                                         progname,
7319                                         (unsigned long long)dqb->dqb_bsoftlimit,
7320                                         progname);
7321                         break;
7322                 case 'B':
7323                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
7324                         dqb->dqb_bhardlimit >>= 10;
7325                         limit_mask |= BHLIMIT;
7326                         if (dqb->dqb_bhardlimit &&
7327                             dqb->dqb_bhardlimit <= 1024) /* <= 1M? */
7328                                 fprintf(stderr,
7329                                         "%s setquota: warning: block hardlimit '%llu' smaller than minimum qunit size\n"
7330                                         "See '%s help setquota' or Lustre manual for details\n",
7331                                         progname,
7332                                         (unsigned long long)dqb->dqb_bhardlimit,
7333                                         progname);
7334                         break;
7335                 case 'i':
7336                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
7337                         limit_mask |= ISLIMIT;
7338                         if (dqb->dqb_isoftlimit &&
7339                             dqb->dqb_isoftlimit <= 1024) /* <= 1K inodes? */
7340                                 fprintf(stderr,
7341                                         "%s setquota: warning: inode softlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
7342                                         progname,
7343                                         (unsigned long long)dqb->dqb_isoftlimit,
7344                                         progname);
7345                         break;
7346                 case 'I':
7347                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
7348                         limit_mask |= IHLIMIT;
7349                         if (dqb->dqb_ihardlimit &&
7350                             dqb->dqb_ihardlimit <= 1024) /* <= 1K inodes? */
7351                                 fprintf(stderr,
7352                                         "%s setquota: warning: inode hardlimit '%llu' smaller than minimum qunit size\nSee '%s help setquota' or Lustre manual for details\n",
7353                                         progname,
7354                                         (unsigned long long)dqb->dqb_ihardlimit,
7355                                         progname);
7356                         break;
7357                 case LFS_POOL_OPT:
7358                         if (lfs_verify_poolarg(optarg)) {
7359                                 rc = -1;
7360                                 goto out;
7361                         }
7362                         fprintf(stdout,
7363                                 "Trying to set quota for pool %s\n", optarg);
7364                         strncpy(qctl->qc_poolname, optarg, LOV_MAXPOOLNAME);
7365                         qctl->qc_cmd  = LUSTRE_Q_SETQUOTAPOOL;
7366                         break;
7367                 default:
7368                         fprintf(stderr,
7369                                 "%s setquota: unrecognized option '%s'\n",
7370                                 progname, argv[optind - 1]);
7371                         rc = CMD_HELP;
7372                         goto out;
7373                 }
7374         }
7375
7376         if (qctl->qc_type == ALLQUOTA) {
7377                 fprintf(stderr,
7378                         "%s setquota: either -u or -g must be specified\n",
7379                         progname);
7380                 rc = CMD_HELP;
7381                 goto out;
7382         }
7383
7384         if (!use_default && limit_mask == 0) {
7385                 fprintf(stderr,
7386                         "%s setquota: at least one limit must be specified\n",
7387                         progname);
7388                 rc = CMD_HELP;
7389                 goto out;
7390         }
7391
7392         if (use_default && limit_mask != 0) {
7393                 fprintf(stderr,
7394                         "%s setquota: limits should not be specified when using default quota\n",
7395                         progname);
7396                 rc = CMD_HELP;
7397                 goto out;
7398         }
7399
7400         if (use_default && qctl->qc_id == 0) {
7401                 fprintf(stderr,
7402                         "%s setquota: can not set default quota for root user/group/project\n",
7403                         progname);
7404                 rc = CMD_HELP;
7405                 goto out;
7406         }
7407
7408         if (optind != argc - 1) {
7409                 fprintf(stderr,
7410                         "%s setquota: filesystem not specified or unexpected argument '%s'\n",
7411                         progname, argv[optind]);
7412                 rc = CMD_HELP;
7413                 goto out;
7414         }
7415
7416         mnt = argv[optind];
7417
7418         if (use_default) {
7419                 dqb->dqb_bhardlimit = 0;
7420                 dqb->dqb_bsoftlimit = 0;
7421                 dqb->dqb_ihardlimit = 0;
7422                 dqb->dqb_isoftlimit = 0;
7423                 dqb->dqb_itime = 0;
7424                 dqb->dqb_btime = 0;
7425                 dqb->dqb_valid |= QIF_LIMITS | QIF_TIMES;
7426         } else if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
7427                    (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
7428                 /* sigh, we can't just set blimits/ilimits */
7429                 struct if_quotactl tmp_qctl = {.qc_cmd  = LUSTRE_Q_GETQUOTA,
7430                                                .qc_type = qctl->qc_type,
7431                                                .qc_id   = qctl->qc_id};
7432
7433                 rc = llapi_quotactl(mnt, &tmp_qctl);
7434                 if (rc < 0)
7435                         goto out;
7436
7437                 if (!(limit_mask & BHLIMIT))
7438                         dqb->dqb_bhardlimit = tmp_qctl.qc_dqblk.dqb_bhardlimit;
7439                 if (!(limit_mask & BSLIMIT))
7440                         dqb->dqb_bsoftlimit = tmp_qctl.qc_dqblk.dqb_bsoftlimit;
7441                 if (!(limit_mask & IHLIMIT))
7442                         dqb->dqb_ihardlimit = tmp_qctl.qc_dqblk.dqb_ihardlimit;
7443                 if (!(limit_mask & ISLIMIT))
7444                         dqb->dqb_isoftlimit = tmp_qctl.qc_dqblk.dqb_isoftlimit;
7445
7446                 /* Keep grace times if we have got no softlimit arguments */
7447                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
7448                         dqb->dqb_valid |= QIF_BTIME;
7449                         dqb->dqb_btime = tmp_qctl.qc_dqblk.dqb_btime;
7450                 }
7451
7452                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
7453                         dqb->dqb_valid |= QIF_ITIME;
7454                         dqb->dqb_itime = tmp_qctl.qc_dqblk.dqb_itime;
7455                 }
7456         }
7457
7458         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
7459         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
7460
7461         rc = llapi_quotactl(mnt, qctl);
7462         if (rc) {
7463                 if (*obd_type)
7464                         fprintf(stderr,
7465                                 "%s setquota: cannot quotactl '%s' '%s': %s",
7466                                 progname, obd_type,
7467                                 obd_uuid2str(&qctl->obd_uuid), strerror(-rc));
7468         }
7469 out:
7470         free(qctl);
7471         return rc;
7472 }
7473
7474 /* Converts seconds value into format string
7475  * result is returned in buf
7476  * Notes:
7477  *        1. result is in descenting order: 1w2d3h4m5s
7478  *        2. zero fields are not filled (except for p. 3): 5d1s
7479  *        3. zero seconds value is presented as "0s"
7480  */
7481 static char *__sec2str(time_t seconds, char *buf)
7482 {
7483         const char spec[] = "smhdw";
7484         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
7485         unsigned long c;
7486         char *tail = buf;
7487         int i;
7488
7489         for (i = ARRAY_SIZE(mult) - 1 ; i >= 0; i--) {
7490                 c = seconds / mult[i];
7491
7492                 if (c > 0 || (i == 0 && buf == tail))
7493                         tail += scnprintf(tail, 40-(tail-buf), "%lu%c", c,
7494                                           spec[i]);
7495
7496                 seconds %= mult[i];
7497         }
7498
7499         return tail;
7500 }
7501
7502 static void sec2str(time_t seconds, char *buf, int rc)
7503 {
7504         char *tail = buf;
7505
7506         if (rc)
7507                 *tail++ = '[';
7508
7509         tail = __sec2str(seconds, tail);
7510
7511         if (rc && tail - buf < 39) {
7512                 *tail++ = ']';
7513                 *tail++ = 0;
7514         }
7515 }
7516
7517 static void diff2str(time_t seconds, char *buf, time_t now)
7518 {
7519         buf[0] = 0;
7520         if (!seconds)
7521                 return;
7522         if (seconds <= now) {
7523                 strcpy(buf, "none");
7524                 return;
7525         }
7526         __sec2str(seconds - now, buf);
7527 }
7528
7529 static void print_quota_title(char *name, struct if_quotactl *qctl,
7530                               bool human_readable, bool show_default)
7531 {
7532         if (show_default) {
7533                 printf("Disk default %s quota:\n", qtype_name(qctl->qc_type));
7534                 printf("%15s %8s%8s%8s %8s%8s%8s\n",
7535                        "Filesystem", "bquota", "blimit", "bgrace",
7536                        "iquota", "ilimit", "igrace");
7537         } else {
7538                 printf("Disk quotas for %s %s (%cid %u):\n",
7539                        qtype_name(qctl->qc_type), name,
7540                        *qtype_name(qctl->qc_type), qctl->qc_id);
7541                 printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
7542                        "Filesystem", human_readable ? "used" : "kbytes",
7543                        "quota", "limit", "grace",
7544                        "files", "quota", "limit", "grace");
7545         }
7546 }
7547
7548 static void kbytes2str(__u64 num, char *buf, int buflen, bool h)
7549 {
7550         if (!h) {
7551                 snprintf(buf, buflen, "%ju", (uintmax_t)num);
7552         } else {
7553                 if (num >> 40)
7554                         snprintf(buf, buflen, "%5.4gP",
7555                                  (double)num / ((__u64)1 << 40));
7556                 else if (num >> 30)
7557                         snprintf(buf, buflen, "%5.4gT",
7558                                  (double)num / (1 << 30));
7559                 else if (num >> 20)
7560                         snprintf(buf, buflen, "%5.4gG",
7561                                  (double)num / (1 << 20));
7562                 else if (num >> 10)
7563                         snprintf(buf, buflen, "%5.4gM",
7564                                  (double)num / (1 << 10));
7565                 else
7566                         snprintf(buf, buflen, "%ju%s", (uintmax_t)num, "k");
7567         }
7568 }
7569
7570 #define STRBUF_LEN      32
7571 static void print_quota(char *mnt, struct if_quotactl *qctl, int type,
7572                         int rc, bool h, bool show_default)
7573 {
7574         time_t now;
7575
7576         time(&now);
7577
7578         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA ||
7579             qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ||
7580             qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) {
7581                 int bover = 0, iover = 0;
7582                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
7583                 char numbuf[3][STRBUF_LEN];
7584                 char timebuf[40];
7585                 char strbuf[STRBUF_LEN];
7586
7587                 if (dqb->dqb_bhardlimit &&
7588                     lustre_stoqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
7589                         bover = 1;
7590                 } else if (dqb->dqb_bsoftlimit && dqb->dqb_btime) {
7591                         if (dqb->dqb_btime > now)
7592                                 bover = 2;
7593                         else
7594                                 bover = 3;
7595                 }
7596
7597                 if (dqb->dqb_ihardlimit &&
7598                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
7599                         iover = 1;
7600                 } else if (dqb->dqb_isoftlimit && dqb->dqb_itime) {
7601                         if (dqb->dqb_itime > now)
7602                                 iover = 2;
7603                         else
7604                                 iover = 3;
7605                 }
7606
7607                 if (strlen(mnt) > 15)
7608                         printf("%s\n%15s", mnt, "");
7609                 else
7610                         printf("%15s", mnt);
7611
7612                 if (bover)
7613                         diff2str(dqb->dqb_btime, timebuf, now);
7614                 else if (show_default)
7615                         snprintf(timebuf, sizeof(timebuf), "%llu",
7616                                  (unsigned long long)dqb->dqb_btime);
7617
7618                 kbytes2str(lustre_stoqb(dqb->dqb_curspace),
7619                            strbuf, sizeof(strbuf), h);
7620                 if (rc == -EREMOTEIO)
7621                         sprintf(numbuf[0], "%s*", strbuf);
7622                 else
7623                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
7624                                 "%s" : "[%s]", strbuf);
7625
7626                 kbytes2str(dqb->dqb_bsoftlimit, strbuf, sizeof(strbuf), h);
7627                 if (type == QC_GENERAL)
7628                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS) ?
7629                                 "%s" : "[%s]", strbuf);
7630                 else
7631                         sprintf(numbuf[1], "%s", "-");
7632
7633                 kbytes2str(dqb->dqb_bhardlimit, strbuf, sizeof(strbuf), h);
7634                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS) ?
7635                         "%s" : "[%s]", strbuf);
7636
7637                 if (show_default)
7638                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
7639                 else
7640                         printf(" %7s%c %6s %7s %7s",
7641                                numbuf[0], bover ? '*' : ' ', numbuf[1],
7642                                numbuf[2], bover > 1 ? timebuf : "-");
7643
7644                 if (iover)
7645                         diff2str(dqb->dqb_itime, timebuf, now);
7646                 else if (show_default)
7647                         snprintf(timebuf, sizeof(timebuf), "%llu",
7648                                  (unsigned long long)dqb->dqb_itime);
7649
7650                 snprintf(numbuf[0], sizeof(numbuf),
7651                          (dqb->dqb_valid & QIF_INODES) ? "%ju" : "[%ju]",
7652                          (uintmax_t)dqb->dqb_curinodes);
7653
7654                 if (type == QC_GENERAL)
7655                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS) ?
7656                                 "%ju" : "[%ju]",
7657                                 (uintmax_t)dqb->dqb_isoftlimit);
7658                 else
7659                         sprintf(numbuf[1], "%s", "-");
7660
7661                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
7662                         "%ju" : "[%ju]", (uintmax_t)dqb->dqb_ihardlimit);
7663
7664                 if (show_default)
7665                         printf(" %6s %7s %7s", numbuf[1], numbuf[2], timebuf);
7666                 else if (type != QC_OSTIDX)
7667                         printf(" %7s%c %6s %7s %7s",
7668                                numbuf[0], iover ? '*' : ' ', numbuf[1],
7669                                numbuf[2], iover > 1 ? timebuf : "-");
7670                 else
7671                         printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
7672                 printf("\n");
7673         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO || LUSTRE_Q_GETINFOPOOL ||
7674                    qctl->qc_cmd == Q_GETOINFO) {
7675                 char bgtimebuf[40];
7676                 char igtimebuf[40];
7677
7678                 if (qctl->qc_dqinfo.dqi_bgrace == NOTIFY_GRACE_TIME)
7679                         strncpy(bgtimebuf, NOTIFY_GRACE, 40);
7680                 else
7681                         sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
7682                 if (qctl->qc_dqinfo.dqi_igrace == NOTIFY_GRACE_TIME)
7683                         strncpy(igtimebuf, NOTIFY_GRACE, 40);
7684                 else
7685                         sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
7686
7687                 printf("Block grace time: %s; Inode grace time: %s\n",
7688                        bgtimebuf, igtimebuf);
7689         }
7690 }
7691
7692 static int tgt_name2index(const char *tgtname, unsigned int *idx)
7693 {
7694         char *dash, *endp;
7695
7696         /* format is "lustre-OST0001" */
7697         dash = memchr(tgtname, '-', LUSTRE_MAXFSNAME + 1);
7698         if (!dash) {
7699                 fprintf(stderr, "wrong tgtname format '%s'\n", tgtname);
7700                 return -EINVAL;
7701         }
7702         dash += 4;
7703
7704         *idx = strtoul(dash, &endp, 16);
7705         if (*idx > 0xffff) {
7706                 fprintf(stderr, "wrong index %s\n", tgtname);
7707                 return -ERANGE;
7708         }
7709
7710         return 0;
7711 }
7712
7713 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt,
7714                            bool h, __u64 *total)
7715 {
7716         int rc = 0, rc1 = 0, count = 0, i = 0;
7717         char **list = NULL, *buffer = NULL;
7718         __u32 valid = qctl->qc_valid;
7719
7720         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL && is_mdt)
7721                 return 0;
7722
7723         /* Is it correct for the case OST0000, OST0002, OST0003 -
7724          * we will ask OST0001 that is absent and won't ask OST0003? */
7725         rc = llapi_get_obd_count(mnt, &count, is_mdt);
7726         if (rc) {
7727                 fprintf(stderr, "can not get %s count: %s\n",
7728                         is_mdt ? "mdt" : "ost", strerror(-rc));
7729                 return rc;
7730         }
7731
7732         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
7733                 char fname[PATH_MAX];
7734                 char fsname[LUSTRE_MAXFSNAME + 1];
7735                 int bufsize = sizeof(struct obd_uuid) * count;
7736
7737                 rc = llapi_search_fsname(mnt, fsname);
7738                 if (rc) {
7739                         fprintf(stderr, "cannot get fsname for mountpoint %s\n",
7740                                 mnt);
7741                         goto out;
7742                 }
7743                 buffer = malloc(bufsize + sizeof(*list) * count);
7744                 if (!buffer)
7745                         return -ENOMEM;
7746                 list = (char **)(buffer + bufsize);
7747                 snprintf(fname, PATH_MAX, "%s.%s", fsname, qctl->qc_poolname);
7748                 count = llapi_get_poolmembers(fname, list, count,
7749                                               buffer, bufsize);
7750                 if (count <= 0)
7751                         goto out;
7752         }
7753
7754         for (i = 0; i < count; i++) {
7755                 if (qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
7756                         unsigned int index;
7757
7758                         if (tgt_name2index(list[i], &index))
7759                                 continue;
7760                         qctl->qc_idx = index;
7761                 } else {
7762                         qctl->qc_idx = i;
7763                 }
7764
7765                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
7766                 rc = llapi_quotactl(mnt, qctl);
7767                 if (rc) {
7768                         /* It is remote client case. */
7769                         if (rc == -EOPNOTSUPP) {
7770                                 rc = 0;
7771                                 goto out;
7772                         }
7773
7774                         if (!rc1)
7775                                 rc1 = rc;
7776                         fprintf(stderr, "quotactl %s%d failed.\n",
7777                                 is_mdt ? "mdt" : "ost", qctl->qc_idx);
7778                         continue;
7779                 }
7780
7781                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl,
7782                             qctl->qc_valid, 0, h, false);
7783                 *total += is_mdt ? qctl->qc_dqblk.dqb_ihardlimit :
7784                                    qctl->qc_dqblk.dqb_bhardlimit;
7785         }
7786 out:
7787         if (buffer)
7788                 free(buffer);
7789         qctl->qc_valid = valid;
7790         return rc ? : rc1;
7791 }
7792
7793 static int get_print_quota(char *mnt, char *name, struct if_quotactl *qctl,
7794                            int verbose, int quiet, bool human_readable,
7795                            bool show_default)
7796 {
7797         int rc1 = 0, rc2 = 0, rc3 = 0;
7798         char *obd_type = (char *)qctl->obd_type;
7799         char *obd_uuid = (char *)qctl->obd_uuid.uuid;
7800         __u64 total_ialloc = 0, total_balloc = 0;
7801         bool use_default_for_blk = false;
7802         bool use_default_for_file = false;
7803         int inacc;
7804
7805         rc1 = llapi_quotactl(mnt, qctl);
7806         if (rc1 < 0) {
7807                 switch (rc1) {
7808                 case -ESRCH:
7809                         fprintf(stderr, "%s quotas are not enabled.\n",
7810                                 qtype_name(qctl->qc_type));
7811                         goto out;
7812                 case -EPERM:
7813                         fprintf(stderr, "Permission denied.\n");
7814                 case -ENODEV:
7815                 case -ENOENT:
7816                         /* We already got error message. */
7817                         goto out;
7818                 default:
7819                         fprintf(stderr, "Unexpected quotactl error: %s\n",
7820                                 strerror(-rc1));
7821                 }
7822         }
7823
7824         if (!show_default && qctl->qc_id == 0) {
7825                 qctl->qc_dqblk.dqb_bhardlimit = 0;
7826                 qctl->qc_dqblk.dqb_bsoftlimit = 0;
7827                 qctl->qc_dqblk.dqb_ihardlimit = 0;
7828                 qctl->qc_dqblk.dqb_isoftlimit = 0;
7829                 qctl->qc_dqblk.dqb_btime = 0;
7830                 qctl->qc_dqblk.dqb_itime = 0;
7831                 qctl->qc_dqblk.dqb_valid |= QIF_LIMITS | QIF_TIMES;
7832         }
7833
7834         if (qctl->qc_dqblk.dqb_valid & QIF_BTIME &&
7835             LQUOTA_FLAG(qctl->qc_dqblk.dqb_btime) & LQUOTA_FLAG_DEFAULT) {
7836                 use_default_for_blk = true;
7837                 qctl->qc_dqblk.dqb_btime &= LQUOTA_GRACE_MASK;
7838         }
7839
7840         if (qctl->qc_dqblk.dqb_valid & QIF_ITIME &&
7841             LQUOTA_FLAG(qctl->qc_dqblk.dqb_itime) & LQUOTA_FLAG_DEFAULT) {
7842                 use_default_for_file = true;
7843                 qctl->qc_dqblk.dqb_itime &= LQUOTA_GRACE_MASK;
7844         }
7845
7846         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
7847              qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL ||
7848              qctl->qc_cmd == LUSTRE_Q_GETDEFAULT) && !quiet)
7849                 print_quota_title(name, qctl, human_readable, show_default);
7850
7851         if (rc1 && *obd_type)
7852                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
7853
7854         if (qctl->qc_valid != QC_GENERAL)
7855                 mnt = "";
7856
7857         inacc = (qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
7858                  qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) &&
7859                 ((qctl->qc_dqblk.dqb_valid & (QIF_LIMITS|QIF_USAGE)) !=
7860                  (QIF_LIMITS|QIF_USAGE));
7861
7862         print_quota(mnt, qctl, QC_GENERAL, rc1, human_readable, show_default);
7863
7864         if (!show_default && verbose &&
7865             qctl->qc_valid == QC_GENERAL && qctl->qc_cmd != LUSTRE_Q_GETINFO &&
7866             qctl->qc_cmd != LUSTRE_Q_GETINFOPOOL) {
7867                 char strbuf[STRBUF_LEN];
7868
7869                 rc2 = print_obd_quota(mnt, qctl, 1, human_readable,
7870                                       &total_ialloc);
7871                 rc3 = print_obd_quota(mnt, qctl, 0, human_readable,
7872                                       &total_balloc);
7873                 kbytes2str(total_balloc, strbuf, sizeof(strbuf),
7874                            human_readable);
7875                 printf("Total allocated inode limit: %ju, total allocated block limit: %s\n",
7876                        (uintmax_t)total_ialloc, strbuf);
7877         }
7878
7879         if (use_default_for_blk)
7880                 printf("%cid %u is using default block quota setting\n",
7881                        *qtype_name(qctl->qc_type), qctl->qc_id);
7882
7883         if (use_default_for_file)
7884                 printf("%cid %u is using default file quota setting\n",
7885                        *qtype_name(qctl->qc_type), qctl->qc_id);
7886
7887         if (rc1 || rc2 || rc3 || inacc)
7888                 printf("Some errors happened when getting quota info. Some devices may be not working or deactivated. The data in \"[]\" is inaccurate.\n");
7889 out:
7890         if (rc1)
7891                 return rc1;
7892         if (rc2)
7893                 return rc2;
7894         if (rc3)
7895                 return rc3;
7896         if (inacc)
7897                 return -EIO;
7898
7899         return 0;
7900 }
7901
7902 static int lfs_project(int argc, char **argv)
7903 {
7904         int ret = 0, err = 0, c, i;
7905         struct project_handle_control phc = { 0 };
7906         enum lfs_project_ops_t op;
7907
7908         phc.newline = true;
7909         phc.assign_projid = false;
7910         /* default action */
7911         op = LFS_PROJECT_LIST;
7912
7913         while ((c = getopt(argc, argv, "p:cCsdkr0")) != -1) {
7914                 switch (c) {
7915                 case 'c':
7916                         if (op != LFS_PROJECT_LIST) {
7917                                 fprintf(stderr,
7918                                         "%s: cannot specify '-c' '-C' '-s' together\n",
7919                                         progname);
7920                                 return CMD_HELP;
7921                         }
7922
7923                         op = LFS_PROJECT_CHECK;
7924                         break;
7925                 case 'C':
7926                         if (op != LFS_PROJECT_LIST) {
7927                                 fprintf(stderr,
7928                                         "%s: cannot specify '-c' '-C' '-s' together\n",
7929                                         progname);
7930                                 return CMD_HELP;
7931                         }
7932
7933                         op = LFS_PROJECT_CLEAR;
7934                         break;
7935                 case 's':
7936                         if (op != LFS_PROJECT_LIST) {
7937                                 fprintf(stderr,
7938                                         "%s: cannot specify '-c' '-C' '-s' together\n",
7939                                         progname);
7940                                 return CMD_HELP;
7941                         }
7942
7943                         phc.set_inherit = true;
7944                         op = LFS_PROJECT_SET;
7945                         break;
7946                 case 'd':
7947                         phc.dironly = true;
7948                         break;
7949                 case 'k':
7950                         phc.keep_projid = true;
7951                         break;
7952                 case 'r':
7953                         phc.recursive = true;
7954                         break;
7955                 case 'p':
7956                         if (str2quotaid(&phc.projid, optarg)) {
7957                                 fprintf(stderr,
7958                                         "Invalid project ID: %s\n",
7959                                         optarg);
7960                                 return CMD_HELP;
7961                         }
7962
7963                         phc.assign_projid = true;
7964
7965                         break;
7966                 case '0':
7967                         phc.newline = false;
7968                         break;
7969                 default:
7970                         fprintf(stderr, "%s: invalid option '%c'\n",
7971                                 progname, optopt);
7972                         return CMD_HELP;
7973                 }
7974         }
7975
7976         if (phc.assign_projid && op == LFS_PROJECT_LIST) {
7977                 op = LFS_PROJECT_SET;
7978                 phc.set_projid = true;
7979         } else if (phc.assign_projid && op == LFS_PROJECT_SET) {
7980                 phc.set_projid = true;
7981         }
7982
7983         switch (op) {
7984         case LFS_PROJECT_CHECK:
7985                 if (phc.keep_projid) {
7986                         fprintf(stderr,
7987                                 "%s: '-k' is useless together with '-c'\n",
7988                                 progname);
7989                         return CMD_HELP;
7990                 }
7991                 break;
7992         case LFS_PROJECT_CLEAR:
7993                 if (!phc.newline) {
7994                         fprintf(stderr,
7995                                 "%s: '-0' is useless together with '-C'\n",
7996                                 progname);
7997                         return CMD_HELP;
7998                 }
7999                 if (phc.assign_projid) {
8000                         fprintf(stderr,
8001                                 "%s: '-p' is useless together with '-C'\n",
8002                                 progname);
8003                         return CMD_HELP;
8004                 }
8005                 break;
8006         case LFS_PROJECT_SET:
8007                 if (!phc.newline) {
8008                         fprintf(stderr,
8009                                 "%s: '-0' is useless together with '-s'\n",
8010                                 progname);
8011                         return CMD_HELP;
8012                 }
8013                 if (phc.keep_projid) {
8014                         fprintf(stderr,
8015                                 "%s: '-k' is useless together with '-s'\n",
8016                                 progname);
8017                         return CMD_HELP;
8018                 }
8019                 break;
8020         default:
8021                 if (!phc.newline) {
8022                         fprintf(stderr,
8023                                 "%s: '-0' is useless for list operations\n",
8024                                 progname);
8025                         return CMD_HELP;
8026                 }
8027                 break;
8028         }
8029
8030         argv += optind;
8031         argc -= optind;
8032         if (argc == 0) {
8033                 fprintf(stderr, "%s: missing file or directory target(s)\n",
8034                         progname);
8035                 return CMD_HELP;
8036         }
8037
8038         for (i = 0; i < argc; i++) {
8039                 switch (op) {
8040                 case LFS_PROJECT_CHECK:
8041                         err = lfs_project_check(argv[i], &phc);
8042                         break;
8043                 case LFS_PROJECT_LIST:
8044                         err = lfs_project_list(argv[i], &phc);
8045                         break;
8046                 case LFS_PROJECT_CLEAR:
8047                         err = lfs_project_clear(argv[i], &phc);
8048                         break;
8049                 case LFS_PROJECT_SET:
8050                         err = lfs_project_set(argv[i], &phc);
8051                         break;
8052                 default:
8053                         break;
8054                 }
8055                 if (err && !ret)
8056                         ret = err;
8057         }
8058
8059         return ret;
8060 }
8061
8062 static int lfs_quota(int argc, char **argv)
8063 {
8064         int c;
8065         char *mnt, *name = NULL;
8066         struct if_quotactl *qctl;
8067         char *obd_uuid;
8068         int rc = 0, rc1 = 0, verbose = 0, quiet = 0;
8069         __u32 valid = QC_GENERAL, idx = 0;
8070         bool human_readable = false;
8071         bool show_default = false;
8072         int qtype;
8073         struct option long_opts[] = {
8074         { .val = LFS_POOL_OPT, .name = "pool", .has_arg = required_argument },
8075         { .name = NULL } };
8076
8077         qctl = calloc(1, sizeof(*qctl) + LOV_MAXPOOLNAME + 1);
8078         if (!qctl)
8079                 return -ENOMEM;
8080
8081         qctl->qc_cmd = LUSTRE_Q_GETQUOTA;
8082         qctl->qc_type = ALLQUOTA;
8083         obd_uuid = (char *)qctl->obd_uuid.uuid;
8084
8085         while ((c = getopt_long(argc, argv, "gGi:I:o:pPqtuUvh",
8086                 long_opts, NULL)) != -1) {
8087                 switch (c) {
8088                 case 'U':
8089                         show_default = true;
8090                 case 'u':
8091                         qtype = USRQUOTA;
8092                         goto quota_type;
8093                 case 'G':
8094                         show_default = true;
8095                 case 'g':
8096                         qtype = GRPQUOTA;
8097                         goto quota_type;
8098                 case 'P':
8099                         show_default = true;
8100                 case 'p':
8101                         qtype = PRJQUOTA;
8102 quota_type:
8103                         if (qctl->qc_type != ALLQUOTA) {
8104                                 fprintf(stderr,
8105                                         "%s quota: only one of -u, -g, or -p may be specified\n",
8106                                         progname);
8107                                 rc = CMD_HELP;
8108                                 goto out;
8109                         }
8110                         qctl->qc_type = qtype;
8111                         break;
8112                 case 't':
8113                         qctl->qc_cmd = LUSTRE_Q_GETINFO;
8114                         break;
8115                 case 'o':
8116                         valid = qctl->qc_valid = QC_UUID;
8117                         snprintf(obd_uuid, sizeof(*obd_uuid), "%s", optarg);
8118                         break;
8119                 case 'i':
8120                         valid = qctl->qc_valid = QC_MDTIDX;
8121                         idx = qctl->qc_idx = atoi(optarg);
8122                         if (idx == 0 && *optarg != '0') {
8123                                 fprintf(stderr,
8124                                         "%s quota: invalid MDT index '%s'\n",
8125                                         progname, optarg);
8126                                 rc = CMD_HELP;
8127                                 goto out;
8128                         }
8129                         break;
8130                 case 'I':
8131                         valid = qctl->qc_valid = QC_OSTIDX;
8132                         idx = qctl->qc_idx = atoi(optarg);
8133                         if (idx == 0 && *optarg != '0') {
8134                                 fprintf(stderr,
8135                                         "%s quota: invalid OST index '%s'\n",
8136                                         progname, optarg);
8137                                 rc = CMD_HELP;
8138                                 goto out;
8139                         }
8140                         break;
8141                 case 'v':
8142                         verbose = 1;
8143                         break;
8144                 case 'q':
8145                         quiet = 1;
8146                         break;
8147                 case 'h':
8148                         human_readable = true;
8149                         break;
8150                 case LFS_POOL_OPT:
8151                         if (lfs_verify_poolarg(optarg)) {
8152                                 rc = -1;
8153                                 goto out;
8154                         }
8155                         strncpy(qctl->qc_poolname, optarg, LOV_MAXPOOLNAME);
8156                         qctl->qc_cmd = qctl->qc_cmd == LUSTRE_Q_GETINFO ?
8157                                                 LUSTRE_Q_GETINFOPOOL :
8158                                                 LUSTRE_Q_GETQUOTAPOOL;
8159                         break;
8160                 default:
8161                         fprintf(stderr, "%s quota: unrecognized option '%s'\n",
8162                                 progname, argv[optind - 1]);
8163                         rc = CMD_HELP;
8164                         goto out;
8165                 }
8166         }
8167
8168         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
8169         if ((qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8170              qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) &&
8171              qctl->qc_type == ALLQUOTA &&
8172              optind == argc - 1 && !show_default) {
8173                 qctl->qc_idx = idx;
8174
8175                 for (qtype = USRQUOTA; qtype <= GRPQUOTA; qtype++) {
8176                         qctl->qc_type = qtype;
8177                         qctl->qc_valid = valid;
8178                         if (qtype == USRQUOTA) {
8179                                 qctl->qc_id = geteuid();
8180                                 rc = uid2name(&name, qctl->qc_id);
8181                         } else {
8182                                 qctl->qc_id = getegid();
8183                                 rc = gid2name(&name, qctl->qc_id);
8184                                 memset(&qctl->qc_dqblk, 0,
8185                                        sizeof(qctl->qc_dqblk));
8186                         }
8187                         if (rc)
8188                                 name = "<unknown>";
8189                         mnt = argv[optind];
8190                         rc1 = get_print_quota(mnt, name, qctl, verbose, quiet,
8191                                               human_readable, show_default);
8192                         if (rc1 && !rc)
8193                                 rc = rc1;
8194                 }
8195                 goto out;
8196         /* lfs quota -u username /path/to/lustre/mount */
8197         } else if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA ||
8198                    qctl->qc_cmd == LUSTRE_Q_GETQUOTAPOOL) {
8199                 /* options should be followed by u/g-name and mntpoint */
8200                 if ((!show_default && optind + 2 != argc) ||
8201                     (show_default && optind + 1 != argc) ||
8202                     qctl->qc_type == ALLQUOTA) {
8203                         fprintf(stderr,
8204                                 "%s quota: name and mount point must be specified\n",
8205                                 progname);
8206                         rc = CMD_HELP;
8207                         goto out;
8208                 }
8209
8210                 if (!show_default) {
8211                         name = argv[optind++];
8212                         switch (qctl->qc_type) {
8213                         case USRQUOTA:
8214                                 rc = name2uid(&qctl->qc_id, name);
8215                                 break;
8216                         case GRPQUOTA:
8217                                 rc = name2gid(&qctl->qc_id, name);
8218                                 break;
8219                         case PRJQUOTA:
8220                                 rc = name2projid(&qctl->qc_id, name);
8221                                 break;
8222                         default:
8223                                 rc = -ENOTSUP;
8224                                 break;
8225                         }
8226                 } else {
8227                         qctl->qc_valid = QC_GENERAL;
8228                         qctl->qc_cmd = LUSTRE_Q_GETDEFAULT;
8229                         qctl->qc_id = 0;
8230                 }
8231
8232                 if (rc) {
8233                         if (str2quotaid(&qctl->qc_id, name)) {
8234                                 fprintf(stderr, "%s quota: invalid id '%s'\n",
8235                                         progname, name);
8236                                 rc = CMD_HELP;
8237                                 goto out;
8238                         }
8239                 }
8240         } else if (optind + 1 != argc || qctl->qc_type == ALLQUOTA) {
8241                 fprintf(stderr, "%s quota: missing quota info argument(s)\n",
8242                         progname);
8243                 rc = CMD_HELP;
8244                 goto out;
8245         }
8246
8247         mnt = argv[optind];
8248         rc = get_print_quota(mnt, name, qctl, verbose, quiet,
8249                              human_readable, show_default);
8250 out:
8251         free(qctl);
8252         return rc;
8253 }
8254 #endif /* HAVE_SYS_QUOTA_H! */
8255
8256 static int flushctx_ioctl(char *mp)
8257 {
8258         int fd, rc;
8259
8260         fd = open(mp, O_RDONLY);
8261         if (fd == -1) {
8262                 fprintf(stderr, "flushctx: error open %s: %s\n",
8263                         mp, strerror(errno));
8264                 return -1;
8265         }
8266
8267         rc = ioctl(fd, LL_IOC_FLUSHCTX);
8268         if (rc == -1)
8269                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
8270                         mp, strerror(errno));
8271
8272         close(fd);
8273         return rc;
8274 }
8275
8276 static int lfs_flushctx(int argc, char **argv)
8277 {
8278         int     kdestroy = 0, reap = 0, c;
8279         char    mntdir[PATH_MAX] = {'\0'};
8280         int     index = 0;
8281         int     rc = 0;
8282
8283         while ((c = getopt(argc, argv, "kr")) != -1) {
8284                 switch (c) {
8285                 case 'k':
8286                         kdestroy = 1;
8287                         break;
8288                 case 'r':
8289                         reap = 1;
8290                         break;
8291                 default:
8292                         fprintf(stderr,
8293                                 "error: %s: option '-%c' unrecognized\n",
8294                                 argv[0], c);
8295                         return CMD_HELP;
8296                 }
8297         }
8298
8299         if (kdestroy) {
8300                 rc = system("kdestroy > /dev/null");
8301                 if (rc) {
8302                         rc = WEXITSTATUS(rc);
8303                         fprintf(stderr,
8304                                 "error destroying tickets: %d, continuing\n",
8305                                 rc);
8306                 }
8307         }
8308
8309         if (optind >= argc) {
8310                 /* flush for all mounted lustre fs. */
8311                 while (!llapi_search_mounts(NULL, index++, mntdir, NULL)) {
8312                         /* Check if we have a mount point */
8313                         if (mntdir[0] == '\0')
8314                                 continue;
8315
8316                         if (flushctx_ioctl(mntdir))
8317                                 rc = -1;
8318
8319                         mntdir[0] = '\0'; /* avoid matching in next loop */
8320                 }
8321         } else {
8322                 /* flush fs as specified */
8323                 while (optind < argc) {
8324                         if (flushctx_ioctl(argv[optind++]))
8325                                 rc = -1;
8326                 }
8327         }
8328
8329         if (reap) {
8330                 rc = system("keyctl reap > /dev/null");
8331                 if (rc != 0) {
8332                         rc = WEXITSTATUS(rc);
8333                         fprintf(stderr, "error reaping keyring: %d\n", rc);
8334                 }
8335         }
8336
8337         return rc;
8338 }
8339
8340 static int lfs_changelog(int argc, char **argv)
8341 {
8342         void *changelog_priv;
8343         struct changelog_rec *rec;
8344         long long startrec = 0, endrec = 0;
8345         char *mdd;
8346         struct option long_opts[] = {
8347                 { .val = 'f', .name = "follow", .has_arg = no_argument },
8348                 { .name = NULL } };
8349         char short_opts[] = "f";
8350         int rc, follow = 0;
8351
8352         while ((rc = getopt_long(argc, argv, short_opts,
8353                 long_opts, NULL)) != -1) {
8354                 switch (rc) {
8355                 case 'f':
8356                         follow++;
8357                         break;
8358                 default:
8359                         fprintf(stderr,
8360                                 "%s changelog: unrecognized option '%s'\n",
8361                                 progname, argv[optind - 1]);
8362                         return CMD_HELP;
8363                 }
8364         }
8365         if (optind >= argc) {
8366                 fprintf(stderr, "%s changelog: mdtname must be specified\n",
8367                         progname);
8368                 return CMD_HELP;
8369         }
8370
8371         mdd = argv[optind++];
8372         if (argc > optind) {
8373                 errno = 0;
8374                 startrec = strtoll(argv[optind++], NULL, 10);
8375                 if (errno != 0 || startrec < 0) {
8376                         fprintf(stderr,
8377                                 "%s changelog: bad startrec\n",
8378                                 progname);
8379                         return CMD_HELP;
8380                 }
8381         }
8382
8383         if (argc > optind) {
8384                 errno = 0;
8385                 endrec = strtoll(argv[optind++], NULL, 10);
8386                 if (errno != 0 || endrec < 0) {
8387                         fprintf(stderr,
8388                                 "%s changelog: bad endrec\n",
8389                                 progname);
8390                         return CMD_HELP;
8391                 }
8392         }
8393
8394         rc = llapi_changelog_start(&changelog_priv,
8395                                    CHANGELOG_FLAG_BLOCK |
8396                                    CHANGELOG_FLAG_JOBID |
8397                                    CHANGELOG_FLAG_EXTRA_FLAGS |
8398                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
8399                                    mdd, startrec);
8400         if (rc < 0) {
8401                 fprintf(stderr, "%s changelog: cannot start changelog: %s\n",
8402                         progname, strerror(errno = -rc));
8403                 return rc;
8404         }
8405
8406         rc = llapi_changelog_set_xflags(changelog_priv,
8407                                         CHANGELOG_EXTRA_FLAG_UIDGID |
8408                                         CHANGELOG_EXTRA_FLAG_NID |
8409                                         CHANGELOG_EXTRA_FLAG_OMODE |
8410                                         CHANGELOG_EXTRA_FLAG_XATTR);
8411         if (rc < 0) {
8412                 fprintf(stderr,
8413                         "%s changelog: cannot set xflags for changelog: %s\n",
8414                         progname, strerror(errno = -rc));
8415                 return rc;
8416         }
8417
8418         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
8419                 time_t secs;
8420                 struct tm ts;
8421
8422                 if (endrec && rec->cr_index > endrec) {
8423                         llapi_changelog_free(&rec);
8424                         break;
8425                 }
8426                 if (rec->cr_index < startrec) {
8427                         llapi_changelog_free(&rec);
8428                         continue;
8429                 }
8430
8431                 secs = rec->cr_time >> 30;
8432                 gmtime_r(&secs, &ts);
8433                 printf("%ju %02d%-5s %02d:%02d:%02d.%09d %04d.%02d.%02d "
8434                        "0x%x t="DFID, (uintmax_t)rec->cr_index, rec->cr_type,
8435                        changelog_type2str(rec->cr_type),
8436                        ts.tm_hour, ts.tm_min, ts.tm_sec,
8437                        (int)(rec->cr_time & ((1 << 30) - 1)),
8438                        ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday,
8439                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
8440
8441                 if (rec->cr_flags & CLF_JOBID) {
8442                         struct changelog_ext_jobid *jid =
8443                                 changelog_rec_jobid(rec);
8444
8445                         if (jid->cr_jobid[0] != '\0')
8446                                 printf(" j=%s", jid->cr_jobid);
8447                 }
8448
8449                 if (rec->cr_flags & CLF_EXTRA_FLAGS) {
8450                         struct changelog_ext_extra_flags *ef =
8451                                 changelog_rec_extra_flags(rec);
8452
8453                         printf(" ef=0x%llx",
8454                                (unsigned long long)ef->cr_extra_flags);
8455
8456                         if (ef->cr_extra_flags & CLFE_UIDGID) {
8457                                 struct changelog_ext_uidgid *uidgid =
8458                                         changelog_rec_uidgid(rec);
8459
8460                                 printf(" u=%llu:%llu",
8461                                        (unsigned long long)uidgid->cr_uid,
8462                                        (unsigned long long)uidgid->cr_gid);
8463                         }
8464                         if (ef->cr_extra_flags & CLFE_NID) {
8465                                 struct changelog_ext_nid *nid =
8466                                         changelog_rec_nid(rec);
8467
8468                                 printf(" nid=%s",
8469                                        libcfs_nid2str(nid->cr_nid));
8470                         }
8471
8472                         if (ef->cr_extra_flags & CLFE_OPEN) {
8473                                 struct changelog_ext_openmode *omd =
8474                                         changelog_rec_openmode(rec);
8475                                 char mode[] = "---";
8476
8477                                 /* exec mode must be exclusive */
8478                                 if (omd->cr_openflags & MDS_FMODE_EXEC) {
8479                                         mode[2] = 'x';
8480                                 } else {
8481                                         if (omd->cr_openflags & MDS_FMODE_READ)
8482                                                 mode[0] = 'r';
8483                                         if (omd->cr_openflags &
8484                                             (MDS_FMODE_WRITE |
8485                                              MDS_OPEN_TRUNC |
8486                                              MDS_OPEN_APPEND))
8487                                                 mode[1] = 'w';
8488                                 }
8489
8490                                 if (strcmp(mode, "---") != 0)
8491                                         printf(" m=%s", mode);
8492                         }
8493
8494                         if (ef->cr_extra_flags & CLFE_XATTR) {
8495                                 struct changelog_ext_xattr *xattr =
8496                                         changelog_rec_xattr(rec);
8497
8498                                 if (xattr->cr_xattr[0] != '\0')
8499                                         printf(" x=%s", xattr->cr_xattr);
8500                         }
8501                 }
8502
8503                 if (!fid_is_zero(&rec->cr_pfid))
8504                         printf(" p="DFID, PFID(&rec->cr_pfid));
8505                 if (rec->cr_namelen)
8506                         printf(" %.*s", rec->cr_namelen,
8507                                changelog_rec_name(rec));
8508
8509                 if (rec->cr_flags & CLF_RENAME) {
8510                         struct changelog_ext_rename *rnm =
8511                                 changelog_rec_rename(rec);
8512
8513                         if (!fid_is_zero(&rnm->cr_sfid))
8514                                 printf(" s="DFID" sp="DFID" %.*s",
8515                                        PFID(&rnm->cr_sfid),
8516                                        PFID(&rnm->cr_spfid),
8517                                        (int)changelog_rec_snamelen(rec),
8518                                        changelog_rec_sname(rec));
8519                 }
8520                 printf("\n");
8521
8522                 llapi_changelog_free(&rec);
8523         }
8524
8525         llapi_changelog_fini(&changelog_priv);
8526
8527         if (rc < 0)
8528                 fprintf(stderr, "%s changelog: cannot access changelog: %s\n",
8529                         progname, strerror(errno = -rc));
8530
8531         return (rc == 1 ? 0 : rc);
8532 }
8533
8534 static int lfs_changelog_clear(int argc, char **argv)
8535 {
8536         long long endrec;
8537         int rc;
8538
8539         if (argc != 4)
8540                 return CMD_HELP;
8541
8542         errno = 0;
8543         endrec = strtoll(argv[3], NULL, 10);
8544         if (errno != 0 || endrec < 0) {
8545                 fprintf(stderr,
8546                         "%s: bad endrec '%s'\n",
8547                         argv[0], argv[3]);
8548                 return CMD_HELP;
8549         }
8550
8551         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
8552
8553         if (rc == -EINVAL)
8554                 fprintf(stderr, "%s: record out of range: %llu\n",
8555                         argv[0], endrec);
8556         else if (rc == -ENOENT)
8557                 fprintf(stderr, "%s: no changelog user: %s\n",
8558                         argv[0], argv[2]);
8559         else if (rc)
8560                 fprintf(stderr, "%s error: %s\n", argv[0],
8561                         strerror(-rc));
8562
8563         if (rc)
8564                 errno = -rc;
8565
8566         return rc;
8567 }
8568
8569 static void rstripc(char *str, int c)
8570 {
8571         char *end = str + strlen(str);
8572
8573         for (; str < end && end[-1] == c; --end)
8574                 end[-1] = '\0';
8575 }
8576
8577 static int lfs_fid2path(int argc, char **argv)
8578 {
8579         struct option long_opts[] = {
8580                 { .val = 'c',   .name = "cur",  .has_arg = no_argument },
8581                 { .val = 'c',   .name = "current",      .has_arg = no_argument },
8582                 { .val = 'c',   .name = "print-link",   .has_arg = no_argument },
8583                 { .val = 'f',   .name = "print-fid",    .has_arg = no_argument },
8584                 { .val = 'l',   .name = "link", .has_arg = required_argument },
8585                 { .name = NULL } };
8586         char short_opts[] = "cfl:pr:";
8587         bool print_link = false;
8588         bool print_fid = false;
8589         bool print_mnt_dir;
8590         char mnt_dir[PATH_MAX] = "";
8591         int mnt_fd = -1;
8592         char *path_or_fsname;
8593         long long recno = -1;
8594         int linkno = -1;
8595         char *endptr = NULL;
8596         int rc = 0;
8597         int c;
8598         int i;
8599
8600         while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
8601                 switch (c) {
8602                 case 'c':
8603                         print_link = true;
8604                         break;
8605                 case 'f':
8606                         print_fid = true;
8607                         break;
8608                 case 'l':
8609                         errno = 0;
8610                         linkno = strtol(optarg, &endptr, 10);
8611                         if (errno != 0 || *endptr != '\0' || linkno < 0) {
8612                                 fprintf(stderr,
8613                                         "%s fid2path: invalid linkno '%s'\n",
8614                                         progname, optarg);
8615                                 return CMD_HELP;
8616                         }
8617                         break;
8618                 case 'r':
8619                         /* recno is something to do with changelogs
8620                          * that was never implemented. We just pass it
8621                          * through for the MDT to ignore.
8622                          */
8623                         errno = 0;
8624                         recno = strtoll(optarg, &endptr, 10);
8625                         if (errno != 0 || *endptr != '\0' || recno < 0) {
8626                                 fprintf(stderr,
8627                                         "%s fid2path: invalid recno '%s'\n",
8628                                         progname, optarg);
8629                                 return CMD_HELP;
8630                         }
8631                         break;
8632                 default:
8633                         fprintf(stderr,
8634                                 "%s fid2path: unrecognized option '%s'\n",
8635                                 progname, argv[optind - 1]);
8636                         return CMD_HELP;
8637                 }
8638         }
8639
8640         if (argc - optind < 2) {
8641                 fprintf(stderr,
8642                         "Usage: %s fid2path FSNAME|ROOT FID...\n",
8643                         progname);
8644                 return CMD_HELP;
8645         }
8646
8647         path_or_fsname = argv[optind];
8648
8649         if (*path_or_fsname == '/') {
8650                 print_mnt_dir = true;
8651                 rc = llapi_search_mounts(path_or_fsname, 0, mnt_dir, NULL);
8652         } else {
8653                 print_mnt_dir = false;
8654                 rc = llapi_search_rootpath(mnt_dir, path_or_fsname);
8655         }
8656
8657         if (rc < 0) {
8658                 fprintf(stderr,
8659                         "%s fid2path: cannot resolve mount point for '%s': %s\n",
8660                         progname, path_or_fsname, strerror(-rc));
8661                 goto out;
8662         }
8663
8664         mnt_fd = open(mnt_dir, O_RDONLY | O_DIRECTORY);
8665         if (mnt_fd < 0) {
8666                 fprintf(stderr,
8667                         "%s fid2path: cannot open mount point for '%s': %s\n",
8668                         progname, path_or_fsname, strerror(-rc));
8669                 goto out;
8670         }
8671
8672         /* Strip trailing slashes from mnt_dir. */
8673         rstripc(mnt_dir + 1, '/');
8674
8675         for (i = optind + 1; i < argc; i++) {
8676                 const char *fid_str = argv[i];
8677                 struct lu_fid fid;
8678                 int rc2;
8679
8680                 rc2 = llapi_fid_parse(fid_str, &fid, NULL);
8681                 if (rc2 < 0) {
8682                         fprintf(stderr,
8683                                 "%s fid2path: invalid FID '%s'\n",
8684                                 progname, fid_str);
8685                         if (rc == 0)
8686                                 rc = rc2;
8687
8688                         continue;
8689                 }
8690
8691                 int linktmp = (linkno >= 0) ? linkno : 0;
8692                 while (1) {
8693                         int oldtmp = linktmp;
8694                         long long rectmp = recno;
8695                         char path_buf[PATH_MAX];
8696
8697                         rc2 = llapi_fid2path_at(mnt_fd, &fid,
8698                                 path_buf, sizeof(path_buf), &rectmp, &linktmp);
8699                         if (rc2 < 0) {
8700                                 fprintf(stderr,
8701                                         "%s fid2path: cannot find %s %s: %s\n",
8702                                         progname, path_or_fsname, fid_str,
8703                                         strerror(-rc2));
8704                                 if (rc == 0)
8705                                         rc = rc2;
8706                                 break;
8707                         }
8708
8709                         if (print_fid)
8710                                 printf("%s ", fid_str);
8711
8712                         if (print_link)
8713                                 printf("%d ", linktmp);
8714
8715                         /* You may think this looks wrong or weird (and it is!)
8716                          * but we are actually trying to preserve the old quirky
8717                          * behaviors (enforced by our old quirky tests!) that
8718                          * make lfs so much fun to work on:
8719                          *
8720                          *   lustre 0x200000007:0x1:0x0 => "/"
8721                          *   /mnt/lustre 0x200000007:0x1:0x0 => "/mnt/lustre//"
8722                          *
8723                          * Note that llapi_fid2path() returns "" for the root
8724                          * FID. */
8725
8726                         printf("%s%s%s\n",
8727                                print_mnt_dir ? mnt_dir : "",
8728                                (print_mnt_dir || *path_buf == '\0') ? "/" : "",
8729                                path_buf);
8730
8731                         if (linkno >= 0)
8732                                 /* specified linkno */
8733                                 break;
8734
8735                         if (oldtmp == linktmp)
8736                                 /* no more links */
8737                                 break;
8738                 }
8739         }
8740 out:
8741         if (!(mnt_fd < 0))
8742                 close(mnt_fd);
8743
8744         return rc;
8745 }
8746
8747 static int lfs_path2fid(int argc, char **argv)
8748 {
8749         struct option long_opts[] = {
8750                 { .val = 'p', .name = "parents", .has_arg = no_argument },
8751                 { .name = NULL } };
8752         char            **path;
8753         const char        short_opts[] = "p";
8754         const char       *sep = "";
8755         struct lu_fid     fid;
8756         int               rc = 0;
8757         bool              show_parents = false;
8758
8759         while ((rc = getopt_long(argc, argv, short_opts,
8760                                  long_opts, NULL)) != -1) {
8761                 switch (rc) {
8762                 case 'p':
8763                         show_parents = true;
8764                         break;
8765                 default:
8766                         fprintf(stderr,
8767                                 "%s path2fid: unrecognized option '%s'\n",
8768                                 progname, argv[optind - 1]);
8769                         return CMD_HELP;
8770                 }
8771         }
8772
8773         if (optind > argc - 1) {
8774                 fprintf(stderr, "%s path2fid: FILE... must be specified\n",
8775                         progname);
8776                 return CMD_HELP;
8777         } else if (optind < argc - 1) {
8778                 sep = ": ";
8779         }
8780
8781         rc = 0;
8782         for (path = argv + optind; *path != NULL; path++) {
8783                 int err = 0;
8784
8785                 if (!show_parents) {
8786                         err = llapi_path2fid(*path, &fid);
8787                         if (!err)
8788                                 printf("%s%s"DFID"\n",
8789                                        *sep != '\0' ? *path : "", sep,
8790                                        PFID(&fid));
8791                 } else {
8792                         char            name[NAME_MAX + 1];
8793                         unsigned int    linkno = 0;
8794
8795                         while ((err = llapi_path2parent(*path, linkno, &fid,
8796                                                 name, sizeof(name))) == 0) {
8797                                 if (*sep != '\0' && linkno == 0)
8798                                         printf("%s%s", *path, sep);
8799
8800                                 printf("%s"DFID"/%s", linkno != 0 ? "\t" : "",
8801                                        PFID(&fid), name);
8802                                 linkno++;
8803                         }
8804
8805                         /* err == -ENODATA is end-of-loop */
8806                         if (linkno > 0 && err == -ENODATA) {
8807                                 printf("\n");
8808                                 err = 0;
8809                         }
8810                 }
8811
8812                 if (err) {
8813                         fprintf(stderr,
8814                                 "%s path2fid: cannot get %sfid for '%s': %s\n",
8815                                 progname, show_parents ? "parent " : "", *path,
8816                                 strerror(-err));
8817                         if (rc == 0) {
8818                                 rc = err;
8819                                 errno = -err;
8820                         }
8821                 }
8822         }
8823
8824         return rc;
8825 }
8826
8827 #define MAX_ERRNO       4095
8828 #define IS_ERR_VALUE(x) ((unsigned long)(x) >= (unsigned long)-MAX_ERRNO)
8829
8830 static int lfs_rmfid_and_show_errors(const char *device, struct fid_array *fa)
8831 {
8832         int rc, rc2, k;
8833
8834         rc = llapi_rmfid(device, fa);
8835         if (rc < 0) {
8836                 fprintf(stderr, "%s rmfid: cannot remove FIDs: %s\n",
8837                         progname, strerror(-rc));
8838                 return rc;
8839         }
8840
8841         for (k = 0; k < fa->fa_nr; k++) {
8842                 rc2 = (__s32)fa->fa_fids[k].f_ver;
8843                 if (!IS_ERR_VALUE(rc2))
8844                         continue;
8845
8846                 if (rc == 0)
8847                         rc = rc2;
8848
8849                 fa->fa_fids[k].f_ver = 0;
8850                 fprintf(stderr, "%s rmfid: cannot remove "DFID": %s\n",
8851                         progname, PFID(&fa->fa_fids[k]), strerror(-rc2));
8852         }
8853
8854         return rc;
8855 }
8856
8857 static int lfs_rmfid(int argc, char **argv)
8858 {
8859         char *fidstr, *device;
8860         int rc = 0, rc2, nr;
8861         struct fid_array *fa;
8862
8863         if (optind > argc - 1) {
8864                 fprintf(stderr, "%s rmfid: missing dirname\n", progname);
8865                 return CMD_HELP;
8866         }
8867
8868         device = argv[optind++];
8869
8870         nr = argc - optind;
8871         fa = malloc(offsetof(struct fid_array, fa_fids[nr + 1]));
8872         if (!fa)
8873                 return -ENOMEM;
8874
8875         fa->fa_nr = 0;
8876         rc = 0;
8877         while (optind < argc) {
8878                 int found;
8879
8880                 fidstr = argv[optind++];
8881                 while (*fidstr == '[')
8882                         fidstr++;
8883                 found = sscanf(fidstr, SFID, RFID(&fa->fa_fids[fa->fa_nr]));
8884                 if (found != 3) {
8885                         fprintf(stderr, "unrecognized FID: %s\n",
8886                                 argv[optind - 1]);
8887                         exit(1);
8888                 }
8889                 fa->fa_nr++;
8890                 if (fa->fa_nr == OBD_MAX_FIDS_IN_ARRAY) {
8891                         /* start another batch */
8892                         rc2 = lfs_rmfid_and_show_errors(device, fa);
8893                         if (rc2 && !rc)
8894                                 rc = rc2;
8895                         fa->fa_nr = 0;
8896                 }
8897         }
8898         if (fa->fa_nr) {
8899                 rc2 = lfs_rmfid_and_show_errors(device, fa);
8900                 if (rc2 && !rc)
8901                         rc = rc2;
8902         }
8903
8904         return rc;
8905 }
8906
8907 static int lfs_data_version(int argc, char **argv)
8908 {
8909         char *path;
8910         __u64 data_version;
8911         int fd;
8912         int rc;
8913         int c;
8914         int data_version_flags = LL_DV_RD_FLUSH; /* Read by default */
8915
8916         if (argc < 2) {
8917                 fprintf(stderr, "%s data_version: FILE must be specified\n",
8918                         progname);
8919                 return CMD_HELP;
8920         }
8921
8922         while ((c = getopt(argc, argv, "nrw")) != -1) {
8923                 switch (c) {
8924                 case 'n':
8925                         data_version_flags = 0;
8926                         break;
8927                 case 'r':
8928                         data_version_flags |= LL_DV_RD_FLUSH;
8929                         break;
8930                 case 'w':
8931                         data_version_flags |= LL_DV_WR_FLUSH;
8932                         break;
8933                 default:
8934                         fprintf(stderr,
8935                                 "%s data_version: unrecognized option '%s'\n",
8936                                 progname, argv[optind - 1]);
8937                         return CMD_HELP;
8938                 }
8939         }
8940         if (optind == argc) {
8941                 fprintf(stderr, "%s data_version: FILE must be specified\n",
8942                         progname);
8943                 return CMD_HELP;
8944         }
8945
8946         path = argv[optind];
8947         fd = open(path, O_RDONLY);
8948         if (fd < 0) {
8949                 rc = -errno;
8950                 fprintf(stderr, "%s data_version: cannot open file '%s': %s\n",
8951                         progname, path, strerror(-rc));
8952                 return rc;
8953         }
8954
8955         rc = llapi_get_data_version(fd, &data_version, data_version_flags);
8956         if (rc < 0)
8957                 fprintf(stderr,
8958                         "%s data_version: cannot get version for '%s': %s\n",
8959                         progname, path, strerror(-rc));
8960         else
8961                 printf("%ju" "\n", (uintmax_t)data_version);
8962
8963         close(fd);
8964         return rc;
8965 }
8966
8967 static int lfs_hsm_state(int argc, char **argv)
8968 {
8969         int rc;
8970         int i = 1;
8971         char *path;
8972         struct hsm_user_state hus;
8973
8974         if (argc < 2)
8975                 return CMD_HELP;
8976
8977         do {
8978                 path = argv[i];
8979
8980                 rc = llapi_hsm_state_get(path, &hus);
8981                 if (rc) {
8982                         fprintf(stderr, "can't get hsm state for %s: %s\n",
8983                                 path, strerror(errno = -rc));
8984                         return rc;
8985                 }
8986
8987                 /* Display path name and status flags */
8988                 printf("%s: (0x%08x)", path, hus.hus_states);
8989
8990                 if (hus.hus_states & HS_RELEASED)
8991                         printf(" released");
8992                 if (hus.hus_states & HS_EXISTS)
8993                         printf(" exists");
8994                 if (hus.hus_states & HS_DIRTY)
8995                         printf(" dirty");
8996                 if (hus.hus_states & HS_ARCHIVED)
8997                         printf(" archived");
8998                 /* Display user-settable flags */
8999                 if (hus.hus_states & HS_NORELEASE)
9000                         printf(" never_release");
9001                 if (hus.hus_states & HS_NOARCHIVE)
9002                         printf(" never_archive");
9003                 if (hus.hus_states & HS_LOST)
9004                         printf(" lost_from_hsm");
9005
9006                 if (hus.hus_archive_id != 0)
9007                         printf(", archive_id:%d", hus.hus_archive_id);
9008                 printf("\n");
9009
9010         } while (++i < argc);
9011
9012         return 0;
9013 }
9014
9015 #define LFS_HSM_SET   0
9016 #define LFS_HSM_CLEAR 1
9017
9018 /**
9019  * Generic function to set or clear HSM flags.
9020  * Used by hsm_set and hsm_clear.
9021  *
9022  * @mode  if LFS_HSM_SET, set the flags, if LFS_HSM_CLEAR, clear the flags.
9023  */
9024 static int lfs_hsm_change_flags(int argc, char **argv, int mode)
9025 {
9026         struct option long_opts[] = {
9027         { .val = 'A',   .name = "archived",     .has_arg = no_argument },
9028         { .val = 'a',   .name = "noarchive",    .has_arg = no_argument },
9029         { .val = 'd',   .name = "dirty",        .has_arg = no_argument },
9030         { .val = 'e',   .name = "exists",       .has_arg = no_argument },
9031         { .val = 'l',   .name = "lost",         .has_arg = no_argument },
9032         { .val = 'r',   .name = "norelease",    .has_arg = no_argument },
9033         { .val = 'i',   .name = "archive-id",   .has_arg = required_argument },
9034         { .name = NULL } };
9035         char short_opts[] = "lraAdei:";
9036         __u64 mask = 0;
9037         int c, rc;
9038         char *path;
9039         __u32 archive_id = 0;
9040         char *end = NULL;
9041
9042         if (argc < 3)
9043                 return CMD_HELP;
9044
9045         while ((c = getopt_long(argc, argv, short_opts,
9046                                 long_opts, NULL)) != -1) {
9047                 switch (c) {
9048                 case 'l':
9049                         mask |= HS_LOST;
9050                         break;
9051                 case 'a':
9052                         mask |= HS_NOARCHIVE;
9053                         break;
9054                 case 'A':
9055                         mask |= HS_ARCHIVED;
9056                         break;
9057                 case 'r':
9058                         mask |= HS_NORELEASE;
9059                         break;
9060                 case 'd':
9061                         mask |= HS_DIRTY;
9062                         break;
9063                 case 'e':
9064                         mask |= HS_EXISTS;
9065                         break;
9066                 case 'i':
9067                         errno = 0;
9068                         archive_id = strtol(optarg, &end, 10);
9069                         if (errno != 0 || *end != '\0' || archive_id < 0) {
9070                                 fprintf(stderr, "invalid archive_id: '%s'\n",
9071                                         end);
9072                                 return CMD_HELP;
9073                         }
9074                         break;
9075                 case '?':
9076                         return CMD_HELP;
9077                 default:
9078                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
9079                                 argv[0], argv[optind - 1]);
9080                         return CMD_HELP;
9081                 }
9082         }
9083
9084         /* User should have specified a flag */
9085         if (mask == 0)
9086                 return CMD_HELP;
9087
9088         while (optind < argc) {
9089                 path = argv[optind];
9090
9091                 /* If mode == 0, this means we apply the mask. */
9092                 if (mode == LFS_HSM_SET)
9093                         rc = llapi_hsm_state_set(path, mask, 0, archive_id);
9094                 else
9095                         rc = llapi_hsm_state_set(path, 0, mask, 0);
9096
9097                 if (rc != 0) {
9098                         fprintf(stderr, "Can't change hsm flags for %s: %s\n",
9099                                 path, strerror(errno = -rc));
9100                         return rc;
9101                 }
9102                 optind++;
9103         }
9104
9105         return 0;
9106 }
9107
9108 static int lfs_hsm_action(int argc, char **argv)
9109 {
9110         int                              rc;
9111         int                              i = 1;
9112         char                            *path;
9113         struct hsm_current_action        hca;
9114         struct hsm_extent                he;
9115         enum hsm_user_action             hua;
9116         enum hsm_progress_states         hps;
9117
9118         if (argc < 2)
9119                 return CMD_HELP;
9120
9121         do {
9122                 path = argv[i];
9123
9124                 rc = llapi_hsm_current_action(path, &hca);
9125                 if (rc) {
9126                         fprintf(stderr, "can't get hsm action for %s: %s\n",
9127                                 path, strerror(errno = -rc));
9128                         return rc;
9129                 }
9130                 he = hca.hca_location;
9131                 hua = hca.hca_action;
9132                 hps = hca.hca_state;
9133
9134                 printf("%s: %s", path, hsm_user_action2name(hua));
9135
9136                 /* Skip file without action */
9137                 if (hca.hca_action == HUA_NONE) {
9138                         printf("\n");
9139                         continue;
9140                 }
9141
9142                 printf(" %s ", hsm_progress_state2name(hps));
9143
9144                 if ((hps == HPS_RUNNING) &&
9145                     (hua == HUA_ARCHIVE || hua == HUA_RESTORE))
9146                         printf("(%llu bytes moved)\n",
9147                                (unsigned long long)he.length);
9148                 else if ((he.offset + he.length) == LUSTRE_EOF)
9149                         printf("(from %llu to EOF)\n",
9150                                (unsigned long long)he.offset);
9151                 else
9152                         printf("(from %llu to %llu)\n",
9153                                (unsigned long long)he.offset,
9154                                (unsigned long long)(he.offset + he.length));
9155
9156         } while (++i < argc);
9157
9158         return 0;
9159 }
9160
9161 static int lfs_hsm_set(int argc, char **argv)
9162 {
9163         return lfs_hsm_change_flags(argc, argv, LFS_HSM_SET);
9164 }
9165
9166 static int lfs_hsm_clear(int argc, char **argv)
9167 {
9168         return lfs_hsm_change_flags(argc, argv, LFS_HSM_CLEAR);
9169 }
9170
9171 /**
9172  * Check file state and return its fid, to be used by lfs_hsm_request().
9173  *
9174  * \param[in]     file      Path to file to check
9175  * \param[in,out] fid       Pointer to allocated lu_fid struct.
9176  * \param[in,out] last_dev  Pointer to last device id used.
9177  *
9178  * \return 0 on success.
9179  */
9180 static int lfs_hsm_prepare_file(const char *file, struct lu_fid *fid,
9181                                 dev_t *last_dev)
9182 {
9183         struct stat     st;
9184         int             rc;
9185
9186         rc = lstat(file, &st);
9187         if (rc) {
9188                 fprintf(stderr, "Cannot stat %s: %s\n", file, strerror(errno));
9189                 return -errno;
9190         }
9191         /*
9192          * Checking for regular file as archiving as posix copytool
9193          * rejects archiving files other than regular files
9194          */
9195         if (!S_ISREG(st.st_mode)) {
9196                 fprintf(stderr, "error: \"%s\" is not a regular file\n", file);
9197                 return CMD_HELP;
9198         }
9199         /* A request should be ... */
9200         if (*last_dev != st.st_dev && *last_dev != 0) {
9201                 fprintf(stderr,
9202                         "All files should be on the same filesystem: %s\n",
9203                         file);
9204                 return -EINVAL;
9205         }
9206         *last_dev = st.st_dev;
9207
9208         rc = llapi_path2fid(file, fid);
9209         if (rc) {
9210                 fprintf(stderr, "Cannot read FID of %s: %s\n",
9211                         file, strerror(-rc));
9212                 return rc;
9213         }
9214         return 0;
9215 }
9216
9217 /* Fill an HSM HUR item with a given file name.
9218  *
9219  * If mntpath is set, then the filename is actually a FID, and no
9220  * lookup on the filesystem will be performed.
9221  *
9222  * \param[in]  hur         the user request to fill
9223  * \param[in]  idx         index of the item inside the HUR to fill
9224  * \param[in]  mntpath     mountpoint of Lustre
9225  * \param[in]  fname       filename (if mtnpath is NULL)
9226  *                         or FID (if mntpath is set)
9227  * \param[in]  last_dev    pointer to last device id used
9228  *
9229  * \retval 0 on success
9230  * \retval CMD_HELP or a negative errno on error
9231  */
9232 static int fill_hur_item(struct hsm_user_request *hur, unsigned int idx,
9233                          const char *mntpath, const char *fname,
9234                          dev_t *last_dev)
9235 {
9236         struct hsm_user_item *hui = &hur->hur_user_item[idx];
9237         int rc;
9238
9239         hui->hui_extent.length = -1;
9240
9241         if (mntpath) {
9242                 rc = llapi_fid_parse(fname, &hui->hui_fid, NULL);
9243                 if (rc)
9244                         fprintf(stderr, "hsm: '%s' is not a valid FID\n",
9245                                 fname);
9246         } else {
9247                 rc = lfs_hsm_prepare_file(fname, &hui->hui_fid, last_dev);
9248         }
9249
9250         if (rc == 0)
9251                 hur->hur_request.hr_itemcount++;
9252
9253         return rc;
9254 }
9255
9256 static int lfs_hsm_request(int argc, char **argv, int action)
9257 {
9258         struct option long_opts[] = {
9259         { .val = 'a',   .name = "archive",      .has_arg = required_argument },
9260         { .val = 'D',   .name = "data",         .has_arg = required_argument },
9261         { .val = 'l',   .name = "filelist",     .has_arg = required_argument },
9262         { .val = 'm',   .name = "mntpath",      .has_arg = required_argument },
9263         { .name = NULL } };
9264         dev_t last_dev = 0;
9265         char short_opts[] = "l:D:a:m:";
9266         struct hsm_user_request *hur, *oldhur;
9267         int c, i;
9268         size_t len;
9269         int nbfile;
9270         char *line = NULL;
9271         char *filelist = NULL;
9272         char fullpath[PATH_MAX];
9273         char *opaque = NULL;
9274         int opaque_len = 0;
9275         int archive_id = 0;
9276         FILE *fp;
9277         int nbfile_alloc = 0;
9278         char *some_file = NULL;
9279         char *mntpath = NULL;
9280         int rc;
9281
9282         if (argc < 2)
9283                 return CMD_HELP;
9284
9285         while ((c = getopt_long(argc, argv, short_opts,
9286                                 long_opts, NULL)) != -1) {
9287                 switch (c) {
9288                 case 'l':
9289                         filelist = optarg;
9290                         break;
9291                 case 'D':
9292                         opaque = optarg;
9293                         break;
9294                 case 'a':
9295                         if (action != HUA_ARCHIVE &&
9296                             action != HUA_REMOVE) {
9297                                 fprintf(stderr,
9298                                         "error: -a is supported only when archiving or removing\n");
9299                                 return CMD_HELP;
9300                         }
9301                         archive_id = atoi(optarg);
9302                         break;
9303                 case 'm':
9304                         if (!some_file) {
9305                                 mntpath = optarg;
9306                                 some_file = strdup(optarg);
9307                         }
9308                         break;
9309                 case '?':
9310                         return CMD_HELP;
9311                 default:
9312                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
9313                                 argv[0], argv[optind - 1]);
9314                         return CMD_HELP;
9315                 }
9316         }
9317
9318         /* All remaining args are files, so we have at least nbfile */
9319         nbfile = argc - optind;
9320
9321         if ((nbfile == 0) && (!filelist))
9322                 return CMD_HELP;
9323
9324         if (opaque)
9325                 opaque_len = strlen(opaque);
9326
9327         /*
9328          * Alloc the request structure with enough place to store all files
9329          * from command line.
9330          */
9331         hur = llapi_hsm_user_request_alloc(nbfile, opaque_len);
9332         if (!hur) {
9333                 fprintf(stderr, "Cannot create the request: %s\n",
9334                         strerror(errno));
9335                 return errno;
9336         }
9337         nbfile_alloc = nbfile;
9338
9339         hur->hur_request.hr_action = action;
9340         hur->hur_request.hr_archive_id = archive_id;
9341         hur->hur_request.hr_flags = 0;
9342
9343         /* All remaining args are files, add them */
9344         if (nbfile != 0 && some_file == NULL)
9345                 some_file = strdup(argv[optind]);
9346
9347         for (i = 0; i < nbfile; i++) {
9348                 rc = fill_hur_item(hur, i, mntpath, argv[optind + i],
9349                                    &last_dev);
9350                 if (rc)
9351                         goto out_free;
9352         }
9353
9354         /* from here stop using nb_file, use hur->hur_request.hr_itemcount */
9355
9356         /* If a filelist was specified, read the filelist from it. */
9357         if (filelist) {
9358                 fp = fopen(filelist, "r");
9359                 if (!fp) {
9360                         fprintf(stderr, "Cannot read the file list %s: %s\n",
9361                                 filelist, strerror(errno));
9362                         rc = -errno;
9363                         goto out_free;
9364                 }
9365
9366                 while ((rc = getline(&line, &len, fp)) != -1) {
9367                         /*
9368                          * If allocated buffer was too small, get something
9369                          * larger
9370                          */
9371                         if (nbfile_alloc <= hur->hur_request.hr_itemcount) {
9372                                 ssize_t size;
9373
9374                                 nbfile_alloc = nbfile_alloc * 2 + 1;
9375                                 oldhur = hur;
9376                                 hur = llapi_hsm_user_request_alloc(nbfile_alloc,
9377                                                                    opaque_len);
9378                                 if (!hur) {
9379                                         fprintf(stderr,
9380                                                 "hsm: cannot allocate the request: %s\n",
9381                                                 strerror(errno));
9382                                         hur = oldhur;
9383                                         rc = -errno;
9384                                         fclose(fp);
9385                                         goto out_free;
9386                                 }
9387                                 size = hur_len(oldhur);
9388                                 if (size < 0) {
9389                                         fprintf(stderr,
9390                                                 "hsm: cannot allocate %u files + %u bytes data\n",
9391                                                 oldhur->hur_request.hr_itemcount,
9392                                                 oldhur->hur_request.hr_data_len);
9393                                         free(hur);
9394                                         hur = oldhur;
9395                                         rc = -E2BIG;
9396                                         fclose(fp);
9397                                         goto out_free;
9398                                 }
9399                                 memcpy(hur, oldhur, size);
9400                                 free(oldhur);
9401                         }
9402
9403                         /* Chop CR */
9404                         if (line[strlen(line) - 1] == '\n')
9405                                 line[strlen(line) - 1] = '\0';
9406
9407                         rc = fill_hur_item(hur, hur->hur_request.hr_itemcount,
9408                                            mntpath, line, &last_dev);
9409                         if (rc) {
9410                                 fclose(fp);
9411                                 goto out_free;
9412                         }
9413
9414                         if (!some_file) {
9415                                 some_file = line;
9416                                 line = NULL;
9417                         }
9418                 }
9419
9420                 rc = fclose(fp);
9421                 free(line);
9422         }
9423
9424         /* If a --data was used, add it to the request */
9425         hur->hur_request.hr_data_len = opaque_len;
9426         if (opaque)
9427                 memcpy(hur_data(hur), opaque, opaque_len);
9428
9429         /* Send the HSM request */
9430         if (realpath(some_file, fullpath) == NULL) {
9431                 fprintf(stderr, "Could not find path '%s': %s\n",
9432                         some_file, strerror(errno));
9433         }
9434         rc = llapi_hsm_request(fullpath, hur);
9435         if (rc) {
9436                 fprintf(stderr, "Cannot send HSM request (use of %s): %s\n",
9437                         some_file, strerror(-rc));
9438                 goto out_free;
9439         }
9440
9441 out_free:
9442         free(some_file);
9443         free(hur);
9444         return rc;
9445 }
9446
9447 static int lfs_hsm_archive(int argc, char **argv)
9448 {
9449         return lfs_hsm_request(argc, argv, HUA_ARCHIVE);
9450 }
9451
9452 static int lfs_hsm_restore(int argc, char **argv)
9453 {
9454         return lfs_hsm_request(argc, argv, HUA_RESTORE);
9455 }
9456
9457 static int lfs_hsm_release(int argc, char **argv)
9458 {
9459         return lfs_hsm_request(argc, argv, HUA_RELEASE);
9460 }
9461
9462 static int lfs_hsm_remove(int argc, char **argv)
9463 {
9464         return lfs_hsm_request(argc, argv, HUA_REMOVE);
9465 }
9466
9467 static int lfs_hsm_cancel(int argc, char **argv)
9468 {
9469         return lfs_hsm_request(argc, argv, HUA_CANCEL);
9470 }
9471
9472 static int lfs_swap_layouts(int argc, char **argv)
9473 {
9474         if (argc != 3)
9475                 return CMD_HELP;
9476
9477         return llapi_swap_layouts(argv[1], argv[2], 0, 0,
9478                                   SWAP_LAYOUTS_KEEP_MTIME |
9479                                   SWAP_LAYOUTS_KEEP_ATIME);
9480 }
9481
9482 static const char *const ladvise_names[] = LU_LADVISE_NAMES;
9483
9484 static const char *const lock_mode_names[] = LOCK_MODE_NAMES;
9485
9486 int lfs_get_mode(const char *string)
9487 {
9488         enum lock_mode_user mode;
9489
9490         for (mode = 0; mode < ARRAY_SIZE(lock_mode_names); mode++) {
9491                 if (lock_mode_names[mode] == NULL)
9492                         continue;
9493                 if (strcmp(string, lock_mode_names[mode]) == 0)
9494                         return mode;
9495         }
9496
9497         return -EINVAL;
9498 }
9499
9500 static enum lu_ladvise_type lfs_get_ladvice(const char *string)
9501 {
9502         enum lu_ladvise_type advice;
9503
9504         for (advice = 0;
9505              advice < ARRAY_SIZE(ladvise_names); advice++) {
9506                 if (ladvise_names[advice] == NULL)
9507                         continue;
9508                 if (strcmp(string, ladvise_names[advice]) == 0)
9509                         return advice;
9510         }
9511
9512         return LU_LADVISE_INVALID;
9513 }
9514
9515 static int lfs_ladvise(int argc, char **argv)
9516 {
9517         struct option long_opts[] = {
9518         { .val = 'a',   .name = "advice",       .has_arg = required_argument },
9519         { .val = 'b',   .name = "background",   .has_arg = no_argument },
9520         { .val = 'e',   .name = "end",          .has_arg = required_argument },
9521         { .val = 'l',   .name = "length",       .has_arg = required_argument },
9522         { .val = 'm',   .name = "mode",         .has_arg = required_argument },
9523         { .val = 's',   .name = "start",        .has_arg = required_argument },
9524         { .val = 'u',   .name = "unset",        .has_arg = no_argument },
9525         { .name = NULL } };
9526         char                     short_opts[] = "a:be:l:m:s:u";
9527         int                      c;
9528         int                      rc = 0;
9529         const char              *path;
9530         int                      fd;
9531         struct llapi_lu_ladvise  advice;
9532         enum lu_ladvise_type     advice_type = LU_LADVISE_INVALID;
9533         unsigned long long       start = 0;
9534         unsigned long long       end = LUSTRE_EOF;
9535         unsigned long long       length = 0;
9536         unsigned long long       size_units;
9537         unsigned long long       flags = 0;
9538         int                      mode = 0;
9539
9540         optind = 0;
9541         while ((c = getopt_long(argc, argv, short_opts,
9542                                 long_opts, NULL)) != -1) {
9543                 switch (c) {
9544                 case 'a':
9545                         advice_type = lfs_get_ladvice(optarg);
9546                         if (advice_type == LU_LADVISE_INVALID) {
9547                                 fprintf(stderr,
9548                                         "%s: invalid advice type '%s'\n",
9549                                         argv[0], optarg);
9550                                 fprintf(stderr, "Valid types:");
9551
9552                                 for (advice_type = 0;
9553                                      advice_type < ARRAY_SIZE(ladvise_names);
9554                                      advice_type++) {
9555                                         if (ladvise_names[advice_type] == NULL)
9556                                                 continue;
9557                                         fprintf(stderr, " %s",
9558                                                 ladvise_names[advice_type]);
9559                                 }
9560                                 fprintf(stderr, "\n");
9561
9562                                 return CMD_HELP;
9563                         }
9564                         break;
9565                 case 'b':
9566                         flags |= LF_ASYNC;
9567                         break;
9568                 case 'u':
9569                         flags |= LF_UNSET;
9570                         break;
9571                 case 'e':
9572                         size_units = 1;
9573                         rc = llapi_parse_size(optarg, &end,
9574                                               &size_units, 0);
9575                         if (rc) {
9576                                 fprintf(stderr, "%s: bad end offset '%s'\n",
9577                                         argv[0], optarg);
9578                                 return CMD_HELP;
9579                         }
9580                         break;
9581                 case 's':
9582                         size_units = 1;
9583                         rc = llapi_parse_size(optarg, &start,
9584                                               &size_units, 0);
9585                         if (rc) {
9586                                 fprintf(stderr,
9587                                         "%s: bad start offset '%s'\n",
9588                                         argv[0], optarg);
9589                                 return CMD_HELP;
9590                         }
9591                         break;
9592                 case 'l':
9593                         size_units = 1;
9594                         rc = llapi_parse_size(optarg, &length,
9595                                               &size_units, 0);
9596                         if (rc) {
9597                                 fprintf(stderr, "%s: bad length '%s'\n",
9598                                         argv[0], optarg);
9599                                 return CMD_HELP;
9600                         }
9601                         break;
9602                 case 'm':
9603                         mode = lfs_get_mode(optarg);
9604                         if (mode < 0) {
9605                                 fprintf(stderr,
9606                                         "%s: bad mode '%s', valid modes are READ or WRITE\n",
9607                                         argv[0], optarg);
9608                                 return CMD_HELP;
9609                         }
9610                         break;
9611                 case '?':
9612                         return CMD_HELP;
9613                 default:
9614                         fprintf(stderr, "%s: option '%s' unrecognized\n",
9615                                 argv[0], argv[optind - 1]);
9616                         return CMD_HELP;
9617                 }
9618         }
9619
9620         if (advice_type == LU_LADVISE_INVALID) {
9621                 fprintf(stderr, "%s: please give an advice type\n", argv[0]);
9622                 fprintf(stderr, "Valid types:");
9623                 for (advice_type = 0; advice_type < ARRAY_SIZE(ladvise_names);
9624                      advice_type++) {
9625                         if (ladvise_names[advice_type] == NULL)
9626                                 continue;
9627                         fprintf(stderr, " %s", ladvise_names[advice_type]);
9628                 }
9629                 fprintf(stderr, "\n");
9630                 return CMD_HELP;
9631         }
9632
9633         if (advice_type == LU_LADVISE_LOCKNOEXPAND) {
9634                 fprintf(stderr,
9635                         "%s: Lock no expand advice is a per file descriptor advice, so when called from lfs, it does nothing.\n",
9636                         argv[0]);
9637                 return CMD_HELP;
9638         }
9639
9640         if (argc <= optind) {
9641                 fprintf(stderr, "%s: please give one or more file names\n",
9642                         argv[0]);
9643                 return CMD_HELP;
9644         }
9645
9646         if (end != LUSTRE_EOF && length != 0 && end != start + length) {
9647                 fprintf(stderr, "%s: conflicting arguments of -l and -e\n",
9648                         argv[0]);
9649                 return CMD_HELP;
9650         }
9651
9652         if (end == LUSTRE_EOF && length != 0)
9653                 end = start + length;
9654
9655         if (end <= start) {
9656                 fprintf(stderr, "%s: range [%llu, %llu] is invalid\n",
9657                         argv[0], start, end);
9658                 return CMD_HELP;
9659         }
9660
9661         if (advice_type != LU_LADVISE_LOCKAHEAD && mode != 0) {
9662                 fprintf(stderr, "%s: mode is only valid with lockahead\n",
9663                         argv[0]);
9664                 return CMD_HELP;
9665         }
9666
9667         if (advice_type == LU_LADVISE_LOCKAHEAD && mode == 0) {
9668                 fprintf(stderr, "%s: mode is required with lockahead\n",
9669                         argv[0]);
9670                 return CMD_HELP;
9671         }
9672
9673         while (optind < argc) {
9674                 int rc2;
9675
9676                 path = argv[optind++];
9677
9678                 fd = open(path, O_RDONLY);
9679                 if (fd < 0) {
9680                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
9681                                 argv[0], path, strerror(errno));
9682                         rc2 = -errno;
9683                         goto next;
9684                 }
9685
9686                 advice.lla_start = start;
9687                 advice.lla_end = end;
9688                 advice.lla_advice = advice_type;
9689                 advice.lla_value1 = 0;
9690                 advice.lla_value2 = 0;
9691                 advice.lla_value3 = 0;
9692                 advice.lla_value4 = 0;
9693                 if (advice_type == LU_LADVISE_LOCKAHEAD) {
9694                         advice.lla_lockahead_mode = mode;
9695                         advice.lla_peradvice_flags = flags;
9696                 }
9697
9698                 rc2 = llapi_ladvise(fd, flags, 1, &advice);
9699                 close(fd);
9700                 if (rc2 < 0) {
9701                         fprintf(stderr,
9702                                 "%s: cannot give advice '%s' to file '%s': %s\n",
9703                                 argv[0], ladvise_names[advice_type],
9704                                 path, strerror(errno));
9705
9706                         goto next;
9707                 }
9708
9709 next:
9710                 if (rc == 0 && rc2 < 0)
9711                         rc = rc2;
9712         }
9713         return rc;
9714 }
9715
9716 static const char *const heat_names[] = LU_HEAT_NAMES;
9717
9718 static int lfs_heat_get(int argc, char **argv)
9719 {
9720         struct lu_heat *heat;
9721         int rc = 0, rc2;
9722         char *path;
9723         int fd;
9724         int i;
9725
9726         if (argc <= 1)
9727                 return CMD_HELP;
9728
9729         heat = calloc(sizeof(*heat) + sizeof(__u64) * OBD_HEAT_COUNT, 1);
9730         if (!heat) {
9731                 fprintf(stderr, "%s: memory allocation failed\n", argv[0]);
9732                 return -ENOMEM;
9733         }
9734
9735         optind = 1;
9736         while (optind < argc) {
9737                 path = argv[optind++];
9738
9739                 fd = open(path, O_RDONLY);
9740                 if (fd < 0) {
9741                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
9742                                 argv[0], path, strerror(errno));
9743                         rc2 = -errno;
9744                         goto next;
9745                 }
9746
9747                 heat->lh_count = OBD_HEAT_COUNT;
9748                 rc2 = llapi_heat_get(fd, heat);
9749                 close(fd);
9750                 if (rc2 < 0) {
9751                         fprintf(stderr,
9752                                 "%s: cannot get heat of file '%s': %s\n",
9753                                 argv[0], path, strerror(errno));
9754                         goto next;
9755                 }
9756
9757                 printf("flags: %x\n", heat->lh_flags);
9758                 for (i = 0; i < heat->lh_count; i++)
9759                         printf("%s: %llu\n", heat_names[i],
9760                                (unsigned long long)heat->lh_heat[i]);
9761 next:
9762                 if (rc == 0 && rc2 < 0)
9763                         rc = rc2;
9764         }
9765
9766         free(heat);
9767         return rc;
9768 }
9769
9770 static int lfs_heat_set(int argc, char **argv)
9771 {
9772         struct option long_opts[] = {
9773         { .val = 'c',   .name = "clear",        .has_arg = no_argument },
9774         { .val = 'o',   .name = "off",          .has_arg = no_argument },
9775         { .val = 'O',   .name = "on",           .has_arg = no_argument },
9776         { .name = NULL } };
9777         enum lu_heat_flag flags = 0;
9778         int rc = 0, rc2;
9779         char *path;
9780         int fd;
9781         int c;
9782
9783         if (argc <= 1)
9784                 return CMD_HELP;
9785
9786         optind = 0;
9787         while ((c = getopt_long(argc, argv, "coO", long_opts, NULL)) != -1) {
9788                 switch (c) {
9789                 case 'c':
9790                         flags |= LU_HEAT_FLAG_CLEAR;
9791                         break;
9792                 case 'o':
9793                         flags |= LU_HEAT_FLAG_CLEAR;
9794                         flags |= LU_HEAT_FLAG_OFF;
9795                         break;
9796                 case 'O':
9797                         flags &= ~LU_HEAT_FLAG_OFF;
9798                         break;
9799                 case '?':
9800                         return CMD_HELP;
9801                 default:
9802                         fprintf(stderr, "%s: option '%s' unrecognized\n",
9803                                 argv[0], argv[optind - 1]);
9804                         return CMD_HELP;
9805                 }
9806         }
9807
9808         if (argc <= optind) {
9809                 fprintf(stderr, "%s: please give one or more file names\n",
9810                         argv[0]);
9811                 return CMD_HELP;
9812         }
9813
9814         while (optind < argc) {
9815                 path = argv[optind++];
9816
9817                 fd = open(path, O_RDONLY);
9818                 if (fd < 0) {
9819                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
9820                                 argv[0], path, strerror(errno));
9821                         rc2 = -errno;
9822                         goto next;
9823                 }
9824
9825                 rc2 = llapi_heat_set(fd, flags);
9826                 close(fd);
9827                 if (rc2 < 0) {
9828                         fprintf(stderr,
9829                                 "%s: cannot setflags heat of file '%s': %s\n",
9830                                 argv[0], path, strerror(errno));
9831                         goto next;
9832                 }
9833 next:
9834                 if (rc == 0 && rc2 < 0)
9835                         rc = rc2;
9836         }
9837         return rc;
9838 }
9839
9840 /**
9841  * The input string contains a comma delimited list of component ids and
9842  * ranges, for example "1,2-4,7".
9843  */
9844 static int parse_mirror_ids(__u16 *ids, int size, char *arg)
9845 {
9846         bool end_of_loop = false;
9847         char *ptr = NULL;
9848         int nr = 0;
9849         int rc;
9850
9851         if (!arg)
9852                 return -EINVAL;
9853
9854         while (!end_of_loop) {
9855                 int start_index;
9856                 int end_index;
9857                 int i;
9858                 char *endptr = NULL;
9859
9860                 rc = -EINVAL;
9861                 ptr = strchrnul(arg, ',');
9862                 end_of_loop = *ptr == '\0';
9863                 *ptr = '\0';
9864
9865                 start_index = strtol(arg, &endptr, 0);
9866                 if (endptr == arg) /* no data at all */
9867                         break;
9868                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
9869                         break;
9870                 if (start_index < 0)
9871                         break;
9872
9873                 end_index = start_index;
9874                 if (*endptr == '-') {
9875                         end_index = strtol(endptr + 1, &endptr, 0);
9876                         if (*endptr != '\0')
9877                                 break;
9878                         if (end_index < start_index)
9879                                 break;
9880                 }
9881
9882                 for (i = start_index; i <= end_index && size > 0; i++) {
9883                         int j;
9884
9885                         /* remove duplicate */
9886                         for (j = 0; j < nr; j++) {
9887                                 if (ids[j] == i)
9888                                         break;
9889                         }
9890                         if (j == nr) { /* no duplicate */
9891                                 ids[nr++] = i;
9892                                 --size;
9893                         }
9894                 }
9895
9896                 if (size == 0 && i < end_index)
9897                         break;
9898
9899                 *ptr = ',';
9900                 arg = ++ptr;
9901                 rc = 0;
9902         }
9903         if (!end_of_loop && ptr)
9904                 *ptr = ',';
9905
9906         return rc < 0 ? rc : nr;
9907 }
9908
9909 /**
9910  * struct verify_mirror_id - Mirror id to be verified.
9911  * @mirror_id:   A specified mirror id.
9912  * @is_valid_id: @mirror_id is valid or not in the mirrored file.
9913  */
9914 struct verify_mirror_id {
9915         __u16 mirror_id;
9916         bool is_valid_id;
9917 };
9918
9919 /**
9920  * compare_mirror_ids() - Compare mirror ids.
9921  * @layout: Mirror component list.
9922  * @cbdata: Callback data in verify_mirror_id structure.
9923  *
9924  * This is a callback function called by llapi_layout_comp_iterate()
9925  * to compare the specified mirror id with the one in the current
9926  * component of @layout. If they are the same, then the specified
9927  * mirror id is valid.
9928  *
9929  * Return: a negative error code on failure or
9930  *         LLAPI_LAYOUT_ITER_CONT: Proceed iteration
9931  *         LLAPI_LAYOUT_ITER_STOP: Stop iteration
9932  */
9933 static inline
9934 int compare_mirror_ids(struct llapi_layout *layout, void *cbdata)
9935 {
9936         struct verify_mirror_id *mirror_id_cbdata =
9937                                  (struct verify_mirror_id *)cbdata;
9938         uint32_t mirror_id;
9939         int rc = 0;
9940
9941         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
9942         if (rc < 0) {
9943                 rc = -errno;
9944                 fprintf(stderr,
9945                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
9946                         progname, strerror(errno));
9947                 return rc;
9948         }
9949
9950         if (mirror_id_cbdata->mirror_id == mirror_id) {
9951                 mirror_id_cbdata->is_valid_id = true;
9952                 return LLAPI_LAYOUT_ITER_STOP;
9953         }
9954
9955         return LLAPI_LAYOUT_ITER_CONT;
9956 }
9957
9958 /**
9959  * verify_mirror_ids() - Verify specified mirror ids.
9960  * @fname:      Mirrored file name.
9961  * @mirror_ids: Specified mirror ids to be verified.
9962  * @ids_nr:     Number of specified mirror ids.
9963  *
9964  * This function verifies that specified @mirror_ids are valid
9965  * in the mirrored file @fname.
9966  *
9967  * Return: 0 on success or a negative error code on failure.
9968  */
9969 static inline
9970 int verify_mirror_ids(const char *fname, __u16 *mirror_ids, int ids_nr)
9971 {
9972         struct llapi_layout *layout = NULL;
9973         struct verify_mirror_id mirror_id_cbdata = { 0 };
9974         struct stat stbuf;
9975         uint32_t flr_state;
9976         int i;
9977         int fd;
9978         int rc = 0;
9979         int rc2 = 0;
9980
9981         if (ids_nr <= 0)
9982                 return -EINVAL;
9983
9984         if (stat(fname, &stbuf) < 0) {
9985                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
9986                         progname, fname, strerror(errno));
9987                 rc = -errno;
9988                 goto error;
9989         }
9990
9991         if (!S_ISREG(stbuf.st_mode)) {
9992                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
9993                         progname, fname);
9994                 rc = -EINVAL;
9995                 goto error;
9996         }
9997
9998         fd = open(fname, O_DIRECT | O_RDONLY);
9999         if (fd < 0) {
10000                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
10001                         progname, fname, strerror(errno));
10002                 rc = -errno;
10003                 goto error;
10004         }
10005
10006         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
10007         if (rc < 0) {
10008                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
10009                         progname, fname, strerror(errno));
10010                 goto close_fd;
10011         }
10012
10013         layout = llapi_layout_get_by_fd(fd, 0);
10014         if (!layout) {
10015                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
10016                         progname, fname, strerror(errno));
10017                 rc = -errno;
10018                 llapi_lease_release(fd);
10019                 goto close_fd;
10020         }
10021
10022         rc = llapi_layout_flags_get(layout, &flr_state);
10023         if (rc < 0) {
10024                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
10025                         progname, fname, strerror(errno));
10026                 rc = -errno;
10027                 goto free_layout;
10028         }
10029
10030         flr_state &= LCM_FL_FLR_MASK;
10031         switch (flr_state) {
10032         case LCM_FL_NONE:
10033                 rc = -EINVAL;
10034                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
10035                         progname, fname, llapi_layout_flags_string(flr_state));
10036                 goto free_layout;
10037         default:
10038                 break;
10039         }
10040
10041         rc2 = 0;
10042         for (i = 0; i < ids_nr; i++) {
10043                 mirror_id_cbdata.mirror_id = mirror_ids[i];
10044                 mirror_id_cbdata.is_valid_id = false;
10045
10046                 rc = llapi_layout_comp_iterate(layout, compare_mirror_ids,
10047                                                &mirror_id_cbdata);
10048                 if (rc < 0) {
10049                         rc = -errno;
10050                         fprintf(stderr,
10051                                 "%s: '%s' failed to verify mirror id: %u.\n",
10052                                 progname, fname, mirror_ids[i]);
10053                         goto free_layout;
10054                 }
10055
10056                 if (!mirror_id_cbdata.is_valid_id) {
10057                         rc2 = -EINVAL;
10058                         fprintf(stderr,
10059                                 "%s: '%s' invalid specified mirror id: %u.\n",
10060                                 progname, fname, mirror_ids[i]);
10061                 }
10062         }
10063         rc = rc2;
10064
10065 free_layout:
10066         llapi_layout_free(layout);
10067         llapi_lease_release(fd);
10068 close_fd:
10069         close(fd);
10070 error:
10071         return rc;
10072 }
10073
10074 static inline
10075 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
10076                            __u16 *mirror_ids, int ids_nr)
10077 {
10078         struct llapi_resync_comp comp_array[1024] = { { 0 } };
10079         struct llapi_layout *layout;
10080         struct stat stbuf;
10081         uint32_t flr_state;
10082         uint64_t start;
10083         uint64_t end;
10084         int comp_size = 0;
10085         int idx;
10086         int fd;
10087         int rc;
10088         int rc2;
10089
10090         if (stat(fname, &stbuf) < 0) {
10091                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
10092                         progname, fname, strerror(errno));
10093                 rc = -errno;
10094                 goto error;
10095         }
10096         if (!S_ISREG(stbuf.st_mode)) {
10097                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
10098                         progname, fname);
10099                 rc = -EINVAL;
10100                 goto error;
10101         }
10102
10103         fd = open(fname, O_DIRECT | O_RDWR);
10104         if (fd < 0) {
10105                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
10106                         progname, fname, strerror(errno));
10107                 rc = -errno;
10108                 goto error;
10109         }
10110
10111         layout = llapi_layout_get_by_fd(fd, 0);
10112         if (!layout) {
10113                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
10114                         progname, fname, strerror(errno));
10115                 rc = -errno;
10116                 goto close_fd;
10117         }
10118
10119         rc = llapi_layout_flags_get(layout, &flr_state);
10120         if (rc) {
10121                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
10122                         progname, fname, strerror(errno));
10123                 rc = -errno;
10124                 goto free_layout;
10125         }
10126
10127         flr_state &= LCM_FL_FLR_MASK;
10128         if (flr_state == LCM_FL_NONE) {
10129                 rc = -EINVAL;
10130                 fprintf(stderr, "%s: '%s' is not a FLR file.\n",
10131                         progname, fname);
10132                 goto free_layout;
10133         }
10134
10135         /* get stale component info */
10136         comp_size = llapi_mirror_find_stale(layout, comp_array,
10137                                             ARRAY_SIZE(comp_array),
10138                                             mirror_ids, ids_nr);
10139         if (comp_size <= 0) {
10140                 rc = comp_size;
10141                 goto free_layout;
10142         }
10143
10144         ioc->lil_mode = LL_LEASE_WRLCK;
10145         ioc->lil_flags = LL_LEASE_RESYNC;
10146         rc = llapi_lease_set(fd, ioc);
10147         if (rc < 0) {
10148                 if (rc == -EALREADY)
10149                         rc = 0;
10150                 else
10151                         fprintf(stderr,
10152                             "%s: '%s' llapi_lease_get_ext resync failed: %s.\n",
10153                                 progname, fname, strerror(-rc));
10154                 goto free_layout;
10155         }
10156
10157         /* get the read range [start, end) */
10158         start = comp_array[0].lrc_start;
10159         end = comp_array[0].lrc_end;
10160         for (idx = 1; idx < comp_size; idx++) {
10161                 if (comp_array[idx].lrc_start < start)
10162                         start = comp_array[idx].lrc_start;
10163                 if (end < comp_array[idx].lrc_end)
10164                         end = comp_array[idx].lrc_end;
10165         }
10166
10167         rc = llapi_lease_check(fd);
10168         if (rc != LL_LEASE_WRLCK) {
10169                 fprintf(stderr, "%s: '%s' lost lease lock.\n",
10170                         progname, fname);
10171                 goto free_layout;
10172         }
10173
10174         rc = llapi_mirror_resync_many(fd, layout, comp_array, comp_size,
10175                                       start, end);
10176         if (rc < 0)
10177                 fprintf(stderr, "%s: '%s' llapi_mirror_resync_many: %s.\n",
10178                         progname, fname, strerror(-rc));
10179
10180         /* need to do the lease unlock even resync fails */
10181         ioc->lil_mode = LL_LEASE_UNLCK;
10182         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
10183         ioc->lil_count = 0;
10184         for (idx = 0; idx < comp_size; idx++) {
10185                 if (comp_array[idx].lrc_synced) {
10186                         ioc->lil_ids[ioc->lil_count] = comp_array[idx].lrc_id;
10187                         ioc->lil_count++;
10188                 }
10189         }
10190
10191         rc2 = llapi_lease_set(fd, ioc);
10192         /**
10193          * llapi_lease_set returns lease mode when it request to unlock
10194          * the lease lock.
10195          */
10196         if (rc2 <= 0) {
10197                 /* rc2 == 0 means lost lease lock */
10198                 if (rc2 == 0 && rc == 0)
10199                         rc = -EBUSY;
10200                 fprintf(stderr, "%s: resync file '%s' failed: %s.\n",
10201                         progname, fname,
10202                         rc2 == 0 ? "lost lease lock" : strerror(-rc2));
10203         }
10204
10205 free_layout:
10206         llapi_layout_free(layout);
10207 close_fd:
10208         close(fd);
10209 error:
10210         return rc;
10211 }
10212
10213 static inline int lfs_mirror_resync(int argc, char **argv)
10214 {
10215         struct ll_ioc_lease *ioc = NULL;
10216         __u16 mirror_ids[128] = { 0 };
10217         int ids_nr = 0;
10218         int c;
10219         int rc = 0;
10220
10221         struct option long_opts[] = {
10222         { .val = 'o',   .name = "only",         .has_arg = required_argument },
10223         { .name = NULL } };
10224
10225         while ((c = getopt_long(argc, argv, "o:", long_opts, NULL)) >= 0) {
10226                 switch (c) {
10227                 case 'o':
10228                         rc = parse_mirror_ids(mirror_ids,
10229                                         sizeof(mirror_ids) / sizeof(__u16),
10230                                         optarg);
10231                         if (rc < 0) {
10232                                 fprintf(stderr,
10233                                         "%s: bad mirror ids '%s'.\n",
10234                                         argv[0], optarg);
10235                                 goto error;
10236                         }
10237                         ids_nr = rc;
10238                         break;
10239                 default:
10240                         fprintf(stderr, "%s: options '%s' unrecognized.\n",
10241                                 argv[0], argv[optind - 1]);
10242                         rc = -EINVAL;
10243                         goto error;
10244                 }
10245         }
10246
10247         if (argc == optind) {
10248                 fprintf(stderr, "%s: no file name given.\n", argv[0]);
10249                 rc = CMD_HELP;
10250                 goto error;
10251         }
10252
10253         if (ids_nr > 0 && argc > optind + 1) {
10254                 fprintf(stderr,
10255                     "%s: option '--only' cannot be used upon multiple files.\n",
10256                         argv[0]);
10257                 rc = CMD_HELP;
10258                 goto error;
10259         }
10260
10261         if (ids_nr > 0) {
10262                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
10263                 if (rc < 0)
10264                         goto error;
10265         }
10266
10267         /* set the lease on the file */
10268         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
10269         if (!ioc) {
10270                 fprintf(stderr, "%s: cannot alloc id array for ioc: %s.\n",
10271                         argv[0], strerror(errno));
10272                 rc = -errno;
10273                 goto error;
10274         }
10275
10276         for (; optind < argc; optind++) {
10277                 rc = lfs_mirror_resync_file(argv[optind], ioc,
10278                                             mirror_ids, ids_nr);
10279                 /* ignore previous file's error, continue with next file */
10280
10281                 /* reset ioc */
10282                 memset(ioc, 0, sizeof(*ioc) + sizeof(__u32) * 4096);
10283         }
10284
10285         free(ioc);
10286 error:
10287         return rc;
10288 }
10289
10290 static inline int verify_mirror_id_by_fd(int fd, __u16 mirror_id)
10291 {
10292         struct llapi_layout *layout;
10293         int rc;
10294
10295         layout = llapi_layout_get_by_fd(fd, 0);
10296         if (!layout) {
10297                 fprintf(stderr, "could not get layout.\n");
10298                 return  -EINVAL;
10299         }
10300
10301         rc = llapi_layout_comp_iterate(layout, find_mirror_id, &mirror_id);
10302         if (rc < 0) {
10303                 fprintf(stderr, "failed to iterate layout\n");
10304                 llapi_layout_free(layout);
10305
10306                 return rc;
10307         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
10308                 fprintf(stderr, "does not find mirror with ID %u\n", mirror_id);
10309                 llapi_layout_free(layout);
10310
10311                 return -EINVAL;
10312         }
10313         llapi_layout_free(layout);
10314
10315         return 0;
10316 }
10317
10318 /**
10319  * Check whether two files are the same file
10320  * \retval      0  same file
10321  * \retval      1  not the same file
10322  * \retval      <0 error code
10323  */
10324 static inline int check_same_file(int fd, const char *f2)
10325 {
10326         struct stat stbuf1;
10327         struct stat stbuf2;
10328
10329         if (fstat(fd, &stbuf1) < 0)
10330                 return -errno;
10331
10332         if (stat(f2, &stbuf2) < 0)
10333                 return 1;
10334
10335         if (stbuf1.st_rdev == stbuf2.st_rdev &&
10336             stbuf1.st_ino == stbuf2.st_ino)
10337                 return 0;
10338
10339         return 1;
10340 }
10341
10342 static inline int lfs_mirror_read(int argc, char **argv)
10343 {
10344         int rc = CMD_HELP;
10345         __u16 mirror_id = 0;
10346         const char *outfile = NULL;
10347         char *fname;
10348         int fd = 0;
10349         int outfd;
10350         int c;
10351         void *buf;
10352         const size_t buflen = 4 << 20;
10353         off_t pos;
10354         struct option long_opts[] = {
10355         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
10356         { .val = 'o',   .name = "outfile",      .has_arg = required_argument },
10357         { .name = NULL } };
10358
10359         while ((c = getopt_long(argc, argv, "N:o:", long_opts, NULL)) >= 0) {
10360                 char *end;
10361
10362                 switch (c) {
10363                 case 'N': {
10364                         unsigned long int id;
10365
10366                         errno = 0;
10367                         id = strtoul(optarg, &end, 0);
10368                         if (errno != 0 || *end != '\0' || id == 0 ||
10369                             id > UINT16_MAX) {
10370                                 fprintf(stderr,
10371                                         "%s %s: invalid mirror ID '%s'\n",
10372                                         progname, argv[0], optarg);
10373                                 return rc;
10374                         }
10375
10376                         mirror_id = (__u16)id;
10377                         break;
10378                 }
10379                 case 'o':
10380                         outfile = optarg;
10381                         break;
10382                 default:
10383                         fprintf(stderr, "%s: option '%s' unrecognized.\n",
10384                                 progname, argv[optind - 1]);
10385                         return -EINVAL;
10386                 }
10387         }
10388
10389         if (argc == optind) {
10390                 fprintf(stderr, "%s %s: no mirrored file provided\n",
10391                         progname, argv[0]);
10392                 return rc;
10393         } else if (argc > optind + 1) {
10394                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
10395                 return rc;
10396         }
10397
10398         if (mirror_id == 0) {
10399                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
10400                         progname, argv[0]);
10401                 return rc;
10402         }
10403
10404         /* open mirror file */
10405         fname = argv[optind];
10406         fd = open(fname, O_DIRECT | O_RDONLY);
10407         if (fd < 0) {
10408                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
10409                         progname, argv[0], fname, strerror(errno));
10410                 return rc;
10411         }
10412
10413         /* verify mirror id */
10414         rc = verify_mirror_id_by_fd(fd, mirror_id);
10415         if (rc) {
10416                 fprintf(stderr,
10417                         "%s %s: cannot find mirror with ID %u in '%s'\n",
10418                         progname, argv[0], mirror_id, fname);
10419                 goto close_fd;
10420         }
10421
10422         /* open output file - O_EXCL ensures output is not the same as input */
10423         if (outfile) {
10424                 outfd = open(outfile, O_EXCL | O_WRONLY | O_CREAT, 0644);
10425                 if (outfd < 0) {
10426                         fprintf(stderr, "%s %s: cannot create file '%s': %s\n",
10427                                 progname, argv[0], outfile, strerror(errno));
10428                         rc = -errno;
10429                         goto close_fd;
10430                 }
10431         } else {
10432                 outfd = STDOUT_FILENO;
10433         }
10434
10435         /* allocate buffer */
10436         rc = posix_memalign(&buf, sysconf(_SC_PAGESIZE), buflen);
10437         if (rc) {
10438                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
10439                                 progname, argv[0], rc);
10440                 goto close_outfd;
10441         }
10442
10443         pos = 0;
10444         while (1) {
10445                 ssize_t bytes_read;
10446                 ssize_t written = 0;
10447
10448                 bytes_read = llapi_mirror_read(fd, mirror_id, buf, buflen, pos);
10449                 if (bytes_read < 0) {
10450                         rc = bytes_read;
10451                         fprintf(stderr,
10452                                 "%s %s: fail to read data from mirror %u: %s\n",
10453                                 progname, argv[0], mirror_id, strerror(-rc));
10454                         goto free_buf;
10455                 }
10456
10457                 /* EOF reached */
10458                 if (bytes_read == 0)
10459                         break;
10460
10461                 while (written < bytes_read) {
10462                         ssize_t written2;
10463
10464                         written2 = write(outfd, buf + written,
10465                                          bytes_read - written);
10466                         if (written2 < 0) {
10467                                 fprintf(stderr,
10468                                         "%s %s: fail to write %s: %s\n",
10469                                         progname, argv[0], outfile ? : "STDOUT",
10470                                         strerror(errno));
10471                                 rc = -errno;
10472                                 goto free_buf;
10473                         }
10474                         written += written2;
10475                 }
10476
10477                 if (written != bytes_read) {
10478                         fprintf(stderr,
10479                 "%s %s: written %ld bytes does not match with %ld read.\n",
10480                                 progname, argv[0], written, bytes_read);
10481                         rc = -EIO;
10482                         goto free_buf;
10483                 }
10484
10485                 pos += bytes_read;
10486         }
10487
10488         fsync(outfd);
10489         rc = 0;
10490
10491 free_buf:
10492         free(buf);
10493 close_outfd:
10494         if (outfile)
10495                 close(outfd);
10496 close_fd:
10497         close(fd);
10498
10499         return rc;
10500 }
10501
10502 static inline int lfs_mirror_write(int argc, char **argv)
10503 {
10504         int rc = CMD_HELP;
10505         __u16 mirror_id = 0;
10506         const char *inputfile = NULL;
10507         char *fname;
10508         int fd = 0;
10509         int inputfd;
10510         int c;
10511         void *buf;
10512         const size_t buflen = 4 << 20;
10513         off_t pos;
10514         size_t page_size = sysconf(_SC_PAGESIZE);
10515         struct ll_ioc_lease_id ioc;
10516
10517         struct option long_opts[] = {
10518         { .val = 'N',   .name = "mirror-id",    .has_arg = required_argument },
10519         { .val = 'i',   .name = "inputfile",    .has_arg = required_argument },
10520         { .name = NULL } };
10521
10522         while ((c = getopt_long(argc, argv, "N:i:", long_opts, NULL)) >= 0) {
10523                 char *end;
10524
10525                 switch (c) {
10526                 case 'N': {
10527                         unsigned long int id;
10528
10529                         errno = 0;
10530                         id = strtoul(optarg, &end, 0);
10531                         if (errno != 0 || *end != '\0' || id == 0 ||
10532                             id > UINT16_MAX) {
10533                                 fprintf(stderr,
10534                                         "%s %s: invalid mirror ID '%s'\n",
10535                                         progname, argv[0], optarg);
10536                                 return rc;
10537                         }
10538
10539                         mirror_id = (__u16)id;
10540                         break;
10541                 }
10542                 case 'i':
10543                         inputfile = optarg;
10544                         break;
10545                 default:
10546                         fprintf(stderr, "%s: option '%s' unrecognized\n",
10547                                 progname, argv[optind - 1]);
10548                         return -EINVAL;
10549                 }
10550         }
10551
10552         if (argc == optind) {
10553                 fprintf(stderr, "%s %s: no mirrored file provided\n",
10554                         progname, argv[0]);
10555                 return rc;
10556         } else if (argc > optind + 1) {
10557                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
10558                 return rc;
10559         }
10560
10561         if (mirror_id == 0) {
10562                 fprintf(stderr, "%s %s: no valid mirror ID is provided\n",
10563                         progname, argv[0]);
10564                 return rc;
10565         }
10566
10567         /* open mirror file */
10568         fname = argv[optind];
10569         fd = open(fname, O_DIRECT | O_WRONLY);
10570         if (fd < 0) {
10571                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
10572                         progname, argv[0], fname, strerror(errno));
10573                 return rc;
10574         }
10575
10576         /* verify mirror id */
10577         rc = verify_mirror_id_by_fd(fd, mirror_id);
10578         if (rc) {
10579                 fprintf(stderr,
10580                         "%s %s: cannot find mirror with ID %u in '%s'\n",
10581                         progname, argv[0], mirror_id, fname);
10582                 goto close_fd;
10583         }
10584
10585         /* open input file */
10586         if (inputfile) {
10587                 rc = check_same_file(fd, inputfile);
10588                 if (rc == 0) {
10589                         fprintf(stderr,
10590                         "%s %s: input file cannot be the mirrored file\n",
10591                                 progname, argv[0]);
10592                         goto close_fd;
10593                 }
10594                 if (rc < 0)
10595                         goto close_fd;
10596
10597                 inputfd = open(inputfile, O_RDONLY, 0644);
10598                 if (inputfd < 0) {
10599                         fprintf(stderr, "%s %s: cannot open file '%s': %s\n",
10600                                 progname, argv[0], inputfile, strerror(errno));
10601                         rc = -errno;
10602                         goto close_fd;
10603                 }
10604         } else {
10605                 inputfd = STDIN_FILENO;
10606         }
10607
10608         /* allocate buffer */
10609         rc = posix_memalign(&buf, page_size, buflen);
10610         if (rc) {
10611                 fprintf(stderr, "%s %s: posix_memalign returns %d\n",
10612                         progname, argv[0], rc);
10613                 goto close_inputfd;
10614         }
10615
10616         /* prepare target mirror components instantiation */
10617         ioc.lil_mode = LL_LEASE_WRLCK;
10618         ioc.lil_flags = LL_LEASE_RESYNC;
10619         ioc.lil_mirror_id = mirror_id;
10620         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
10621         if (rc < 0) {
10622                 fprintf(stderr,
10623                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
10624                         progname, argv[0], fname, strerror(errno));
10625                 goto free_buf;
10626         }
10627
10628         pos = 0;
10629         while (1) {
10630                 ssize_t bytes_read;
10631                 ssize_t written;
10632                 size_t to_write;
10633
10634                 rc = llapi_lease_check(fd);
10635                 if (rc != LL_LEASE_WRLCK) {
10636                         fprintf(stderr, "%s %s: '%s' lost lease lock\n",
10637                                 progname, argv[0], fname);
10638                         goto free_buf;
10639                 }
10640
10641                 bytes_read = read(inputfd, buf, buflen);
10642                 if (bytes_read < 0) {
10643                         rc = bytes_read;
10644                         fprintf(stderr,
10645                                 "%s %s: fail to read data from '%s': %s\n",
10646                                 progname, argv[0], inputfile ? : "STDIN",
10647                                 strerror(errno));
10648                         rc = -errno;
10649                         goto free_buf;
10650                 }
10651
10652                 /* EOF reached */
10653                 if (bytes_read == 0)
10654                         break;
10655
10656                 /* round up to page align to make direct IO happy. */
10657                 to_write = (bytes_read + page_size - 1) & ~(page_size - 1);
10658
10659                 written = llapi_mirror_write(fd, mirror_id, buf, to_write,
10660                                              pos);
10661                 if (written < 0) {
10662                         rc = written;
10663                         fprintf(stderr,
10664                               "%s %s: fail to write to mirror %u: %s\n",
10665                                 progname, argv[0], mirror_id,
10666                                 strerror(-rc));
10667                         goto free_buf;
10668                 }
10669
10670                 pos += bytes_read;
10671         }
10672
10673         if (pos & (page_size - 1)) {
10674                 rc = llapi_mirror_truncate(fd, mirror_id, pos);
10675                 if (rc < 0)
10676                         goto free_buf;
10677         }
10678
10679         ioc.lil_mode = LL_LEASE_UNLCK;
10680         ioc.lil_flags = LL_LEASE_RESYNC_DONE;
10681         ioc.lil_count = 0;
10682         rc = llapi_lease_set(fd, (struct ll_ioc_lease *)&ioc);
10683         if (rc <= 0) {
10684                 if (rc == 0)
10685                         rc = -EBUSY;
10686                 fprintf(stderr,
10687                         "%s %s: release lease lock of '%s' failed: %s\n",
10688                         progname, argv[0], fname, strerror(errno));
10689                 goto free_buf;
10690         }
10691
10692         rc = 0;
10693
10694 free_buf:
10695         free(buf);
10696 close_inputfd:
10697         if (inputfile)
10698                 close(inputfd);
10699 close_fd:
10700         close(fd);
10701
10702         return rc;
10703 }
10704
10705 static inline int get_other_mirror_ids(int fd, __u16 *ids, __u16 exclude_id)
10706 {
10707         struct llapi_layout *layout;
10708         struct collect_ids_data cid = { .cid_ids = ids,
10709                                         .cid_count = 0,
10710                                         .cid_exclude = exclude_id, };
10711         int rc;
10712
10713         layout = llapi_layout_get_by_fd(fd, 0);
10714         if (!layout) {
10715                 fprintf(stderr, "could not get layout\n");
10716                 return -EINVAL;
10717         }
10718
10719         rc = llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
10720         if (rc < 0) {
10721                 fprintf(stderr, "failed to iterate layout\n");
10722                 llapi_layout_free(layout);
10723
10724                 return rc;
10725         }
10726         llapi_layout_free(layout);
10727
10728         return cid.cid_count;
10729 }
10730
10731 static inline int lfs_mirror_copy(int argc, char **argv)
10732 {
10733         int rc = CMD_HELP;
10734         __u16 read_mirror_id = 0;
10735         __u16 ids[128] = { 0 };
10736         int count = 0;
10737         struct llapi_layout *layout = NULL;
10738         struct llapi_resync_comp comp_array[1024] = { { 0 } };
10739         int comp_size = 0;
10740         char *fname;
10741         int fd = 0;
10742         int c;
10743         int i;
10744         ssize_t copied;
10745         struct ll_ioc_lease *ioc = NULL;
10746         struct ll_ioc_lease_id *resync_ioc;
10747
10748         struct option long_opts[] = {
10749         { .val = 'i',   .name = "read-mirror",  .has_arg = required_argument },
10750         { .val = 'o',   .name = "write-mirror", .has_arg = required_argument },
10751         { .name = NULL } };
10752
10753         while ((c = getopt_long(argc, argv, "i:o:", long_opts, NULL)) >= 0) {
10754                 char *end;
10755
10756                 switch (c) {
10757                 case 'i': {
10758                         unsigned long int id;
10759
10760                         errno = 0;
10761                         id = strtoul(optarg, &end, 0);
10762                         if (errno != 0 || *end != '\0' || id == 0 ||
10763                             id > UINT16_MAX) {
10764                                 fprintf(stderr,
10765                                         "%s %s: invalid read mirror ID '%s'\n",
10766                                         progname, argv[0], optarg);
10767                                 return rc;
10768                         }
10769
10770                         read_mirror_id = (__u16)id;
10771                         break;
10772                 }
10773                 case 'o':
10774                         if (!strcmp(optarg, "-1")) {
10775                                 /* specify all other mirrors */
10776                                 ids[0] = (__u16)-1;
10777                                 count = 1;
10778                         } else {
10779                                 count = parse_mirror_ids((__u16 *)ids,
10780                                                          ARRAY_SIZE(ids),
10781                                                          optarg);
10782                                 if (count < 0)
10783                                         return rc;
10784                         }
10785                         break;
10786                 default:
10787                         fprintf(stderr, "%s: option '%s' unrecognized\n",
10788                                 progname, argv[optind - 1]);
10789                         return -EINVAL;
10790                 }
10791         }
10792
10793         if (argc == optind) {
10794                 fprintf(stderr, "%s %s: no mirrored file provided\n",
10795                         progname, argv[0]);
10796                 return rc;
10797         } else if (argc > optind + 1) {
10798                 fprintf(stderr, "%s %s: too many files\n", progname, argv[0]);
10799                 return rc;
10800         }
10801
10802         if (read_mirror_id == 0) {
10803                 fprintf(stderr,
10804                         "%s %s: no valid read mirror ID %d is provided\n",
10805                         progname, argv[0], read_mirror_id);
10806                 return rc;
10807         }
10808
10809         if (count == 0) {
10810                 fprintf(stderr,
10811                         "%s %s: no write mirror ID is provided\n",
10812                         progname, argv[0]);
10813                 return rc;
10814         }
10815
10816         for (i = 0; i < count; i++) {
10817                 if (read_mirror_id == ids[i]) {
10818                         fprintf(stderr,
10819                         "%s %s: read and write mirror ID cannot be the same\n",
10820                                 progname, argv[0]);
10821                         return rc;
10822                 }
10823         }
10824
10825         /* open mirror file */
10826         fname = argv[optind];
10827
10828         fd = open(fname, O_DIRECT | O_RDWR);
10829         if (fd < 0) {
10830                 fprintf(stderr, "%s %s: cannot open '%s': %s\n",
10831                         progname, argv[0], fname, strerror(errno));
10832                 return rc;
10833         }
10834
10835         /* write to all other mirrors */
10836         if (ids[0] == (__u16)-1) {
10837                 count = get_other_mirror_ids(fd, ids, read_mirror_id);
10838                 if (count <= 0) {
10839                         rc = count;
10840                         fprintf(stderr,
10841                         "%s %s: failed to get other mirror ids in '%s': %d\n",
10842                                 progname, argv[0], fname, rc);
10843                         goto close_fd;
10844                 }
10845         }
10846
10847         /* verify mirror id */
10848         rc = verify_mirror_id_by_fd(fd, read_mirror_id);
10849         if (rc) {
10850                 fprintf(stderr,
10851                         "%s %s: cannot find mirror with ID %u in '%s'\n",
10852                         progname, argv[0], read_mirror_id, fname);
10853                 goto close_fd;
10854         }
10855
10856         for (i = 0; i < count; i++) {
10857                 rc = verify_mirror_id_by_fd(fd, ids[i]);
10858                 if (rc) {
10859                         fprintf(stderr,
10860                         "%s %s: cannot find mirror with ID %u in '%s'\n",
10861                                 progname, argv[0], ids[i], fname);
10862                         goto close_fd;
10863                 }
10864         }
10865
10866         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
10867         if (!ioc) {
10868                 fprintf(stderr,
10869                         "%s %s: cannot alloc comp id array for ioc: %s\n",
10870                         progname, argv[0], strerror(errno));
10871                 rc = -errno;
10872                 goto close_fd;
10873         }
10874
10875         /* get stale component info */
10876         layout = llapi_layout_get_by_fd(fd, 0);
10877         if (!layout) {
10878                 fprintf(stderr, "%s %s: failed to get layout of '%s': %s\n",
10879                         progname, argv[0], fname, strerror(errno));
10880                 rc = -errno;
10881                 goto free_ioc;
10882         }
10883         comp_size = llapi_mirror_find_stale(layout, comp_array,
10884                                             ARRAY_SIZE(comp_array),
10885                                             ids, count);
10886         llapi_layout_free(layout);
10887         if (comp_size < 0) {
10888                 rc = comp_size;
10889                 goto free_ioc;
10890         }
10891
10892         /* prepare target mirror components instantiation */
10893         resync_ioc = (struct ll_ioc_lease_id *)ioc;
10894         resync_ioc->lil_mode = LL_LEASE_WRLCK;
10895         resync_ioc->lil_flags = LL_LEASE_RESYNC;
10896         if (count == 1)
10897                 resync_ioc->lil_mirror_id = ids[0];
10898         else
10899                 resync_ioc->lil_mirror_id = read_mirror_id | MIRROR_ID_NEG;
10900         rc = llapi_lease_set(fd, ioc);
10901         if (rc < 0) {
10902                 fprintf(stderr,
10903                         "%s %s: '%s' llapi_lease_get_ext failed: %s\n",
10904                         progname, argv[0], fname, strerror(errno));
10905                 goto free_ioc;
10906         }
10907
10908         copied = llapi_mirror_copy_many(fd, read_mirror_id, ids, count);
10909         if (copied < 0) {
10910                 rc = copied;
10911                 fprintf(stderr, "%s %s: copy error: %d\n",
10912                         progname, argv[0], rc);
10913                 goto free_ioc;
10914         }
10915
10916         fprintf(stdout, "mirror copied successfully: ");
10917         for (i = 0; i < copied; i++)
10918                 fprintf(stdout, "%d ", ids[i]);
10919         fprintf(stdout, "\n");
10920
10921         ioc->lil_mode = LL_LEASE_UNLCK;
10922         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
10923         ioc->lil_count = 0;
10924         for (i = 0; i < comp_size; i++) {
10925                 int j;
10926
10927                 for (j = 0; j < copied; j++) {
10928                         if (comp_array[i].lrc_mirror_id != ids[j])
10929                                 continue;
10930
10931                         ioc->lil_ids[ioc->lil_count] = comp_array[i].lrc_id;
10932                         ioc->lil_count++;
10933                 }
10934         }
10935         rc = llapi_lease_set(fd, ioc);
10936         if (rc <= 0) {
10937                 if (rc == 0)
10938                         rc = -EBUSY;
10939                 fprintf(stderr,
10940                         "%s %s: release lease lock of '%s' failed: %s\n",
10941                         progname, argv[0], fname, strerror(errno));
10942                 goto free_ioc;
10943         }
10944
10945         rc = 0;
10946
10947 free_ioc:
10948         free(ioc);
10949 close_fd:
10950         close(fd);
10951
10952         return rc;
10953 }
10954
10955 /**
10956  * struct verify_chunk - Mirror chunk to be verified.
10957  * @chunk:        [start, end) of the chunk.
10958  * @mirror_count: Number of mirror ids in @mirror_id array.
10959  * @mirror_id:    Array of valid mirror ids that cover the chunk.
10960  */
10961 struct verify_chunk {
10962         struct lu_extent chunk;
10963         unsigned int mirror_count;
10964         __u16 mirror_id[LUSTRE_MIRROR_COUNT_MAX];
10965 };
10966
10967 /**
10968  * print_chunks() - Print chunk information.
10969  * @fname:       Mirrored file name.
10970  * @chunks:      Array of chunks.
10971  * @chunk_count: Number of chunks in @chunks array.
10972  *
10973  * This function prints [start, end) of each chunk in @chunks
10974  * for mirrored file @fname, and also prints the valid mirror ids
10975  * that cover the chunk.
10976  *
10977  * Return: void.
10978  */
10979 static inline
10980 void print_chunks(const char *fname, struct verify_chunk *chunks,
10981                   int chunk_count)
10982 {
10983         int i;
10984         int j;
10985
10986         fprintf(stdout, "Chunks to be verified in %s:\n", fname);
10987         for (i = 0; i < chunk_count; i++) {
10988                 fprintf(stdout, DEXT, PEXT(&chunks[i].chunk));
10989
10990                 if (chunks[i].mirror_count == 0)
10991                         fprintf(stdout, "\t[");
10992                 else {
10993                         fprintf(stdout, "\t[%u", chunks[i].mirror_id[0]);
10994                         for (j = 1; j < chunks[i].mirror_count; j++)
10995                                 fprintf(stdout, ", %u", chunks[i].mirror_id[j]);
10996                 }
10997                 fprintf(stdout, "]\t%u\n", chunks[i].mirror_count);
10998         }
10999         fprintf(stdout, "\n");
11000 }
11001
11002 /**
11003  * print_checksums() - Print CRC-32 checksum values.
11004  * @chunk: A chunk and its corresponding valid mirror ids.
11005  * @crc:   CRC-32 checksum values on the chunk for each valid mirror.
11006  *
11007  * This function prints CRC-32 checksum values on @chunk for
11008  * each valid mirror that covers it.
11009  *
11010  * Return: void.
11011  */
11012 static inline
11013 void print_checksums(struct verify_chunk *chunk, unsigned long *crc)
11014 {
11015         int i;
11016
11017         fprintf(stdout,
11018                 "CRC-32 checksum value for chunk "DEXT":\n",
11019                 PEXT(&chunk->chunk));
11020         for (i = 0; i < chunk->mirror_count; i++)
11021                 fprintf(stdout, "Mirror %u:\t%#lx\n",
11022                         chunk->mirror_id[i], crc[i]);
11023         fprintf(stdout, "\n");
11024 }
11025
11026 /**
11027  * filter_mirror_id() - Filter specified mirror ids.
11028  * @chunks:      Array of chunks.
11029  * @chunk_count: Number of chunks in @chunks array.
11030  * @mirror_ids:  Specified mirror ids to be verified.
11031  * @ids_nr:      Number of specified mirror ids.
11032  *
11033  * This function scans valid mirror ids that cover each chunk in @chunks
11034  * and filters specified mirror ids.
11035  *
11036  * Return: void.
11037  */
11038 static inline
11039 void filter_mirror_id(struct verify_chunk *chunks, int chunk_count,
11040                       __u16 *mirror_ids, int ids_nr)
11041 {
11042         int i;
11043         int j;
11044         int k;
11045         __u16 valid_id[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
11046         unsigned int valid_count = 0;
11047
11048         for (i = 0; i < chunk_count; i++) {
11049                 if (chunks[i].mirror_count == 0)
11050                         continue;
11051
11052                 valid_count = 0;
11053                 for (j = 0; j < ids_nr; j++) {
11054                         for (k = 0; k < chunks[i].mirror_count; k++) {
11055                                 if (chunks[i].mirror_id[k] == mirror_ids[j]) {
11056                                         valid_id[valid_count] = mirror_ids[j];
11057                                         valid_count++;
11058                                         break;
11059                                 }
11060                         }
11061                 }
11062
11063                 memcpy(chunks[i].mirror_id, valid_id,
11064                        sizeof(__u16) * valid_count);
11065                 chunks[i].mirror_count = valid_count;
11066         }
11067 }
11068
11069 /**
11070  * lfs_mirror_prepare_chunk() - Find mirror chunks to be verified.
11071  * @layout:      Mirror component list.
11072  * @chunks:      Array of chunks.
11073  * @chunks_size: Array size of @chunks.
11074  *
11075  * This function scans the components in @layout from offset 0 to LUSTRE_EOF
11076  * to find out chunk segments and store them in @chunks array.
11077  *
11078  * The @mirror_id array in each element of @chunks will store the valid
11079  * mirror ids that cover the chunk. If a mirror component covering the
11080  * chunk has LCME_FL_STALE or LCME_FL_OFFLINE flag, then the mirror id
11081  * will not be stored into the @mirror_id array, and the chunk for that
11082  * mirror will not be verified.
11083  *
11084  * The @mirror_count in each element of @chunks will store the number of
11085  * mirror ids in @mirror_id array. If @mirror_count is 0, it indicates the
11086  * chunk is invalid in all of the mirrors. And if @mirror_count is 1, it
11087  * indicates the chunk is valid in only one mirror. In both cases, the
11088  * chunk will not be verified.
11089  *
11090  * Here is an example:
11091  *
11092  *  0      1M     2M     3M     4M           EOF
11093  *  +------+-------------+--------------------+
11094  *  |      |             |      S             |       mirror1
11095  *  +------+------+------+------+-------------+
11096  *  |             |   S  |   S  |             |       mirror2
11097  *  +-------------+------+------+-------------+
11098  *
11099  * prepared @chunks array will contain 5 elements:
11100  * (([0, 1M), [1, 2], 2),
11101  *  ([1M, 2M), [1, 2], 2),
11102  *  ([2M, 3M), [1], 1),
11103  *  ([3M, 4M], [], 0),
11104  *  ([4M, EOF), [2], 1))
11105  *
11106  * Return: the actual array size of @chunks on success
11107  *         or a negative error code on failure.
11108  */
11109 static inline
11110 int lfs_mirror_prepare_chunk(struct llapi_layout *layout,
11111                              struct verify_chunk *chunks,
11112                              size_t chunks_size)
11113 {
11114         uint64_t start;
11115         uint64_t end;
11116         uint32_t mirror_id;
11117         uint32_t flags;
11118         int idx = 0;
11119         int i = 0;
11120         int rc = 0;
11121
11122         memset(chunks, 0, sizeof(*chunks) * chunks_size);
11123
11124         while (1) {
11125                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
11126                 if (rc < 0) {
11127                         fprintf(stderr,
11128                                 "%s: move to the first layout component: %s.\n",
11129                                 progname, strerror(errno));
11130                         goto error;
11131                 }
11132
11133                 i = 0;
11134                 rc = 0;
11135                 chunks[idx].chunk.e_end = LUSTRE_EOF;
11136                 while (rc == 0) {
11137                         rc = llapi_layout_comp_extent_get(layout, &start, &end);
11138                         if (rc < 0) {
11139                                 fprintf(stderr,
11140                                         "%s: llapi_layout_comp_extent_get failed: %s.\n",
11141                                         progname, strerror(errno));
11142                                 goto error;
11143                         }
11144
11145                         if (start > chunks[idx].chunk.e_start ||
11146                             end <= chunks[idx].chunk.e_start)
11147                                 goto next;
11148
11149                         if (end < chunks[idx].chunk.e_end)
11150                                 chunks[idx].chunk.e_end = end;
11151
11152                         rc = llapi_layout_comp_flags_get(layout, &flags);
11153                         if (rc < 0) {
11154                                 fprintf(stderr,
11155                                         "%s: llapi_layout_comp_flags_get failed: %s.\n",
11156                                         progname, strerror(errno));
11157                                 goto error;
11158                         }
11159
11160                         if (flags & LCME_FL_STALE || flags & LCME_FL_OFFLINE)
11161                                 goto next;
11162
11163                         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
11164                         if (rc < 0) {
11165                                 fprintf(stderr,
11166                                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
11167                                         progname, strerror(errno));
11168                                 goto error;
11169                         }
11170
11171                         chunks[idx].mirror_id[i] = mirror_id;
11172                         i++;
11173                         if (i >= ARRAY_SIZE(chunks[idx].mirror_id)) {
11174                                 fprintf(stderr,
11175                                         "%s: mirror_id array is too small.\n",
11176                                         progname);
11177                                 rc = -EINVAL;
11178                                 goto error;
11179                         }
11180
11181 next:
11182                         rc = llapi_layout_comp_use(layout,
11183                                                    LLAPI_LAYOUT_COMP_USE_NEXT);
11184                         if (rc < 0) {
11185                                 fprintf(stderr,
11186                                         "%s: move to the next layout component: %s.\n",
11187                                         progname, strerror(errno));
11188                                 goto error;
11189                         }
11190                 } /* loop through all components */
11191
11192                 chunks[idx].mirror_count = i;
11193
11194                 if (chunks[idx].chunk.e_end == LUSTRE_EOF)
11195                         break;
11196
11197                 idx++;
11198                 if (idx >= chunks_size) {
11199                         fprintf(stderr, "%s: chunks array is too small.\n",
11200                                 progname);
11201                         rc = -EINVAL;
11202                         goto error;
11203                 }
11204
11205                 chunks[idx].chunk.e_start = chunks[idx - 1].chunk.e_end;
11206         }
11207
11208 error:
11209         return rc < 0 ? rc : idx + 1;
11210 }
11211
11212 /**
11213  * lfs_mirror_verify_chunk() - Verify a chunk.
11214  * @fd:        File descriptor of the mirrored file.
11215  * @file_size: Size of the mirrored file.
11216  * @chunk:     A chunk and its corresponding valid mirror ids.
11217  * @verbose:   Verbose mode.
11218  *
11219  * This function verifies a @chunk contains exactly the same data
11220  * ammong the mirrors that cover it.
11221  *
11222  * If @verbose is specified, then the function will print where the
11223  * differences are if the data do not match. Otherwise, it will
11224  * just return an error in that case.
11225  *
11226  * Return: 0 on success or a negative error code on failure.
11227  */
11228 static inline
11229 int lfs_mirror_verify_chunk(int fd, size_t file_size,
11230                             struct verify_chunk *chunk, int verbose)
11231 {
11232         const size_t buflen = 4 * 1024 * 1024; /* 4M */
11233         void *buf;
11234         size_t page_size = sysconf(_SC_PAGESIZE);
11235         ssize_t bytes_read;
11236         ssize_t bytes_done;
11237         size_t count;
11238         off_t pos;
11239         unsigned long crc;
11240         unsigned long crc_array[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
11241         int i;
11242         int rc = 0;
11243
11244         if (file_size == 0)
11245                 return 0;
11246
11247         rc = posix_memalign(&buf, page_size, buflen);
11248         if (rc) /* error code is returned directly */
11249                 return -rc;
11250
11251         if (verbose > 1) {
11252                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
11253                         PEXT(&chunk->chunk));
11254                 for (i = 0; i < chunk->mirror_count; i++)
11255                         fprintf(stdout, " %u", chunk->mirror_id[i]);
11256                 fprintf(stdout, "\n");
11257         }
11258
11259         bytes_done = 0;
11260         count = MIN(chunk->chunk.e_end, file_size) - chunk->chunk.e_start;
11261         pos = chunk->chunk.e_start;
11262         while (bytes_done < count) {
11263                 /* compute initial CRC-32 checksum */
11264                 crc = crc32(0L, Z_NULL, 0);
11265                 memset(crc_array, 0, sizeof(crc_array));
11266
11267                 bytes_read = 0;
11268                 for (i = 0; i < chunk->mirror_count; i++) {
11269                         bytes_read = llapi_mirror_read(fd, chunk->mirror_id[i],
11270                                                        buf, buflen, pos);
11271                         if (bytes_read < 0) {
11272                                 rc = bytes_read;
11273                                 fprintf(stderr,
11274                                         "%s: failed to read data from mirror %u: %s.\n",
11275                                         progname, chunk->mirror_id[i],
11276                                         strerror(-rc));
11277                                 goto error;
11278                         }
11279
11280                         /* compute new CRC-32 checksum */
11281                         crc_array[i] = crc32(crc, buf, bytes_read);
11282                 }
11283
11284                 if (verbose)
11285                         print_checksums(chunk, crc_array);
11286
11287                 /* compare CRC-32 checksum values */
11288                 for (i = 1; i < chunk->mirror_count; i++) {
11289                         if (crc_array[i] != crc_array[0]) {
11290                                 rc = -EINVAL;
11291
11292                                 fprintf(stderr,
11293                                         "%s: chunk "DEXT" has different checksum value on mirror %u and mirror %u.\n",
11294                                         progname, PEXT(&chunk->chunk),
11295                                         chunk->mirror_id[0],
11296                                         chunk->mirror_id[i]);
11297                         }
11298                 }
11299
11300                 pos += bytes_read;
11301                 bytes_done += bytes_read;
11302         }
11303
11304         if (verbose > 1 && rc == 0) {
11305                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
11306                         PEXT(&chunk->chunk));
11307                 for (i = 0; i < chunk->mirror_count; i++)
11308                         fprintf(stdout, " %u", chunk->mirror_id[i]);
11309                 fprintf(stdout, " PASS\n\n");
11310         }
11311
11312 error:
11313         free(buf);
11314         return rc;
11315 }
11316
11317 /**
11318  * lfs_mirror_verify_file() - Verify a mirrored file.
11319  * @fname:      Mirrored file name.
11320  * @mirror_ids: Specified mirror ids to be verified.
11321  * @ids_nr:     Number of specified mirror ids.
11322  * @verbose:    Verbose mode.
11323  *
11324  * This function verifies that each SYNC mirror of a mirrored file
11325  * specified by @fname contains exactly the same data.
11326  *
11327  * If @mirror_ids is specified, then the function will verify the
11328  * mirrors specified by @mirror_ids contain exactly the same data.
11329  *
11330  * If @verbose is specified, then the function will print where the
11331  * differences are if the data do not match. Otherwise, it will
11332  * just return an error in that case.
11333  *
11334  * Return: 0 on success or a negative error code on failure.
11335  */
11336 static inline
11337 int lfs_mirror_verify_file(const char *fname, __u16 *mirror_ids, int ids_nr,
11338                            int verbose)
11339 {
11340         struct verify_chunk chunks_array[1024] = { };
11341         struct llapi_layout *layout = NULL;
11342         struct stat stbuf;
11343         uint32_t flr_state;
11344         int fd;
11345         int chunk_count = 0;
11346         int idx = 0;
11347         int rc = 0;
11348         int rc1 = 0;
11349         int rc2 = 0;
11350
11351         if (stat(fname, &stbuf) < 0) {
11352                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
11353                         progname, fname, strerror(errno));
11354                 rc = -errno;
11355                 goto error;
11356         }
11357
11358         if (!S_ISREG(stbuf.st_mode)) {
11359                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
11360                         progname, fname);
11361                 rc = -EINVAL;
11362                 goto error;
11363         }
11364
11365         if (stbuf.st_size == 0) {
11366                 if (verbose)
11367                         fprintf(stdout, "%s: '%s' file size is 0.\n",
11368                                 progname, fname);
11369                 rc = 0;
11370                 goto error;
11371         }
11372
11373         fd = open(fname, O_DIRECT | O_RDONLY);
11374         if (fd < 0) {
11375                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
11376                         progname, fname, strerror(errno));
11377                 rc = -errno;
11378                 goto error;
11379         }
11380
11381         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
11382         if (rc < 0) {
11383                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
11384                         progname, fname, strerror(errno));
11385                 goto close_fd;
11386         }
11387
11388         layout = llapi_layout_get_by_fd(fd, 0);
11389         if (!layout) {
11390                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
11391                         progname, fname, strerror(errno));
11392                 rc = -errno;
11393                 llapi_lease_release(fd);
11394                 goto close_fd;
11395         }
11396
11397         rc = llapi_layout_flags_get(layout, &flr_state);
11398         if (rc < 0) {
11399                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
11400                         progname, fname, strerror(errno));
11401                 rc = -errno;
11402                 goto free_layout;
11403         }
11404
11405         flr_state &= LCM_FL_FLR_MASK;
11406         switch (flr_state) {
11407         case LCM_FL_NONE:
11408                 rc = -EINVAL;
11409                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
11410                         progname, fname, llapi_layout_flags_string(flr_state));
11411                 goto free_layout;
11412         default:
11413                 break;
11414         }
11415
11416         /* find out mirror chunks to be verified */
11417         chunk_count = lfs_mirror_prepare_chunk(layout, chunks_array,
11418                                                ARRAY_SIZE(chunks_array));
11419         if (chunk_count < 0) {
11420                 rc = chunk_count;
11421                 goto free_layout;
11422         }
11423
11424         if (ids_nr > 0)
11425                 /* filter specified mirror ids */
11426                 filter_mirror_id(chunks_array, chunk_count, mirror_ids, ids_nr);
11427
11428         if (verbose > 2)
11429                 print_chunks(fname, chunks_array, chunk_count);
11430
11431         for (idx = 0; idx < chunk_count; idx++) {
11432                 if (chunks_array[idx].chunk.e_start >= stbuf.st_size) {
11433                         if (verbose)
11434                                 fprintf(stdout,
11435                                         "%s: '%s' chunk "DEXT" exceeds file size %#llx: skipped\n",
11436                                         progname, fname,
11437                                         PEXT(&chunks_array[idx].chunk),
11438                                         (unsigned long long)stbuf.st_size);
11439                         break;
11440                 }
11441
11442                 if (chunks_array[idx].mirror_count == 0) {
11443                         fprintf(stderr,
11444                                 "%s: '%s' chunk "DEXT" is invalid in all of the mirrors: ",
11445                                 progname, fname,
11446                                 PEXT(&chunks_array[idx].chunk));
11447                         if (verbose) {
11448                                 fprintf(stderr, "skipped\n");
11449                                 continue;
11450                         }
11451                         rc = -EINVAL;
11452                         fprintf(stderr, "failed\n");
11453                         goto free_layout;
11454                 }
11455
11456                 if (chunks_array[idx].mirror_count == 1) {
11457                         if (verbose)
11458                                 fprintf(stdout,
11459                                         "%s: '%s' chunk "DEXT" is only valid in mirror %u: skipped\n",
11460                                         progname, fname,
11461                                         PEXT(&chunks_array[idx].chunk),
11462                                         chunks_array[idx].mirror_id[0]);
11463                         continue;
11464                 }
11465
11466                 rc = llapi_lease_check(fd);
11467                 if (rc != LL_LEASE_RDLCK) {
11468                         fprintf(stderr, "%s: '%s' lost lease lock.\n",
11469                                 progname, fname);
11470                         goto free_layout;
11471                 }
11472
11473                 /* verify one chunk */
11474                 rc1 = lfs_mirror_verify_chunk(fd, stbuf.st_size,
11475                                               &chunks_array[idx], verbose);
11476                 if (rc1 < 0) {
11477                         rc2 = rc1;
11478                         if (!verbose) {
11479                                 rc = rc1;
11480                                 goto free_layout;
11481                         }
11482                 }
11483         }
11484
11485         if (rc2 < 0)
11486                 rc = rc2;
11487
11488 free_layout:
11489         llapi_layout_free(layout);
11490         llapi_lease_release(fd);
11491 close_fd:
11492         close(fd);
11493 error:
11494         return rc;
11495 }
11496
11497 /**
11498  * lfs_mirror_verify() - Parse and execute lfs mirror verify command.
11499  * @argc: The count of lfs mirror verify command line arguments.
11500  * @argv: Array of strings for lfs mirror verify command line arguments.
11501  *
11502  * This function parses lfs mirror verify command and verifies the
11503  * specified mirrored file(s).
11504  *
11505  * Return: 0 on success or a negative error code on failure.
11506  */
11507 static inline int lfs_mirror_verify(int argc, char **argv)
11508 {
11509         __u16 mirror_ids[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
11510         int ids_nr = 0;
11511         int c;
11512         int verbose = 0;
11513         int rc = 0;
11514         int rc1 = 0;
11515         char cmd[PATH_MAX];
11516
11517         struct option long_opts[] = {
11518         { .val = 'o',   .name = "only",         .has_arg = required_argument },
11519         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
11520         { .name = NULL } };
11521
11522         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
11523         progname = cmd;
11524         while ((c = getopt_long(argc, argv, "o:v", long_opts, NULL)) >= 0) {
11525                 switch (c) {
11526                 case 'o':
11527                         rc = parse_mirror_ids(mirror_ids,
11528                                               ARRAY_SIZE(mirror_ids),
11529                                               optarg);
11530                         if (rc < 0) {
11531                                 fprintf(stderr,
11532                                         "%s: bad mirror ids '%s'.\n",
11533                                         progname, optarg);
11534                                 goto error;
11535                         }
11536                         ids_nr = rc;
11537                         if (ids_nr < 2) {
11538                                 fprintf(stderr,
11539                                         "%s: at least 2 mirror ids needed with '--only' option.\n",
11540                                         progname);
11541                                 rc = CMD_HELP;
11542                                 goto error;
11543                         }
11544                         break;
11545                 case 'v':
11546                         verbose++;
11547                         break;
11548                 default:
11549                         fprintf(stderr, "%s: option '%s' unrecognized.\n",
11550                                 progname, argv[optind - 1]);
11551                         rc = -EINVAL;
11552                         goto error;
11553                 }
11554         }
11555
11556         if (argc == optind) {
11557                 fprintf(stderr, "%s: no file name given.\n", progname);
11558                 rc = CMD_HELP;
11559                 goto error;
11560         }
11561
11562         if (ids_nr > 0 && argc > optind + 1) {
11563                 fprintf(stderr,
11564                         "%s: '--only' cannot be used upon multiple files.\n",
11565                         progname);
11566                 rc = CMD_HELP;
11567                 goto error;
11568         }
11569
11570         if (ids_nr > 0) {
11571                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
11572                 if (rc < 0)
11573                         goto error;
11574         }
11575
11576         rc = 0;
11577         for (; optind < argc; optind++) {
11578                 rc1 = lfs_mirror_verify_file(argv[optind], mirror_ids, ids_nr,
11579                                              verbose);
11580                 if (rc1 < 0)
11581                         rc = rc1;
11582         }
11583 error:
11584         return rc;
11585 }
11586
11587 /**
11588  * lfs_mirror() - Parse and execute lfs mirror commands.
11589  * @argc: The count of lfs mirror command line arguments.
11590  * @argv: Array of strings for lfs mirror command line arguments.
11591  *
11592  * This function parses lfs mirror commands and performs the
11593  * corresponding functions specified in mirror_cmdlist[].
11594  *
11595  * Return: 0 on success or an error code on failure.
11596  */
11597 static int lfs_mirror(int argc, char **argv)
11598 {
11599         char cmd[PATH_MAX];
11600         int rc = 0;
11601
11602         setlinebuf(stdout);
11603
11604         Parser_init("lfs-mirror > ", mirror_cmdlist);
11605
11606         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
11607         progname = cmd;
11608         program_invocation_short_name = cmd;
11609         if (argc > 1)
11610                 rc = Parser_execarg(argc - 1, argv + 1, mirror_cmdlist);
11611         else
11612                 rc = Parser_commands();
11613
11614         return rc < 0 ? -rc : rc;
11615 }
11616
11617 static void lustre_som_swab(struct lustre_som_attrs *attrs)
11618 {
11619 #if __BYTE_ORDER == __BIG_ENDIAN
11620         __swab16s(&attrs->lsa_valid);
11621         __swab64s(&attrs->lsa_size);
11622         __swab64s(&attrs->lsa_blocks);
11623 #endif
11624 }
11625
11626 enum lfs_som_type {
11627         LFS_SOM_SIZE = 0x1,
11628         LFS_SOM_BLOCKS = 0x2,
11629         LFS_SOM_FLAGS = 0x4,
11630         LFS_SOM_ATTR_ALL = LFS_SOM_SIZE | LFS_SOM_BLOCKS |
11631                            LFS_SOM_FLAGS,
11632 };
11633
11634 static int lfs_getsom(int argc, char **argv)
11635 {
11636         const char *path;
11637         struct lustre_som_attrs *attrs;
11638         char buf[sizeof(*attrs) + 64];
11639         enum lfs_som_type type = LFS_SOM_ATTR_ALL;
11640         int rc = 0, c;
11641
11642         while ((c = getopt(argc, argv, "sbf")) != -1) {
11643                 switch (c) {
11644                 case 's':
11645                         type = LFS_SOM_SIZE;
11646                         break;
11647                 case 'b':
11648                         type = LFS_SOM_BLOCKS;
11649                         break;
11650                 case 'f':
11651                         type = LFS_SOM_FLAGS;
11652                         break;
11653                 default:
11654                         fprintf(stderr, "%s: invalid option '%c'\n",
11655                                 progname, optopt);
11656                         return CMD_HELP;
11657                 }
11658         }
11659
11660         argc -= optind;
11661         argv += optind;
11662
11663         if (argc != 1) {
11664                 fprintf(stderr, "%s: %s\n",
11665                         progname, argc == 0 ? "miss file target" :
11666                         "input more than 2 files");
11667                 return CMD_HELP;
11668         }
11669
11670         path = argv[0];
11671         attrs = (void *)buf;
11672         rc = lgetxattr(path, "trusted.som", attrs, sizeof(buf));
11673         if (rc < 0) {
11674                 rc = -errno;
11675                 fprintf(stderr, "%s failed to get som xattr: %s (%d)\n",
11676                         argv[0], strerror(errno), errno);
11677                 return rc;
11678         }
11679
11680         lustre_som_swab(attrs);
11681
11682         switch (type) {
11683         case LFS_SOM_ATTR_ALL:
11684                 printf("file: %s size: %llu blocks: %llu flags: %x\n",
11685                        path, (unsigned long long)attrs->lsa_size,
11686                        (unsigned long long)attrs->lsa_blocks,
11687                        attrs->lsa_valid);
11688                 break;
11689         case LFS_SOM_SIZE:
11690                 printf("%llu\n", (unsigned long long)attrs->lsa_size);
11691                 break;
11692         case LFS_SOM_BLOCKS:
11693                 printf("%llu\n", (unsigned long long)attrs->lsa_blocks);
11694                 break;
11695         case LFS_SOM_FLAGS:
11696                 printf("%x\n", attrs->lsa_valid);
11697                 break;
11698         default:
11699                 fprintf(stderr, "%s: unknown option\n", progname);
11700                 return CMD_HELP;
11701         }
11702
11703         return 0;
11704 }
11705
11706 /**
11707  * lfs_mirror_list_commands() - List lfs mirror commands.
11708  * @argc: The count of command line arguments.
11709  * @argv: Array of strings for command line arguments.
11710  *
11711  * This function lists lfs mirror commands defined in mirror_cmdlist[].
11712  *
11713  * Return: 0 on success.
11714  */
11715 static int lfs_mirror_list_commands(int argc, char **argv)
11716 {
11717         char buffer[81] = "";
11718
11719         Parser_list_commands(mirror_cmdlist, buffer, sizeof(buffer),
11720                              NULL, 0, 4);
11721
11722         return 0;
11723 }
11724
11725 static int lfs_pcc_attach(int argc, char **argv)
11726 {
11727         struct option long_opts[] = {
11728         { .val = 'i',   .name = "id",   .has_arg = required_argument },
11729         { .name = NULL } };
11730         int c;
11731         int rc = 0;
11732         __u32 archive_id = 0;
11733         const char *path;
11734         char *end;
11735         char fullpath[PATH_MAX];
11736         enum lu_pcc_type type = LU_PCC_READWRITE;
11737
11738         optind = 0;
11739         while ((c = getopt_long(argc, argv, "i:",
11740                                 long_opts, NULL)) != -1) {
11741                 switch (c) {
11742                 case 'i':
11743                         errno = 0;
11744                         archive_id = strtoul(optarg, &end, 0);
11745                         if (errno != 0 || *end != '\0' ||
11746                             archive_id == 0 || archive_id > UINT32_MAX) {
11747                                 fprintf(stderr,
11748                                         "error: %s: bad archive ID '%s'\n",
11749                                         argv[0], optarg);
11750                                 return CMD_HELP;
11751                         }
11752                         break;
11753                 case '?':
11754                         return CMD_HELP;
11755                 default:
11756                         fprintf(stderr, "%s: option '%s' unrecognized\n",
11757                                 argv[0], argv[optind - 1]);
11758                         return CMD_HELP;
11759                 }
11760         }
11761
11762         if (archive_id == 0) {
11763                 fprintf(stderr, "%s: must specify attach ID\n", argv[0]);
11764                 return CMD_HELP;
11765         }
11766
11767         if (argc <= optind) {
11768                 fprintf(stderr, "%s: must specify one or more file names\n",
11769                         argv[0]);
11770                 return CMD_HELP;
11771         }
11772
11773         while (optind < argc) {
11774                 int rc2;
11775
11776                 path = argv[optind++];
11777                 if (!realpath(path, fullpath)) {
11778                         fprintf(stderr, "%s: could not find path '%s': %s\n",
11779                                 argv[0], path, strerror(errno));
11780                         if (rc == 0)
11781                                 rc = -EINVAL;
11782                         continue;
11783                 }
11784
11785                 rc2 = llapi_pcc_attach(fullpath, archive_id, type);
11786                 if (rc2 < 0) {
11787                         fprintf(stderr,
11788                                 "%s: cannot attach '%s' to PCC with archive ID '%u': %s\n",
11789                                 argv[0], path, archive_id, strerror(-rc2));
11790                         if (rc == 0)
11791                                 rc = rc2;
11792                 }
11793         }
11794         return rc;
11795 }
11796
11797 static int lfs_pcc_attach_fid(int argc, char **argv)
11798 {
11799         struct option long_opts[] = {
11800         { .val = 'i',   .name = "id",   .has_arg = required_argument },
11801         { .val = 'm',   .name = "mnt",  .has_arg = required_argument },
11802         { .name = NULL } };
11803         char                     short_opts[] = "i:m:";
11804         int                      c;
11805         int                      rc = 0;
11806         __u32                    archive_id = 0;
11807         char                    *end;
11808         const char              *mntpath = NULL;
11809         const char              *fidstr;
11810         enum lu_pcc_type         type = LU_PCC_READWRITE;
11811
11812         optind = 0;
11813         while ((c = getopt_long(argc, argv, short_opts,
11814                                 long_opts, NULL)) != -1) {
11815                 switch (c) {
11816                 case 'i':
11817                         errno = 0;
11818                         archive_id = strtoul(optarg, &end, 0);
11819                         if (errno != 0 || *end != '\0' ||
11820                             archive_id > UINT32_MAX) {
11821                                 fprintf(stderr,
11822                                         "error: %s: bad archive ID '%s'\n",
11823                                         argv[0], optarg);
11824                                 return CMD_HELP;
11825                         }
11826                         break;
11827                 case 'm':
11828                         mntpath = optarg;
11829                         break;
11830                 case '?':
11831                         return CMD_HELP;
11832                 default:
11833                         fprintf(stderr, "%s: option '%s' unrecognized\n",
11834                                 argv[0], argv[optind - 1]);
11835                         return CMD_HELP;
11836                 }
11837         }
11838
11839         if (archive_id == 0) {
11840                 fprintf(stderr, "%s: must specify an archive ID\n", argv[0]);
11841                 return CMD_HELP;
11842         }
11843
11844         if (!mntpath) {
11845                 fprintf(stderr, "%s: must specify Lustre mount point\n",
11846                         argv[0]);
11847                 return CMD_HELP;
11848         }
11849
11850         if (argc <= optind) {
11851                 fprintf(stderr, "%s: must specify one or more fids\n", argv[0]);
11852                 return CMD_HELP;
11853         }
11854
11855         while (optind < argc) {
11856                 int rc2;
11857
11858                 fidstr = argv[optind++];
11859
11860                 rc2 = llapi_pcc_attach_fid_str(mntpath, fidstr,
11861                                                archive_id, type);
11862                 if (rc2 < 0) {
11863                         fprintf(stderr,
11864                                 "%s: cannot attach '%s' on '%s' to PCC with archive ID '%u': %s\n",
11865                                 argv[0], fidstr, mntpath, archive_id,
11866                                 strerror(rc2));
11867                 }
11868                 if (rc == 0 && rc2 < 0)
11869                         rc = rc2;
11870         }
11871         return rc;
11872 }
11873
11874 static int lfs_pcc_detach(int argc, char **argv)
11875 {
11876         struct option long_opts[] = {
11877         { .val = 'k',   .name = "keep", .has_arg = no_argument },
11878         { .name = NULL } };
11879         char                     short_opts[] = "k";
11880         int                      c;
11881         int                      rc = 0;
11882         const char              *path;
11883         char                     fullpath[PATH_MAX];
11884         __u32                    detach_opt = PCC_DETACH_OPT_UNCACHE;
11885
11886         optind = 0;
11887         while ((c = getopt_long(argc, argv, short_opts,
11888                                 long_opts, NULL)) != -1) {
11889                 switch (c) {
11890                 case 'k':
11891                         detach_opt = PCC_DETACH_OPT_NONE;
11892                         break;
11893                 case '?':
11894                         return CMD_HELP;
11895                 default:
11896                         fprintf(stderr, "%s: option '%s' unrecognized\n",
11897                                 argv[0], argv[optind - 1]);
11898                         return CMD_HELP;
11899                 }
11900         }
11901
11902         while (optind < argc) {
11903                 int rc2;
11904
11905                 path = argv[optind++];
11906                 if (!realpath(path, fullpath)) {
11907                         fprintf(stderr, "%s: could not find path '%s': %s\n",
11908                                 argv[0], path, strerror(errno));
11909                         if (rc == 0)
11910                                 rc = -EINVAL;
11911                         continue;
11912                 }
11913
11914                 rc2 = llapi_pcc_detach_file(fullpath, detach_opt);
11915                 if (rc2 < 0) {
11916                         rc2 = -errno;
11917                         fprintf(stderr,
11918                                 "%s: cannot detach '%s' from PCC: %s\n",
11919                                 argv[0], path, strerror(errno));
11920                         if (rc == 0)
11921                                 rc = rc2;
11922                 }
11923         }
11924         return rc;
11925 }
11926
11927 static int lfs_pcc_detach_fid(int argc, char **argv)
11928 {
11929         struct option long_opts[] = {
11930         { .val = 'k',   .name = "keep", .has_arg = no_argument },
11931         { .name = NULL } };
11932         char             short_opts[] = "k";
11933         int              c;
11934         int              rc = 0;
11935         const char      *fid;
11936         const char      *mntpath;
11937         __u32            detach_opt = PCC_DETACH_OPT_UNCACHE;
11938
11939         optind = 0;
11940         while ((c = getopt_long(argc, argv, short_opts,
11941                                 long_opts, NULL)) != -1) {
11942                 switch (c) {
11943                 case 'k':
11944                         detach_opt = PCC_DETACH_OPT_NONE;
11945                         break;
11946                 case '?':
11947                         return CMD_HELP;
11948                 default:
11949                         fprintf(stderr, "%s: option '%s' unrecognized\n",
11950                                 argv[0], argv[optind - 1]);
11951                         return CMD_HELP;
11952                 }
11953         }
11954
11955         mntpath = argv[optind++];
11956
11957         while (optind < argc) {
11958                 int rc2;
11959
11960                 fid = argv[optind++];
11961
11962                 rc2 = llapi_pcc_detach_fid_str(mntpath, fid, detach_opt);
11963                 if (rc2 < 0) {
11964                         fprintf(stderr,
11965                                 "%s: cannot detach '%s' on '%s' from PCC: %s\n",
11966                                 argv[0], fid, mntpath, strerror(-rc2));
11967                         if (rc == 0)
11968                                 rc = rc2;
11969                 }
11970         }
11971         return rc;
11972 }
11973
11974 static int lfs_pcc_state(int argc, char **argv)
11975 {
11976         int                      rc = 0;
11977         const char              *path;
11978         char                     fullpath[PATH_MAX];
11979         struct lu_pcc_state      state;
11980
11981         optind = 1;
11982
11983         if (argc <= 1) {
11984                 fprintf(stderr, "%s: must specify one or more file names\n",
11985                         argv[0]);
11986                 return CMD_HELP;
11987         }
11988
11989         while (optind < argc) {
11990                 int rc2;
11991
11992                 path = argv[optind++];
11993                 if (!realpath(path, fullpath)) {
11994                         fprintf(stderr, "%s: could not find path '%s': %s\n",
11995                                 argv[0], path, strerror(errno));
11996                         if (rc == 0)
11997                                 rc = -EINVAL;
11998                         continue;
11999                 }
12000
12001                 rc2 = llapi_pcc_state_get(fullpath, &state);
12002                 if (rc2 < 0) {
12003                         if (rc == 0)
12004                                 rc = rc2;
12005                         fprintf(stderr,
12006                                 "%s: cannot get PCC state of '%s': %s\n",
12007                                 argv[0], path, strerror(-rc2));
12008                         continue;
12009                 }
12010
12011                 printf("file: %s", path);
12012                 printf(", type: %s", pcc_type2string(state.pccs_type));
12013                 if (state.pccs_type == LU_PCC_NONE &&
12014                     state.pccs_open_count == 0) {
12015                         printf("\n");
12016                         continue;
12017                 }
12018
12019                 printf(", PCC file: %s", state.pccs_path);
12020                 printf(", user number: %u", state.pccs_open_count);
12021                 printf(", flags: %x", state.pccs_flags);
12022                 printf("\n");
12023         }
12024         return rc;
12025 }
12026
12027 /**
12028  * lfs_pcc_list_commands() - List lfs pcc commands.
12029  * @argc: The count of command line arguments.
12030  * @argv: Array of strings for command line arguments.
12031  *
12032  * This function lists lfs pcc commands defined in pcc_cmdlist[].
12033  *
12034  * Return: 0 on success.
12035  */
12036 static int lfs_pcc_list_commands(int argc, char **argv)
12037 {
12038         char buffer[81] = "";
12039
12040         Parser_list_commands(pcc_cmdlist, buffer, sizeof(buffer),
12041                              NULL, 0, 4);
12042
12043         return 0;
12044 }
12045
12046 /**
12047  * lfs_pcc() - Parse and execute lfs pcc commands.
12048  * @argc: The count of lfs pcc command line arguments.
12049  * @argv: Array of strings for lfs pcc command line arguments.
12050  *
12051  * This function parses lfs pcc commands and performs the
12052  * corresponding functions specified in pcc_cmdlist[].
12053  *
12054  * Return: 0 on success or an error code on failure.
12055  */
12056 static int lfs_pcc(int argc, char **argv)
12057 {
12058         char cmd[PATH_MAX];
12059         int rc = 0;
12060
12061         setlinebuf(stdout);
12062
12063         Parser_init("lfs-pcc > ", pcc_cmdlist);
12064
12065         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
12066         progname = cmd;
12067         program_invocation_short_name = cmd;
12068         if (argc > 1)
12069                 rc = Parser_execarg(argc - 1, argv + 1, pcc_cmdlist);
12070         else
12071                 rc = Parser_commands();
12072
12073         return rc < 0 ? -rc : rc;
12074 }
12075
12076 static int lfs_list_commands(int argc, char **argv)
12077 {
12078         char buffer[81] = ""; /* 80 printable chars + terminating NUL */
12079
12080         Parser_list_commands(cmdlist, buffer, sizeof(buffer), NULL, 0, 4);
12081
12082         return 0;
12083 }
12084
12085 int main(int argc, char **argv)
12086 {
12087         int rc;
12088
12089         /* Ensure that liblustreapi constructor has run */
12090         if (!llapi_liblustreapi_initialized())
12091                 fprintf(stderr, "liblustreapi was not properly initialized\n");
12092
12093         setlinebuf(stdout);
12094         opterr = 0;
12095
12096         Parser_init("lfs > ", cmdlist);
12097
12098         progname = program_invocation_short_name; /* Used in error messages */
12099         if (argc > 1) {
12100                 llapi_set_command_name(argv[1]);
12101                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
12102                 llapi_clear_command_name();
12103         } else {
12104                 rc = Parser_commands();
12105         }
12106
12107         return rc < 0 ? -rc : rc;
12108 }
12109
12110 #ifdef _LUSTRE_IDL_H_
12111 /* Everything we need here should be included by lustreapi.h. */
12112 # error "lfs should not depend on lustre_idl.h"
12113 #endif /* _LUSTRE_IDL_H_ */