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