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