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