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