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