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