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