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