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