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