Whamcloud - gitweb
LU-10657 utils: fd leak in mirror_split()
[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 <fcntl.h>
62 #include <dirent.h>
63 #include <time.h>
64 #include <ctype.h>
65 #include <zlib.h>
66 #include <libgen.h>
67 #include "lfs_project.h"
68
69 #include <libcfs/util/string.h>
70 #include <libcfs/util/ioctl.h>
71 #include <libcfs/util/parser.h>
72 #include <lustre/lustreapi.h>
73 #include <linux/lustre/lustre_ver.h>
74 #include <linux/lustre/lustre_param.h>
75 #include <linux/lnet/nidstr.h>
76 #include <cyaml.h>
77
78 #ifndef ARRAY_SIZE
79 # define ARRAY_SIZE(a) ((sizeof(a)) / (sizeof((a)[0])))
80 #endif /* !ARRAY_SIZE */
81
82 /* all functions */
83 static int lfs_find(int argc, char **argv);
84 static int lfs_getstripe(int argc, char **argv);
85 static int lfs_getdirstripe(int argc, char **argv);
86 static int lfs_setdirstripe(int argc, char **argv);
87 static int lfs_rmentry(int argc, char **argv);
88 static int lfs_osts(int argc, char **argv);
89 static int lfs_mdts(int argc, char **argv);
90 static int lfs_df(int argc, char **argv);
91 static int lfs_getname(int argc, char **argv);
92 static int lfs_check(int argc, char **argv);
93 #ifdef HAVE_SYS_QUOTA_H
94 static int lfs_setquota(int argc, char **argv);
95 static int lfs_quota(int argc, char **argv);
96 static int lfs_project(int argc, char **argv);
97 #endif
98 static int lfs_flushctx(int argc, char **argv);
99 static int lfs_cp(int argc, char **argv);
100 static int lfs_ls(int argc, char **argv);
101 static int lfs_poollist(int argc, char **argv);
102 static int lfs_changelog(int argc, char **argv);
103 static int lfs_changelog_clear(int argc, char **argv);
104 static int lfs_fid2path(int argc, char **argv);
105 static int lfs_path2fid(int argc, char **argv);
106 static int lfs_data_version(int argc, char **argv);
107 static int lfs_hsm_state(int argc, char **argv);
108 static int lfs_hsm_set(int argc, char **argv);
109 static int lfs_hsm_clear(int argc, char **argv);
110 static int lfs_hsm_action(int argc, char **argv);
111 static int lfs_hsm_archive(int argc, char **argv);
112 static int lfs_hsm_restore(int argc, char **argv);
113 static int lfs_hsm_release(int argc, char **argv);
114 static int lfs_hsm_remove(int argc, char **argv);
115 static int lfs_hsm_cancel(int argc, char **argv);
116 static int lfs_swap_layouts(int argc, char **argv);
117 static int lfs_mv(int argc, char **argv);
118 static int lfs_ladvise(int argc, char **argv);
119 static int lfs_mirror(int argc, char **argv);
120 static int lfs_mirror_list_commands(int argc, char **argv);
121 static int lfs_list_commands(int argc, char **argv);
122 static inline int lfs_mirror_resync(int argc, char **argv);
123 static inline int lfs_mirror_verify(int argc, char **argv);
124
125 enum setstripe_origin {
126         SO_SETSTRIPE,
127         SO_MIGRATE,
128         SO_MIRROR_CREATE,
129         SO_MIRROR_EXTEND,
130         SO_MIRROR_SPLIT,
131 };
132 static int lfs_setstripe_internal(int argc, char **argv,
133                                   enum setstripe_origin opc);
134
135 static inline int lfs_setstripe(int argc, char **argv)
136 {
137         return lfs_setstripe_internal(argc, argv, SO_SETSTRIPE);
138 }
139 static inline int lfs_setstripe_migrate(int argc, char **argv)
140 {
141         return lfs_setstripe_internal(argc, argv, SO_MIGRATE);
142 }
143 static inline int lfs_mirror_create(int argc, char **argv)
144 {
145         return lfs_setstripe_internal(argc, argv, SO_MIRROR_CREATE);
146 }
147 static inline int lfs_mirror_extend(int argc, char **argv)
148 {
149         return lfs_setstripe_internal(argc, argv, SO_MIRROR_EXTEND);
150 }
151 static inline int lfs_mirror_split(int argc, char **argv)
152 {
153         return lfs_setstripe_internal(argc, argv, SO_MIRROR_SPLIT);
154 }
155
156 /* Setstripe and migrate share mostly the same parameters */
157 #define SSM_CMD_COMMON(cmd) \
158         "usage: "cmd" [--component-end|-E <comp_end>]\n"                \
159         "                 [--stripe-count|-c <stripe_count>]\n"         \
160         "                 [--stripe-index|-i <start_ost_idx>]\n"        \
161         "                 [--stripe-size|-S <stripe_size>]\n"           \
162         "                 [--layout|-L <pattern>]\n"            \
163         "                 [--pool|-p <pool_name>]\n"                    \
164         "                 [--ost|-o <ost_indices>]\n"                   \
165         "                 [--yaml|-y <yaml_template_file>]\n"
166
167 #define SSM_HELP_COMMON \
168         "\tstripe_count: Number of OSTs to stripe over (0=fs default, -1 all)\n" \
169         "\tstart_ost_idx: OST index of first stripe (-1=default round robin)\n"\
170         "\tstripe_size:  Number of bytes on each OST (0=fs default)\n" \
171         "\t              Can be specified with K, M or G (for KB, MB, GB\n" \
172         "\t              respectively)\n"                               \
173         "\tpool_name:    Name of OST pool to use (default none)\n"      \
174         "\tlayout:       stripe pattern type: raid0, mdt (default raid0)\n"\
175         "\tost_indices:  List of OST indices, can be repeated multiple times\n"\
176         "\t              Indices be specified in a format of:\n"        \
177         "\t                -o <ost_1>,<ost_i>-<ost_j>,<ost_n>\n"        \
178         "\t              Or:\n"                                         \
179         "\t                -o <ost_1> -o <ost_i>-<ost_j> -o <ost_n>\n"  \
180         "\t              If --pool is set with --ost, then the OSTs\n"  \
181         "\t              must be the members of the pool.\n"            \
182         "\tcomp_end:     Extent end of component, start after previous end.\n"\
183         "\t              Can be specified with K, M or G (for KB, MB, GB\n" \
184         "\t              respectively, -1 for EOF). Must be a multiple of\n"\
185         "\t              stripe_size.\n"                                      \
186         "\tyaml_template_file:\n"                                             \
187         "\t              YAML layout template file, can't be used with -c,\n" \
188         "\t              -i, -S, -p, -o, or -E arguments.\n"
189
190 #define MIRROR_CREATE_HELP                                                     \
191         "\tmirror_count: Number of mirrors to be created with the upcoming\n"  \
192         "\t              setstripe layout options\n"                           \
193         "\t              It defaults to 1 if not specified; if specified,\n"   \
194         "\t              it must follow the option without a space.\n"         \
195         "\t              The option can also be repeated multiple times to\n"  \
196         "\t              separate mirrors that have different layouts.\n"      \
197         "\tsetstripe options: Mirror layout\n"                                 \
198         "\t              It can be a plain layout or a composite layout.\n"    \
199         "\t              If not specified, the stripe options inherited\n"     \
200         "\t              from the previous component will be used.\n"          \
201         "\tflags:        set flags to the component of the current mirror.\n"  \
202         "\t              Only \"prefer\" flag is supported so far.\n"
203
204 #define MIRROR_EXTEND_HELP                                                     \
205         MIRROR_CREATE_HELP                                                     \
206         "\tvictim_file:  The layout of victim_file will be split and used\n"   \
207         "\t              as a mirror added to the mirrored file.\n"            \
208         "\tno-verify:    This option indicates not to verify the mirror(s)\n"  \
209         "\t              from victim file(s) in case the victim file(s)\n"     \
210         "\t              contains the same data as the original mirrored\n"    \
211         "\t              file.\n"
212
213 #define MIRROR_EXTEND_USAGE                                                    \
214         "                 <--mirror-count|-N[mirror_count]>\n"                 \
215         "                 [setstripe options|-f <victim_file>]\n"              \
216         "                 [--no-verify]\n"
217
218 #define SETSTRIPE_USAGE                                                 \
219         SSM_CMD_COMMON("setstripe")                                     \
220         MIRROR_EXTEND_USAGE                                             \
221         "                 <directory|filename>\n"                       \
222         SSM_HELP_COMMON                                                 \
223         MIRROR_EXTEND_HELP
224
225 #define MIGRATE_USAGE                                                   \
226         SSM_CMD_COMMON("migrate  ")                                     \
227         "                 [--block|-b]\n"                               \
228         "                 [--non-block|-n]\n"                           \
229         "                 [--non-direct|-D]\n"                          \
230         "                 <filename>\n"                                 \
231         SSM_HELP_COMMON                                                 \
232         "\n"                                                            \
233         "\tblock:        Block file access during data migration (default)\n" \
234         "\tnon-block:    Abort migrations if concurrent access is detected\n" \
235         "\tnon-direct:   Do not use direct I/O to copy file contents\n" \
236
237 #define SETDIRSTRIPE_USAGE                                      \
238         "               [--mdt-count|-c stripe_count>\n"        \
239         "               [--mdt-index|-i mdt_index]\n"           \
240         "               [--mdt-hash|-H mdt_hash]\n"             \
241         "               [--default|-D] [--mode|-m mode] <dir>\n"        \
242         "\tstripe_count: stripe count of the striped directory\n"       \
243         "\tmdt_index: MDT index of first stripe\n"                      \
244         "\tmdt_hash:  hash type of the striped directory. mdt types:\n" \
245         "       fnv_1a_64 FNV-1a hash algorithm (default)\n"            \
246         "       all_char  sum of characters % MDT_COUNT (not recommended)\n" \
247         "\tdefault_stripe: set default dirstripe of the directory\n"    \
248         "\tmode: the mode of the directory\n"
249
250 /**
251  * command_t mirror_cmdlist - lfs mirror commands.
252  */
253 command_t mirror_cmdlist[] = {
254         { .pc_name = "create", .pc_func = lfs_mirror_create,
255           .pc_help = "Create a mirrored file.\n"
256                 "usage: lfs mirror create "
257                 "<--mirror-count|-N[mirror_count]> "
258                 "[setstripe options] ... <filename|directory>\n"
259           MIRROR_CREATE_HELP },
260         { .pc_name = "extend", .pc_func = lfs_mirror_extend,
261           .pc_help = "Extend a mirrored file.\n"
262                 "usage: lfs mirror extend "
263                 "<--mirror-count|-N[mirror_count]> [--no-verify] "
264                 "[setstripe options|-f <victim_file>] ... <filename>\n"
265           MIRROR_EXTEND_HELP },
266         { .pc_name = "split", .pc_func = lfs_mirror_split,
267           .pc_help = "Split a mirrored file.\n"
268         "usage: lfs mirror split <--mirror-id <mirror_id>> [--destroy|-d] "
269         "[-f <new_file>] <mirrored file>\n"
270         "\tmirror_id:    The numerical unique identifier for a mirror. It\n"
271         "\t              can be fetched by lfs getstripe command.\n"
272         "\tnew_file:     This option indicates the layout of the split\n"
273         "\t              mirror will be stored into. If not specified,\n"
274         "\t              a new file named <mirrored_file>.mirror~<mirror_id>\n"
275         "\t              will be used.\n" },
276         { .pc_name = "resync", .pc_func = lfs_mirror_resync,
277           .pc_help = "Resynchronizes out-of-sync mirrored file(s).\n"
278                 "usage: lfs mirror resync [--only <mirror_id[,...]>] "
279                 "<mirrored file> [<mirrored file2>...]\n"},
280         { .pc_name = "verify", .pc_func = lfs_mirror_verify,
281           .pc_help = "Verify mirrored file(s).\n"
282                 "usage: lfs mirror verify "
283                 "[--only <mirror_id,mirror_id2[,...]>] "
284                 "[--verbose|-v] <mirrored_file> [<mirrored_file2> ...]\n"},
285         { .pc_name = "--list-commands", .pc_func = lfs_mirror_list_commands,
286           .pc_help = "list commands supported by lfs mirror"},
287         { .pc_name = "help", .pc_func = Parser_help, .pc_help = "help" },
288         { .pc_name = "exit", .pc_func = Parser_quit, .pc_help = "quit" },
289         { .pc_name = "quit", .pc_func = Parser_quit, .pc_help = "quit" },
290         { .pc_help = NULL }
291 };
292
293 /* all available commands */
294 command_t cmdlist[] = {
295         {"setstripe", lfs_setstripe, 0,
296          "To create a file with specified striping/composite layout, or\n"
297          "create/replace the default layout on an existing directory:\n"
298          SSM_CMD_COMMON("setstripe")
299          "                 <directory|filename>\n"
300          " or\n"
301          "To add component(s) to an existing composite file:\n"
302          SSM_CMD_COMMON("setstripe --component-add")
303          SSM_HELP_COMMON
304          "To totally delete the default striping from an existing directory:\n"
305          "usage: setstripe -d <directory>\n"
306          " or\n"
307          "To delete the last component(s) from an existing composite file\n"
308          "(note that this will also delete any data in those components):\n"
309          "usage: setstripe --component-del [--component-id|-I <comp_id>]\n"
310          "                               [--component-flags|-F <comp_flags>]\n"
311          "                               <filename>\n"
312          "\tcomp_id:     Unique component ID to delete\n"
313          "\tcomp_flags:  'init' indicating all instantiated components\n"
314          "\t             '^init' indicating all uninstantiated components\n"
315          "\t-I and -F cannot be specified at the same time\n"},
316         {"getstripe", lfs_getstripe, 0,
317          "To list the layout pattern for a given file or files in a\n"
318          "directory or recursively for all files in a directory tree.\n"
319          "usage: getstripe [--ost|-O <uuid>] [--quiet|-q] [--verbose|-v]\n"
320          "                 [--stripe-count|-c] [--stripe-index|-i] [--fid|-F]\n"
321          "                 [--pool|-p] [--stripe-size|-S] [--directory|-d]\n"
322          "                 [--mdt-index|-m] [--recursive|-r] [--raw|-R]\n"
323          "                 [--layout|-L] [--generation|-g] [--yaml|-y]\n"
324          "                 [--component-id[=comp_id]|-I[comp_id]]\n"
325          "                 [--component-flags[=comp_flags]]\n"
326          "                 [--component-count]\n"
327          "                 [--component-start[=[+-]comp_start]]\n"
328          "                 [--component-end[=[+-]comp_end]|-E[[+-]comp_end]]\n"
329          "                 <directory|filename> ..."},
330         {"setdirstripe", lfs_setdirstripe, 0,
331          "To create a striped directory on a specified MDT. This can only\n"
332          "be done on MDT0 with the right of administrator.\n"
333          "usage: setdirstripe [OPTION] <directory>\n"
334          SETDIRSTRIPE_USAGE},
335         {"getdirstripe", lfs_getdirstripe, 0,
336          "To list the layout pattern info for a given directory\n"
337          "or recursively for all directories in a directory tree.\n"
338          "usage: getdirstripe [--mdt-count|-c] [--mdt-index|-m|-i]\n"
339          "                    [--mdt-hash|-H] [--obd|-O <uuid>]\n"
340          "                    [--recursive|-r] [--yaml|-y]\n"
341          "                    [--default|-D] <dir> ..."},
342         {"mkdir", lfs_setdirstripe, 0,
343          "To create a striped directory on a specified MDT. This can only\n"
344          "be done on MDT0 with the right of administrator.\n"
345          "usage: mkdir [OPTION] <directory>\n"
346          SETDIRSTRIPE_USAGE},
347         {"rm_entry", lfs_rmentry, 0,
348          "To remove the name entry of the remote directory. Note: This\n"
349          "command will only delete the name entry, i.e. the remote directory\n"
350          "will become inaccessable after this command. This can only be done\n"
351          "by the administrator\n"
352          "usage: rm_entry <dir>\n"},
353         {"pool_list", lfs_poollist, 0,
354          "List pools or pool OSTs\n"
355          "usage: pool_list <fsname>[.<pool>] | <pathname>\n"},
356         {"find", lfs_find, 0,
357          "find files matching given attributes recursively in directory tree.\n"
358          "usage: find <directory|filename> ...\n"
359          "     [[!] --atime|-A [+-]N] [[!] --ctime|-C [+-]N]\n"
360          "     [[!] --mtime|-M [+-]N] [--maxdepth|-D N]\n"
361          "     [[!] --mdt-index|--mdt|-m <uuid|index,...>]\n"
362          "     [[!] --name|-n <pattern>] [[!] --ost|-O <uuid|index,...>]\n"
363          "     [--print|-P] [--print0|-0] [[!] --size|-s [+-]N[bkMGTPE]]\n"
364          "     [[!] --stripe-count|-c [+-]<stripes>]\n"
365          "     [[!] --stripe-index|-i <index,...>]\n"
366          "     [[!] --stripe-size|-S [+-]N[kMGT]] [[!] --type|-t <filetype>]\n"
367          "     [[!] --gid|-g|--group|-G <gid>|<gname>]\n"
368          "     [[!] --uid|-u|--user|-U <uid>|<uname>] [[!] --pool <pool>]\n"
369          "     [[!] --projid <projid>]\n"
370          "     [[!] --layout|-L released,raid0,mdt]\n"
371          "     [[!] --component-count [+-]<comp_cnt>]\n"
372          "     [[!] --component-start [+-]N[kMGTPE]]\n"
373          "     [[!] --component-end|-E [+-]N[kMGTPE]]\n"
374          "     [[!] --component-flags <comp_flags>]\n"
375          "     [[!] --mirror-count|-N [+-]<n>]\n"
376          "     [[!] --mirror-state <[^]state>]\n"
377          "     [[!] --mdt-count|-T [+-]<stripes>]\n"
378          "     [[!] --mdt-hash|-H <hashtype>\n"
379          "\t !: used before an option indicates 'NOT' requested attribute\n"
380          "\t -: used before a value indicates less than requested value\n"
381          "\t +: used before a value indicates more than requested value\n"
382          "\thashtype:   hash type of the striped directory.\n"
383          "\t            fnv_1a_64 FNV-1a hash algorithm\n"
384          "\t            all_char  sum of characters % MDT_COUNT\n"},
385         {"check", lfs_check, 0,
386          "Display the status of MDS or OSTs (as specified in the command)\n"
387          "or all the servers (MDS and OSTs).\n"
388          "usage: check <osts|mds|servers>"},
389         {"osts", lfs_osts, 0, "list OSTs connected to client "
390          "[for specified path only]\n" "usage: osts [path]"},
391         {"mdts", lfs_mdts, 0, "list MDTs connected to client "
392          "[for specified path only]\n" "usage: mdts [path]"},
393         {"df", lfs_df, 0,
394          "report filesystem disk space usage or inodes usage"
395          "of each MDS and all OSDs or a batch belonging to a specific pool .\n"
396          "Usage: df [-i] [-h] [--lazy|-l] [--pool|-p <fsname>[.<pool>] [path]"},
397         {"getname", lfs_getname, 0, "list instances and specified mount points "
398          "[for specified path only]\n"
399          "Usage: getname [-h]|[path ...] "},
400 #ifdef HAVE_SYS_QUOTA_H
401         {"setquota", lfs_setquota, 0, "Set filesystem quotas.\n"
402          "usage: setquota <-u|-g|-p> <uname>|<uid>|<gname>|<gid>|<projid>\n"
403          "                -b <block-softlimit> -B <block-hardlimit>\n"
404          "                -i <inode-softlimit> -I <inode-hardlimit> <filesystem>\n"
405          "       setquota <-u|--user|-g|--group|-p|--projid> <uname>|<uid>|<gname>|<gid>|<projid>\n"
406          "                [--block-softlimit <block-softlimit>]\n"
407          "                [--block-hardlimit <block-hardlimit>]\n"
408          "                [--inode-softlimit <inode-softlimit>]\n"
409          "                [--inode-hardlimit <inode-hardlimit>] <filesystem>\n"
410          "       setquota [-t] <-u|--user|-g|--group|-p|--projid>\n"
411          "                [--block-grace <block-grace>]\n"
412          "                [--inode-grace <inode-grace>] <filesystem>\n"
413          "       -b can be used instead of --block-softlimit/--block-grace\n"
414          "       -B can be used instead of --block-hardlimit\n"
415          "       -i can be used instead of --inode-softlimit/--inode-grace\n"
416          "       -I can be used instead of --inode-hardlimit\n\n"
417          "Note: The total quota space will be split into many qunits and\n"
418          "      balanced over all server targets, the minimal qunit size is\n"
419          "      1M bytes for block space and 1K inodes for inode space.\n\n"
420          "      Quota space rebalancing process will stop when this mininum\n"
421          "      value is reached. As a result, quota exceeded can be returned\n"
422          "      while many targets still have 1MB or 1K inodes of spare\n"
423          "      quota space."},
424         {"quota", lfs_quota, 0, "Display disk usage and limits.\n"
425          "usage: quota [-q] [-v] [-h] [-o <obd_uuid>|-i <mdt_idx>|-I "
426                        "<ost_idx>]\n"
427          "             [<-u|-g|-p> <uname>|<uid>|<gname>|<gid>|<projid>] <filesystem>\n"
428          "       quota [-o <obd_uuid>|-i <mdt_idx>|-I <ost_idx>] -t <-u|-g|-p> <filesystem>"},
429         {"project", lfs_project, 0,
430          "Change or list project attribute for specified file or directory.\n"
431          "usage: project [-d|-r] <file|directory...>\n"
432          "         list project ID and flags on file(s) or directories\n"
433          "       project [-p id] [-s] [-r] <file|directory...>\n"
434          "         set project ID and/or inherit flag for specified file(s) or directories\n"
435          "       project -c [-d|-r [-p id] [-0]] <file|directory...>\n"
436          "         check project ID and flags on file(s) or directories, print outliers\n"
437          "       project -C [-r] [-k] <file|directory...>\n"
438          "         clear the project inherit flag and ID on the file or directory\n"
439         },
440 #endif
441         {"flushctx", lfs_flushctx, 0, "Flush security context for current user.\n"
442          "usage: flushctx [-k] [mountpoint...]"},
443         {"cp", lfs_cp, 0,
444          "Remote user copy files and directories.\n"
445          "usage: cp [OPTION]... [-T] SOURCE DEST\n\tcp [OPTION]... SOURCE... DIRECTORY\n\tcp [OPTION]... -t DIRECTORY SOURCE..."},
446         {"ls", lfs_ls, 0,
447          "Remote user list directory contents.\n"
448          "usage: ls [OPTION]... [FILE]..."},
449         {"changelog", lfs_changelog, 0,
450          "Show the metadata changes on an MDT."
451          "\nusage: changelog <mdtname> [startrec [endrec]]"},
452         {"changelog_clear", lfs_changelog_clear, 0,
453          "Indicate that old changelog records up to <endrec> are no longer of "
454          "interest to consumer <id>, allowing the system to free up space.\n"
455          "An <endrec> of 0 means all records.\n"
456          "usage: changelog_clear <mdtname> <id> <endrec>"},
457         {"fid2path", lfs_fid2path, 0,
458          "Resolve the full path(s) for given FID(s). For a specific hardlink "
459          "specify link number <linkno>.\n"
460         /* "For a historical link name, specify changelog record <recno>.\n" */
461          "usage: fid2path [--link <linkno>] <fsname|rootpath> <fid> ..."
462                 /* [ --rec <recno> ] */ },
463         {"path2fid", lfs_path2fid, 0, "Display the fid(s) for a given path(s).\n"
464          "usage: path2fid [--parents] <path> ..."},
465         {"data_version", lfs_data_version, 0, "Display file data version for "
466          "a given path.\n" "usage: data_version -[n|r|w] <path>"},
467         {"hsm_state", lfs_hsm_state, 0, "Display the HSM information (states, "
468          "undergoing actions) for given files.\n usage: hsm_state <file> ..."},
469         {"hsm_set", lfs_hsm_set, 0, "Set HSM user flag on specified files.\n"
470          "usage: hsm_set [--norelease] [--noarchive] [--dirty] [--exists] "
471          "[--archived] [--lost] [--archive-id NUM] <file> ..."},
472         {"hsm_clear", lfs_hsm_clear, 0, "Clear HSM user flag on specified "
473          "files.\n"
474          "usage: hsm_clear [--norelease] [--noarchive] [--dirty] [--exists] "
475          "[--archived] [--lost] <file> ..."},
476         {"hsm_action", lfs_hsm_action, 0, "Display current HSM request for "
477          "given files.\n" "usage: hsm_action <file> ..."},
478         {"hsm_archive", lfs_hsm_archive, 0,
479          "Archive file to external storage.\n"
480          "usage: hsm_archive [--filelist FILELIST] [--data DATA] [--archive NUM] "
481          "<file> ..."},
482         {"hsm_restore", lfs_hsm_restore, 0,
483          "Restore file from external storage.\n"
484          "usage: hsm_restore [--filelist FILELIST] [--data DATA] <file> ..."},
485         {"hsm_release", lfs_hsm_release, 0,
486          "Release files from Lustre.\n"
487          "usage: hsm_release [--filelist FILELIST] [--data DATA] <file> ..."},
488         {"hsm_remove", lfs_hsm_remove, 0,
489          "Remove file copy from external storage.\n"
490          "usage: hsm_remove [--filelist FILELIST] [--data DATA] "
491          "[--archive NUM]\n"
492          "                  (FILE [FILE ...] | "
493          "--mntpath MOUNTPATH FID [FID ...])\n"
494          "\n"
495          "Note: To remove an archived copy of a file already deleted from a "
496          "Lustre FS, the\n"
497          "--mntpath option and a list of FIDs must be specified"
498         },
499         {"hsm_cancel", lfs_hsm_cancel, 0,
500          "Cancel requests related to specified files.\n"
501          "usage: hsm_cancel [--filelist FILELIST] [--data DATA] <file> ..."},
502         {"swap_layouts", lfs_swap_layouts, 0, "Swap layouts between 2 files.\n"
503          "usage: swap_layouts <path1> <path2>"},
504         {"migrate", lfs_setstripe_migrate, 0,
505          "migrate a directory between MDTs.\n"
506          "usage: migrate --mdt-index <mdt_idx> [--verbose|-v] "
507          "<directory>\n"
508          "\tmdt_idx:      index of the destination MDT\n"
509          "\n"
510          "migrate file objects from one OST "
511          "layout\nto another (may be not safe with concurent writes).\n"
512          "usage: migrate  "
513          "[--stripe-count|-c] <stripe_count>\n"
514          "              [--stripe-index|-i] <start_ost_index>\n"
515          "              [--stripe-size|-S] <stripe_size>\n"
516          "              [--pool|-p] <pool_name>\n"
517          "              [--ost|-o] <ost_indices>\n"
518          "              [--block|-b]\n"
519          "              [--non-block|-n]\n"
520          "              [--non-direct|-D]\n"
521          "              <file|directory>\n"
522          "\tstripe_count:     number of OSTs to stripe a file over\n"
523          "\tstripe_ost_index: index of the first OST to stripe a file over\n"
524          "\tstripe_size:      number of bytes to store before moving to the next OST\n"
525          "\tpool_name:        name of the predefined pool of OSTs\n"
526          "\tost_indices:      OSTs to stripe over, in order\n"
527          "\tblock:            wait for the operation to return before continuing\n"
528          "\tnon-block:        do not wait for the operation to return\n"
529          "\tnon-direct:       do not use direct I/O to copy file contents.\n"},
530         {"mv", lfs_mv, 0,
531          "To move directories between MDTs. This command is deprecated, "
532          "use \"migrate\" instead.\n"
533          "usage: mv <directory|filename> [--mdt-index|-m] <mdt_index> "
534          "[--verbose|-v]\n"},
535         {"ladvise", lfs_ladvise, 0,
536          "Provide servers with advice about access patterns for a file.\n"
537          "usage: ladvise [--advice|-a ADVICE] [--start|-s START[kMGT]]\n"
538          "               [--background|-b] [--unset|-u]\n\n"
539          "               {[--end|-e END[kMGT]] | [--length|-l LENGTH[kMGT]]}\n"
540          "               {[--mode|-m [READ,WRITE]}\n"
541          "               <file> ...\n"},
542         {"mirror", lfs_mirror, mirror_cmdlist,
543          "lfs commands used to manage files with mirrored components:\n"
544          "lfs mirror create - create a mirrored file or directory\n"
545          "lfs mirror extend - add mirror(s) to an existing file\n"
546          "lfs mirror split  - split a mirror from an existing mirrored file\n"
547          "lfs mirror resync - resynchronize out-of-sync mirrored file(s)\n"
548          "lfs mirror verify - verify mirrored file(s)\n"},
549         {"help", Parser_help, 0, "help"},
550         {"exit", Parser_quit, 0, "quit"},
551         {"quit", Parser_quit, 0, "quit"},
552         {"--version", Parser_version, 0,
553          "output build version of the utility and exit"},
554         {"--list-commands", lfs_list_commands, 0,
555          "list commands supported by the utility and exit"},
556         { 0, 0, 0, NULL }
557 };
558
559
560 static int check_hashtype(const char *hashtype)
561 {
562         int i;
563
564         for (i = LMV_HASH_TYPE_ALL_CHARS; i < LMV_HASH_TYPE_MAX; i++)
565                 if (strcmp(hashtype, mdt_hash_name[i]) == 0)
566                         return i;
567
568         return 0;
569 }
570
571
572 static const char *error_loc = "syserror";
573
574 enum {
575         MIGRATION_NONBLOCK      = 1 << 0,
576         MIGRATION_MIRROR        = 1 << 1,
577         MIGRATION_NONDIRECT     = 1 << 2,
578 };
579
580 static int lfs_component_create(char *fname, int open_flags, mode_t open_mode,
581                                 struct llapi_layout *layout);
582
583 static int
584 migrate_open_files(const char *name, __u64 migration_flags,
585                    const struct llapi_stripe_param *param,
586                    struct llapi_layout *layout, int *fd_src, int *fd_tgt)
587 {
588         int                      fd = -1;
589         int                      fdv = -1;
590         int                      rflags;
591         int                      mdt_index;
592         int                      random_value;
593         char                     parent[PATH_MAX];
594         char                     volatile_file[PATH_MAX];
595         char                    *ptr;
596         int                      rc;
597         struct stat              st;
598         struct stat              stv;
599
600         if (param == NULL && layout == NULL) {
601                 error_loc = "layout information";
602                 return -EINVAL;
603         }
604
605         /* search for file directory pathname */
606         if (strlen(name) > sizeof(parent) - 1) {
607                 error_loc = "source file name";
608                 return -ERANGE;
609         }
610
611         strncpy(parent, name, sizeof(parent));
612         ptr = strrchr(parent, '/');
613         if (ptr == NULL) {
614                 if (getcwd(parent, sizeof(parent)) == NULL) {
615                         error_loc = "getcwd";
616                         return -errno;
617                 }
618         } else {
619                 if (ptr == parent) /* leading '/' */
620                         ptr = parent + 1;
621                 *ptr = '\0';
622         }
623
624         /* open file, direct io */
625         /* even if the file is only read, WR mode is nedeed to allow
626          * layout swap on fd */
627         rflags = O_RDWR;
628         if (!(migration_flags & MIGRATION_NONDIRECT))
629                 rflags |= O_DIRECT;
630         fd = open(name, rflags);
631         if (fd < 0) {
632                 rc = -errno;
633                 error_loc = "cannot open source file";
634                 return rc;
635         }
636
637         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
638         if (rc < 0) {
639                 error_loc = "cannot get MDT index";
640                 goto out;
641         }
642
643         do {
644                 int open_flags = O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW;
645                 mode_t open_mode = S_IRUSR | S_IWUSR;
646
647                 random_value = random();
648                 rc = snprintf(volatile_file, sizeof(volatile_file),
649                               "%s/%s:%.4X:%.4X", parent, LUSTRE_VOLATILE_HDR,
650                               mdt_index, random_value);
651                 if (rc >= sizeof(volatile_file)) {
652                         rc = -ENAMETOOLONG;
653                         break;
654                 }
655
656                 /* create, open a volatile file, use caching (ie no directio) */
657                 if (param != NULL)
658                         fdv = llapi_file_open_param(volatile_file, open_flags,
659                                                     open_mode, param);
660                 else
661                         fdv = lfs_component_create(volatile_file, open_flags,
662                                                    open_mode, layout);
663         } while (fdv < 0 && (rc = fdv) == -EEXIST);
664
665         if (rc < 0) {
666                 error_loc = "cannot create volatile file";
667                 goto out;
668         }
669
670         /* In case the MDT does not support creation of volatile files
671          * we should try to unlink it. */
672         (void)unlink(volatile_file);
673
674         /* Not-owner (root?) special case.
675          * Need to set owner/group of volatile file like original.
676          * This will allow to pass related check during layout_swap.
677          */
678         rc = fstat(fd, &st);
679         if (rc != 0) {
680                 rc = -errno;
681                 error_loc = "cannot stat source file";
682                 goto out;
683         }
684
685         rc = fstat(fdv, &stv);
686         if (rc != 0) {
687                 rc = -errno;
688                 error_loc = "cannot stat volatile";
689                 goto out;
690         }
691
692         if (st.st_uid != stv.st_uid || st.st_gid != stv.st_gid) {
693                 rc = fchown(fdv, st.st_uid, st.st_gid);
694                 if (rc != 0) {
695                         rc = -errno;
696                         error_loc = "cannot change ownwership of volatile";
697                         goto out;
698                 }
699         }
700
701 out:
702         if (rc < 0) {
703                 if (fd > 0)
704                         close(fd);
705                 if (fdv > 0)
706                         close(fdv);
707         } else {
708                 *fd_src = fd;
709                 *fd_tgt = fdv;
710                 error_loc = NULL;
711         }
712         return rc;
713 }
714
715 static int migrate_copy_data(int fd_src, int fd_dst, int (*check_file)(int))
716 {
717         struct llapi_layout *layout;
718         size_t   buf_size = 4 * 1024 * 1024;
719         void    *buf = NULL;
720         ssize_t  rsize = -1;
721         ssize_t  wsize = 0;
722         size_t   rpos = 0;
723         size_t   wpos = 0;
724         off_t    bufoff = 0;
725         int      rc;
726
727         layout = llapi_layout_get_by_fd(fd_src, 0);
728         if (layout != NULL) {
729                 uint64_t stripe_size;
730
731                 rc = llapi_layout_stripe_size_get(layout, &stripe_size);
732                 if (rc == 0)
733                         buf_size = stripe_size;
734
735                 llapi_layout_free(layout);
736         }
737
738         /* Use a page-aligned buffer for direct I/O */
739         rc = posix_memalign(&buf, getpagesize(), buf_size);
740         if (rc != 0)
741                 return -rc;
742
743         while (1) {
744                 /* read new data only if we have written all
745                  * previously read data */
746                 if (wpos == rpos) {
747                         if (check_file) {
748                                 rc = check_file(fd_src);
749                                 if (rc < 0)
750                                         break;
751                         }
752
753                         rsize = read(fd_src, buf, buf_size);
754                         if (rsize < 0) {
755                                 rc = -errno;
756                                 break;
757                         }
758                         rpos += rsize;
759                         bufoff = 0;
760                 }
761                 /* eof ? */
762                 if (rsize == 0)
763                         break;
764
765                 wsize = write(fd_dst, buf + bufoff, rpos - wpos);
766                 if (wsize < 0) {
767                         rc = -errno;
768                         break;
769                 }
770                 wpos += wsize;
771                 bufoff += wsize;
772         }
773
774         if (rc == 0) {
775                 rc = fsync(fd_dst);
776                 if (rc < 0)
777                         rc = -errno;
778         }
779
780         free(buf);
781         return rc;
782 }
783
784 static int migrate_copy_timestamps(int fd, int fdv)
785 {
786         struct stat st;
787
788         if (fstat(fd, &st) == 0) {
789                 struct timeval tv[2] = {
790                         {.tv_sec = st.st_atime},
791                         {.tv_sec = st.st_mtime}
792                 };
793
794                 return futimes(fdv, tv);
795         }
796
797         return -errno;
798 }
799
800 static int migrate_block(int fd, int fdv)
801 {
802         __u64   dv1;
803         int     gid;
804         int     rc;
805         int     rc2;
806
807         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
808         if (rc < 0) {
809                 error_loc = "cannot get dataversion";
810                 return rc;
811         }
812
813         do
814                 gid = random();
815         while (gid == 0);
816
817         /* The grouplock blocks all concurrent accesses to the file.
818          * It has to be taken after llapi_get_data_version as it would
819          * block it too. */
820         rc = llapi_group_lock(fd, gid);
821         if (rc < 0) {
822                 error_loc = "cannot get group lock";
823                 return rc;
824         }
825
826         rc = migrate_copy_data(fd, fdv, NULL);
827         if (rc < 0) {
828                 error_loc = "data copy failed";
829                 goto out_unlock;
830         }
831
832         /* Make sure we keep original atime/mtime values */
833         rc = migrate_copy_timestamps(fd, fdv);
834         if (rc < 0) {
835                 error_loc = "timestamp copy failed";
836                 goto out_unlock;
837         }
838
839         /* swap layouts
840          * for a migration we need to check data version on file did
841          * not change.
842          *
843          * Pass in gid=0 since we already own grouplock. */
844         rc = llapi_fswap_layouts_grouplock(fd, fdv, dv1, 0, 0,
845                                            SWAP_LAYOUTS_CHECK_DV1);
846         if (rc == -EAGAIN) {
847                 error_loc = "file changed";
848                 goto out_unlock;
849         } else if (rc < 0) {
850                 error_loc = "cannot swap layout";
851                 goto out_unlock;
852         }
853
854 out_unlock:
855         rc2 = llapi_group_unlock(fd, gid);
856         if (rc2 < 0 && rc == 0) {
857                 error_loc = "unlock group lock";
858                 rc = rc2;
859         }
860
861         return rc;
862 }
863
864 /**
865  * Internal helper for migrate_copy_data(). Check lease and report error if
866  * need be.
867  *
868  * \param[in]  fd           File descriptor on which to check the lease.
869  *
870  * \retval 0       Migration can keep on going.
871  * \retval -errno  Error occurred, abort migration.
872  */
873 static int check_lease(int fd)
874 {
875         int rc;
876
877         rc = llapi_lease_check(fd);
878         if (rc > 0)
879                 return 0; /* llapi_check_lease returns > 0 on success. */
880
881         return -EBUSY;
882 }
883
884 static int migrate_nonblock(int fd, int fdv)
885 {
886         __u64   dv1;
887         __u64   dv2;
888         int     rc;
889
890         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
891         if (rc < 0) {
892                 error_loc = "cannot get data version";
893                 return rc;
894         }
895
896         rc = migrate_copy_data(fd, fdv, check_lease);
897         if (rc < 0) {
898                 error_loc = "data copy failed";
899                 return rc;
900         }
901
902         rc = llapi_get_data_version(fd, &dv2, LL_DV_RD_FLUSH);
903         if (rc != 0) {
904                 error_loc = "cannot get data version";
905                 return rc;
906         }
907
908         if (dv1 != dv2) {
909                 rc = -EAGAIN;
910                 error_loc = "source file changed";
911                 return rc;
912         }
913
914         /* Make sure we keep original atime/mtime values */
915         rc = migrate_copy_timestamps(fd, fdv);
916         if (rc < 0) {
917                 error_loc = "timestamp copy failed";
918                 return rc;
919         }
920
921         return 0;
922 }
923
924 static int lfs_component_set(char *fname, int comp_id,
925                              __u32 flags, __u32 neg_flags)
926 {
927         __u32 ids[2];
928         __u32 flags_array[2];
929         size_t count = 0;
930         int rc;
931
932         if (flags) {
933                 ids[count] = comp_id;
934                 flags_array[count] = flags;
935                 ++count;
936         }
937
938         if (neg_flags) {
939                 ids[count] = comp_id;
940                 flags_array[count] = neg_flags | LCME_FL_NEG;
941                 ++count;
942         }
943
944         rc = llapi_layout_file_comp_set(fname, ids, flags_array, count);
945         if (rc)
946                 fprintf(stderr,
947                         "%s: cannot change the flags of component '%#x' of file '%s': %x / ^(%x)\n",
948                         progname, comp_id, fname, flags, neg_flags);
949
950         return rc;
951 }
952
953 static int lfs_component_del(char *fname, __u32 comp_id,
954                              __u32 flags, __u32 neg_flags)
955 {
956         int     rc = 0;
957
958         if (flags && neg_flags)
959                 return -EINVAL;
960
961         if (!flags && neg_flags)
962                 flags = neg_flags | LCME_FL_NEG;
963
964         if ((flags && comp_id) || (!flags && !comp_id))
965                 return -EINVAL;
966
967         /* LCME_FL_INIT is the only supported flag in PFL */
968         if (flags) {
969                 if (flags & ~LCME_KNOWN_FLAGS) {
970                         fprintf(stderr,
971                                 "%s setstripe: unknown flags %#x\n",
972                                 progname, flags);
973                         return -EINVAL;
974                 }
975         } else if (comp_id > LCME_ID_MAX) {
976                 fprintf(stderr, "%s setstripe: invalid component id %u\n",
977                         progname, comp_id);
978                 return -EINVAL;
979         }
980
981         rc = llapi_layout_file_comp_del(fname, comp_id, flags);
982         if (rc)
983                 fprintf(stderr,
984                         "%s setstripe: cannot delete component %#x from '%s': %s\n",
985                         progname, comp_id, fname, strerror(errno));
986         return rc;
987 }
988
989 static int lfs_component_add(char *fname, struct llapi_layout *layout)
990 {
991         int     rc;
992
993         if (layout == NULL)
994                 return -EINVAL;
995
996         rc = llapi_layout_file_comp_add(fname, layout);
997         if (rc)
998                 fprintf(stderr, "Add layout component(s) to %s failed. %s\n",
999                         fname, strerror(errno));
1000         return rc;
1001 }
1002
1003 static int lfs_component_create(char *fname, int open_flags, mode_t open_mode,
1004                                 struct llapi_layout *layout)
1005 {
1006         struct stat     st;
1007         int     fd;
1008
1009         if (layout == NULL)
1010                 return -EINVAL;
1011
1012         fd = lstat(fname, &st);
1013         if (fd == 0 && S_ISDIR(st.st_mode))
1014                 open_flags = O_DIRECTORY | O_RDONLY;
1015
1016         fd = llapi_layout_file_open(fname, open_flags, open_mode, layout);
1017         if (fd < 0)
1018                 fprintf(stderr, "%s: cannot %s '%s': %s\n", progname,
1019                         S_ISDIR(st.st_mode) ?
1020                                 "set default composite layout for" :
1021                                 "create composite file",
1022                         fname, strerror(errno));
1023         return fd;
1024 }
1025
1026 static int lfs_migrate(char *name, __u64 migration_flags,
1027                        struct llapi_stripe_param *param,
1028                        struct llapi_layout *layout)
1029 {
1030         int fd = -1;
1031         int fdv = -1;
1032         int rc;
1033
1034         rc = migrate_open_files(name, migration_flags, param, layout,
1035                                 &fd, &fdv);
1036         if (rc < 0)
1037                 goto out;
1038
1039         if (!(migration_flags & MIGRATION_NONBLOCK)) {
1040                 /* Blocking mode (forced if servers do not support file lease).
1041                  * It is also the default mode, since we cannot distinguish
1042                  * between a broken lease and a server that does not support
1043                  * atomic swap/close (LU-6785) */
1044                 rc = migrate_block(fd, fdv);
1045                 goto out;
1046         }
1047
1048         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1049         if (rc < 0) {
1050                 error_loc = "cannot get lease";
1051                 goto out;
1052         }
1053
1054         rc = migrate_nonblock(fd, fdv);
1055         if (rc < 0) {
1056                 llapi_lease_release(fd);
1057                 goto out;
1058         }
1059
1060         /* Atomically put lease, swap layouts and close.
1061          * for a migration we need to check data version on file did
1062          * not change. */
1063         rc = llapi_fswap_layouts(fd, fdv, 0, 0, SWAP_LAYOUTS_CLOSE);
1064         if (rc < 0) {
1065                 error_loc = "cannot swap layout";
1066                 goto out;
1067         }
1068
1069 out:
1070         if (fd >= 0)
1071                 close(fd);
1072
1073         if (fdv >= 0)
1074                 close(fdv);
1075
1076         if (rc < 0)
1077                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1078                         progname, name, error_loc, strerror(-rc));
1079         return rc;
1080 }
1081
1082 static int comp_str2flags(char *string, __u32 *flags, __u32 *neg_flags)
1083 {
1084         char *name;
1085
1086         if (string == NULL)
1087                 return -EINVAL;
1088
1089         *flags = 0;
1090         *neg_flags = 0;
1091         for (name = strtok(string, ","); name; name = strtok(NULL, ",")) {
1092                 bool found = false;
1093                 int i;
1094
1095                 for (i = 0; i < ARRAY_SIZE(comp_flags_table); i++) {
1096                         __u32 comp_flag = comp_flags_table[i].cfn_flag;
1097                         const char *comp_name = comp_flags_table[i].cfn_name;
1098
1099                         if (strcmp(name, comp_name) == 0) {
1100                                 *flags |= comp_flag;
1101                                 found = true;
1102                         } else if (strncmp(name, "^", 1) == 0 &&
1103                                    strcmp(name + 1, comp_name) == 0) {
1104                                 *neg_flags |= comp_flag;
1105                                 found = true;
1106                         }
1107                 }
1108                 if (!found) {
1109                         llapi_printf(LLAPI_MSG_ERROR,
1110                                      "%s: component flag '%s' not supported\n",
1111                                      progname, name);
1112                         return -EINVAL;
1113                 }
1114         }
1115
1116         if (!*flags && !*neg_flags)
1117                 return -EINVAL;
1118
1119         /* don't allow to set and exclude the same flag */
1120         if (*flags & *neg_flags)
1121                 return -EINVAL;
1122
1123         return 0;
1124 }
1125
1126 static int mirror_str2state(char *string, __u16 *state, __u16 *neg_state)
1127 {
1128         if (string == NULL)
1129                 return -EINVAL;
1130
1131         *state = 0;
1132         *neg_state = 0;
1133
1134         if (strncmp(string, "^", 1) == 0) {
1135                 *neg_state = llapi_layout_string_flags(string + 1);
1136                 if (*neg_state != 0)
1137                         return 0;
1138         } else {
1139                 *state = llapi_layout_string_flags(string);
1140                 if (*state != 0)
1141                         return 0;
1142         }
1143
1144         llapi_printf(LLAPI_MSG_ERROR,
1145                      "%s: mirrored file state '%s' not supported\n",
1146                      progname, string);
1147         return -EINVAL;
1148 }
1149
1150 /**
1151  * struct mirror_args - Command-line arguments for mirror(s).
1152  * @m_count:  Number of mirrors to be created with this layout.
1153  * @m_flags:  Mirror level flags, only 'prefer' is supported.
1154  * @m_layout: Mirror layout.
1155  * @m_file:   A victim file. Its layout will be split and used as a mirror.
1156  * @m_next:   Point to the next node of the list.
1157  *
1158  * Command-line arguments for mirror(s) will be parsed and stored in
1159  * a linked list that consists of this structure.
1160  */
1161 struct mirror_args {
1162         __u32                   m_count;
1163         __u32                   m_flags;
1164         struct llapi_layout     *m_layout;
1165         const char              *m_file;
1166         struct mirror_args      *m_next;
1167 };
1168
1169 static int mirror_sanity_check_flags(struct llapi_layout *layout, void *unused)
1170 {
1171         uint32_t flags;
1172         int rc;
1173
1174         rc = llapi_layout_comp_flags_get(layout, &flags);
1175         if (rc)
1176                 return -errno;
1177
1178         if (flags & LCME_FL_NEG) {
1179                 fprintf(stderr, "error: %s: negative flags are not supported\n",
1180                         progname);
1181                 return -EINVAL;
1182         }
1183
1184         if (flags & LCME_FL_STALE) {
1185                 fprintf(stderr, "error: %s: setting '%s' is not supported\n",
1186                         progname, comp_flags_table[LCME_FL_STALE].cfn_name);
1187                 return -EINVAL;
1188         }
1189
1190         return LLAPI_LAYOUT_ITER_CONT;
1191 }
1192
1193 static inline int mirror_sanity_check_one(struct llapi_layout *layout)
1194 {
1195         uint64_t start, end;
1196         uint64_t pattern;
1197         int rc;
1198
1199         /* LU-10112: do not support dom+flr in phase 1 */
1200         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
1201         if (rc)
1202                 return -errno;
1203
1204         rc = llapi_layout_pattern_get(layout, &pattern);
1205         if (rc)
1206                 return -errno;
1207
1208         if (pattern == LOV_PATTERN_MDT || pattern == LLAPI_LAYOUT_MDT) {
1209                 fprintf(stderr, "error: %s: doesn't support dom+flr for now\n",
1210                         progname);
1211                 return -ENOTSUP;
1212         }
1213
1214         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_LAST);
1215         if (rc)
1216                 return -errno;
1217
1218         rc = llapi_layout_comp_extent_get(layout, &start, &end);
1219         if (rc)
1220                 return -errno;
1221
1222         if (end != LUSTRE_EOF) {
1223                 fprintf(stderr, "error: %s: mirror layout doesn't reach eof\n",
1224                         progname);
1225                 return -EINVAL;
1226         }
1227
1228         rc = llapi_layout_comp_iterate(layout, mirror_sanity_check_flags, NULL);
1229         return rc;
1230 }
1231
1232 /**
1233  * enum mirror_flags - Flags for extending a mirrored file.
1234  * @MF_NO_VERIFY: Indicates not to verify the mirror(s) from victim file(s)
1235  *             in case the victim file(s) contains the same data as the
1236  *             original mirrored file.
1237  * @MF_DESTROY: Indicates to delete the mirror from the mirrored file.
1238  *
1239  * Flags for extending a mirrored file.
1240  */
1241 enum mirror_flags {
1242         MF_NO_VERIFY    = 0x1,
1243         MF_DESTROY      = 0x2,
1244 };
1245
1246 /**
1247  * mirror_create_sanity_check() - Check mirror list.
1248  * @list:  A linked list that stores the mirror arguments.
1249  *
1250  * This function does a sanity check on @list for creating
1251  * a mirrored file.
1252  *
1253  * Return: 0 on success or a negative error code on failure.
1254  */
1255 static int mirror_create_sanity_check(const char *fname,
1256                                       struct mirror_args *list)
1257 {
1258         int rc = 0;
1259         bool has_m_file = false;
1260         bool has_m_layout = false;
1261
1262         if (list == NULL)
1263                 return -EINVAL;
1264
1265         if (fname) {
1266                 struct llapi_layout *layout;
1267
1268                 layout = llapi_layout_get_by_path(fname, 0);
1269                 if (!layout) {
1270                         fprintf(stderr,
1271                                 "error: %s: file '%s' couldn't get layout\n",
1272                                 progname, fname);
1273                         return -ENODATA;
1274                 }
1275
1276                 rc = mirror_sanity_check_one(layout);
1277                 llapi_layout_free(layout);
1278
1279                 if (rc)
1280                         return rc;
1281         }
1282
1283         while (list != NULL) {
1284                 if (list->m_file != NULL) {
1285                         has_m_file = true;
1286                         llapi_layout_free(list->m_layout);
1287
1288                         list->m_layout =
1289                                 llapi_layout_get_by_path(list->m_file, 0);
1290                         if (list->m_layout == NULL) {
1291                                 fprintf(stderr,
1292                                         "error: %s: file '%s' has no layout\n",
1293                                         progname, list->m_file);
1294                                 return -ENODATA;
1295                         }
1296                 } else {
1297                         has_m_layout = true;
1298                         if (list->m_layout == NULL) {
1299                                 fprintf(stderr, "error: %s: no mirror layout\n",
1300                                         progname);
1301                                 return -EINVAL;
1302                         }
1303                 }
1304
1305                 rc = mirror_sanity_check_one(list->m_layout);
1306                 if (rc)
1307                         return rc;
1308
1309                 list = list->m_next;
1310         }
1311
1312         if (has_m_file && has_m_layout) {
1313                 fprintf(stderr,
1314                         "error: %s: -f <victim_file> option should not be specified with setstripe options\n",
1315                         progname);
1316                 return -EINVAL;
1317         }
1318
1319         return 0;
1320 }
1321
1322 static int mirror_set_flags(struct llapi_layout *layout, void *cbdata)
1323 {
1324         __u32 mirror_flags = *(__u32 *)cbdata;
1325         uint32_t flags;
1326         int rc;
1327
1328         rc = llapi_layout_comp_flags_get(layout, &flags);
1329         if (rc < 0)
1330                 return rc;
1331
1332         if (!flags) {
1333                 rc = llapi_layout_comp_flags_set(layout, mirror_flags);
1334                 if (rc)
1335                         return rc;
1336         }
1337
1338         return LLAPI_LAYOUT_ITER_CONT;
1339 }
1340
1341 /**
1342  * mirror_create() - Create a mirrored file.
1343  * @fname:        The file to be created.
1344  * @mirror_list:  A linked list that stores the mirror arguments.
1345  *
1346  * This function creates a mirrored file @fname with the mirror(s)
1347  * from @mirror_list.
1348  *
1349  * Return: 0 on success or a negative error code on failure.
1350  */
1351 static int mirror_create(char *fname, struct mirror_args *mirror_list)
1352 {
1353         struct llapi_layout *layout = NULL;
1354         struct mirror_args *cur_mirror = NULL;
1355         uint16_t mirror_count = 0;
1356         int i = 0;
1357         int rc = 0;
1358
1359         rc = mirror_create_sanity_check(NULL, mirror_list);
1360         if (rc)
1361                 return rc;
1362
1363         cur_mirror = mirror_list;
1364         while (cur_mirror != NULL) {
1365                 rc = llapi_layout_comp_iterate(cur_mirror->m_layout,
1366                                                mirror_set_flags,
1367                                                &cur_mirror->m_flags);
1368                 if (rc) {
1369                         rc = -errno;
1370                         fprintf(stderr, "%s: failed to set mirror flags\n",
1371                                 progname);
1372                         goto error;
1373                 }
1374
1375                 for (i = 0; i < cur_mirror->m_count; i++) {
1376                         rc = llapi_layout_merge(&layout, cur_mirror->m_layout);
1377                         if (rc) {
1378                                 rc = -errno;
1379                                 fprintf(stderr, "error: %s: "
1380                                         "merge layout failed: %s\n",
1381                                         progname, strerror(errno));
1382                                 goto error;
1383                         }
1384                 }
1385                 mirror_count += cur_mirror->m_count;
1386                 cur_mirror = cur_mirror->m_next;
1387         }
1388
1389         if (layout == NULL) {
1390                 fprintf(stderr, "error: %s: layout is NULL\n", progname);
1391                 return -EINVAL;
1392         }
1393
1394         rc = llapi_layout_mirror_count_set(layout, mirror_count);
1395         if (rc) {
1396                 rc = -errno;
1397                 fprintf(stderr, "error: %s: set mirror count failed: %s\n",
1398                         progname, strerror(errno));
1399                 goto error;
1400         }
1401
1402         rc = lfs_component_create(fname, O_CREAT | O_WRONLY, 0644,
1403                                   layout);
1404         if (rc >= 0) {
1405                 close(rc);
1406                 rc = 0;
1407         }
1408
1409 error:
1410         llapi_layout_free(layout);
1411         return rc;
1412 }
1413
1414 /**
1415  * Compare files and check lease on @fd.
1416  *
1417  * \retval bytes number of bytes are the same
1418  */
1419 static ssize_t mirror_file_compare(int fd, int fdv)
1420 {
1421         const size_t buflen = 4 * 1024 * 1024; /* 4M */
1422         void *buf;
1423         ssize_t bytes_done = 0;
1424         ssize_t bytes_read = 0;
1425
1426         buf = malloc(buflen * 2);
1427         if (!buf)
1428                 return -ENOMEM;
1429
1430         while (1) {
1431                 if (!llapi_lease_check(fd)) {
1432                         bytes_done = -EBUSY;
1433                         break;
1434                 }
1435
1436                 bytes_read = read(fd, buf, buflen);
1437                 if (bytes_read <= 0)
1438                         break;
1439
1440                 if (bytes_read != read(fdv, buf + buflen, buflen))
1441                         break;
1442
1443                 /* XXX: should compute the checksum on each buffer and then
1444                  * compare checksum to avoid cache collision */
1445                 if (memcmp(buf, buf + buflen, bytes_read))
1446                         break;
1447
1448                 bytes_done += bytes_read;
1449         }
1450
1451         free(buf);
1452
1453         return bytes_done;
1454 }
1455
1456 static int mirror_extend_file(const char *fname, const char *victim_file,
1457                               enum mirror_flags mirror_flags)
1458 {
1459         int fd = -1;
1460         int fdv = -1;
1461         struct stat stbuf;
1462         struct stat stbuf_v;
1463         struct ll_ioc_lease *data = NULL;
1464         int rc;
1465
1466         fd = open(fname, O_RDWR);
1467         if (fd < 0) {
1468                 error_loc = "open source file";
1469                 rc = -errno;
1470                 goto out;
1471         }
1472
1473         fdv = open(victim_file, O_RDWR);
1474         if (fdv < 0) {
1475                 error_loc = "open target file";
1476                 rc = -errno;
1477                 goto out;
1478         }
1479
1480         if (fstat(fd, &stbuf) || fstat(fdv, &stbuf_v)) {
1481                 error_loc = "stat source or target file";
1482                 rc = -errno;
1483                 goto out;
1484         }
1485
1486         if (stbuf.st_dev != stbuf_v.st_dev) {
1487                 error_loc = "stat source and target file";
1488                 rc = -EXDEV;
1489                 goto out;
1490         }
1491
1492         /* mirrors should be of the same size */
1493         if (stbuf.st_size != stbuf_v.st_size) {
1494                 error_loc = "file sizes don't match";
1495                 rc = -EINVAL;
1496                 goto out;
1497         }
1498
1499         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1500         if (rc < 0) {
1501                 error_loc = "cannot get lease";
1502                 goto out;
1503         }
1504
1505         if (!(mirror_flags & MF_NO_VERIFY)) {
1506                 ssize_t ret;
1507                 /* mirrors should have the same contents */
1508                 ret = mirror_file_compare(fd, fdv);
1509                 if (ret != stbuf.st_size) {
1510                         error_loc = "file busy or contents don't match";
1511                         rc = ret < 0 ? ret : -EINVAL;
1512                         goto out;
1513                 }
1514         }
1515
1516         /* Get rid of caching pages from clients */
1517         rc = llapi_file_flush(fd);
1518         if (rc < 0) {
1519                 error_loc = "cannot get data version";
1520                 goto out;
1521         }
1522
1523         rc = llapi_file_flush(fdv);
1524         if (rc < 0) {
1525                 error_loc = "cannot get data version";
1526                 goto out;
1527
1528         }
1529
1530         /* Make sure we keep original atime/mtime values */
1531         rc = migrate_copy_timestamps(fd, fdv);
1532         if (rc < 0) {
1533                 error_loc = "cannot copy timestamp";
1534                 goto out;
1535         }
1536
1537         /* Atomically put lease, merge layouts and close. */
1538         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1539         if (!data) {
1540                 error_loc = "memory allocation";
1541                 goto out;
1542         }
1543         data->lil_mode = LL_LEASE_UNLCK;
1544         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1545         data->lil_count = 1;
1546         data->lil_ids[0] = fdv;
1547         rc = llapi_lease_set(fd, data);
1548         if (rc < 0) {
1549                 error_loc = "cannot merge layout";
1550                 goto out;
1551         } else if (rc == 0) {
1552                 rc = -EBUSY;
1553                 error_loc = "lost lease lock";
1554                 goto out;
1555         }
1556         rc = 0;
1557
1558 out:
1559         if (data)
1560                 free(data);
1561         if (fd >= 0)
1562                 close(fd);
1563         if (fdv >= 0)
1564                 close(fdv);
1565         if (!rc)
1566                 (void) unlink(victim_file);
1567         if (rc < 0)
1568                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1569                         progname, fname, error_loc, strerror(-rc));
1570         return rc;
1571 }
1572
1573 static int mirror_extend_layout(char *name, struct llapi_layout *layout)
1574 {
1575         struct ll_ioc_lease *data = NULL;
1576         int fd = -1;
1577         int fdv = -1;
1578         int rc;
1579
1580         rc = migrate_open_files(name, 0, NULL, layout, &fd, &fdv);
1581         if (rc < 0)
1582                 goto out;
1583
1584         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1585         if (rc < 0) {
1586                 error_loc = "cannot get lease";
1587                 goto out;
1588         }
1589
1590         rc = migrate_nonblock(fd, fdv);
1591         if (rc < 0) {
1592                 llapi_lease_release(fd);
1593                 goto out;
1594         }
1595
1596         /* Atomically put lease, merge layouts and close. */
1597         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1598         if (!data) {
1599                 error_loc = "memory allocation";
1600                 goto out;
1601         }
1602         data->lil_mode = LL_LEASE_UNLCK;
1603         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1604         data->lil_count = 1;
1605         data->lil_ids[0] = fdv;
1606         rc = llapi_lease_set(fd, data);
1607         if (rc < 0) {
1608                 error_loc = "cannot merge layout";
1609                 goto out;
1610         } else if (rc == 0) {
1611                 rc = -EBUSY;
1612                 error_loc = "lost lease lock";
1613                 goto out;
1614         }
1615         rc = 0;
1616
1617 out:
1618         if (data)
1619                 free(data);
1620         if (fd >= 0)
1621                 close(fd);
1622         if (fdv >= 0)
1623                 close(fdv);
1624         if (rc < 0)
1625                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1626                         progname, name, error_loc, strerror(-rc));
1627         return rc;
1628 }
1629
1630 static int mirror_extend(char *fname, struct mirror_args *mirror_list,
1631                          enum mirror_flags mirror_flags)
1632 {
1633         int rc;
1634
1635         rc = mirror_create_sanity_check(fname, mirror_list);
1636         if (rc)
1637                 return rc;
1638
1639         while (mirror_list) {
1640                 if (mirror_list->m_file != NULL) {
1641                         rc = mirror_extend_file(fname, mirror_list->m_file,
1642                                                 mirror_flags);
1643                 } else {
1644                         __u32 mirror_count = mirror_list->m_count;
1645
1646                         while (mirror_count > 0) {
1647                                 rc = mirror_extend_layout(fname,
1648                                                         mirror_list->m_layout);
1649                                 if (rc)
1650                                         break;
1651
1652                                 --mirror_count;
1653                         }
1654                 }
1655                 if (rc)
1656                         break;
1657
1658                 mirror_list = mirror_list->m_next;
1659         }
1660
1661         return rc;
1662 }
1663
1664 static int verify_id(struct llapi_layout *layout, void *cbdata)
1665 {
1666         uint32_t id;
1667         int rc;
1668
1669         rc = llapi_layout_mirror_id_get(layout, &id);
1670         if (rc < 0)
1671                 return rc;
1672
1673         if ((__u16)id == *(__u16 *)cbdata)
1674                 return LLAPI_LAYOUT_ITER_STOP;
1675
1676         return LLAPI_LAYOUT_ITER_CONT;
1677 }
1678
1679 static int mirror_split(const char *fname, __u16 mirror_id,
1680                         enum mirror_flags mflags, const char *victim_file)
1681 {
1682         struct llapi_layout *layout;
1683         char parent[PATH_MAX];
1684         char victim[PATH_MAX];
1685         int flags = O_CREAT | O_EXCL | O_LOV_DELAY_CREATE | O_NOFOLLOW;
1686         char *ptr;
1687         struct ll_ioc_lease *data;
1688         uint16_t mirror_count;
1689         int mdt_index;
1690         int fd, fdv;
1691         int rc;
1692
1693         /* check fname contains mirror with mirror_id */
1694         layout = llapi_layout_get_by_path(fname, 0);
1695         if (!layout) {
1696                 fprintf(stderr,
1697                         "error %s: file '%s' couldn't get layout\n",
1698                         progname, fname);
1699                 return -EINVAL;
1700         }
1701
1702         rc = mirror_sanity_check_one(layout);
1703         if (rc)
1704                 goto free_layout;
1705
1706         rc = llapi_layout_mirror_count_get(layout, &mirror_count);
1707         if (rc) {
1708                 fprintf(stderr,
1709                         "error %s: file '%s' couldn't get mirror count\n",
1710                         progname, fname);
1711                 goto free_layout;
1712         }
1713         if (mirror_count < 2) {
1714                 fprintf(stderr,
1715                         "error %s: file '%s' has %d component, cannot split\n",
1716                         progname, fname, mirror_count);
1717                 goto free_layout;
1718         }
1719
1720         rc = llapi_layout_comp_iterate(layout, verify_id, &mirror_id);
1721         if (rc < 0) {
1722                 fprintf(stderr, "error %s: failed to iterate layout of '%s'\n",
1723                         progname, fname);
1724                 goto free_layout;
1725         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
1726                 fprintf(stderr,
1727                      "error %s: file '%s' does not contain mirror with id %u\n",
1728                         progname, fname, mirror_id);
1729                 goto free_layout;
1730         }
1731
1732         fd = open(fname, O_RDWR);
1733         if (fd < 0) {
1734                 fprintf(stderr,
1735                         "error %s: open file '%s' failed: %s\n",
1736                         progname, fname, strerror(errno));
1737                 goto free_layout;
1738         }
1739
1740         /* get victim file directory pathname */
1741         if (strlen(fname) > sizeof(parent) - 1) {
1742                 fprintf(stderr, "error %s: file name of '%s' too long\n",
1743                         progname, fname);
1744                 rc = -ERANGE;
1745                 goto close_fd;
1746         }
1747         strncpy(parent, fname, sizeof(parent));
1748         ptr = strrchr(parent, '/');
1749         if (ptr == NULL) {
1750                 if (getcwd(parent, sizeof(parent)) == NULL) {
1751                         fprintf(stderr, "error %s: getcwd failed: %s\n",
1752                                 progname, strerror(errno));
1753                         rc = -errno;
1754                         goto close_fd;
1755                 }
1756         } else {
1757                 if (ptr == parent)
1758                         ptr = parent + 1;
1759                 *ptr = '\0';
1760         }
1761
1762         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
1763         if (rc < 0) {
1764                 fprintf(stderr, "%s: cannot get MDT index of '%s'\n",
1765                         progname, fname);
1766                 goto close_fd;
1767         }
1768
1769         if (victim_file == NULL) {
1770                 /* use a temp file to store the splitted layout */
1771                 if (mflags & MF_DESTROY) {
1772                         fdv = llapi_create_volatile_idx(parent, mdt_index,
1773                                                         O_LOV_DELAY_CREATE);
1774                 } else {
1775                         snprintf(victim, sizeof(victim), "%s.mirror~%u",
1776                                  fname, mirror_id);
1777                         fdv = open(victim, flags, S_IRUSR | S_IWUSR);
1778                 }
1779         } else {
1780                 /* user specified victim file */
1781                 fdv = open(victim_file, flags, S_IRUSR | S_IWUSR);
1782         }
1783
1784         if (fdv < 0) {
1785                 fprintf(stderr,
1786                         "error %s: create victim file failed: %s\n",
1787                         progname, strerror(errno));
1788                 goto close_fd;
1789         }
1790
1791         /* get lease lock of fname */
1792         rc = llapi_lease_acquire(fd, LL_LEASE_WRLCK);
1793         if (rc < 0) {
1794                 fprintf(stderr,
1795                         "error %s: cannot get lease of file '%s': %d\n",
1796                         progname, fname, rc);
1797                 goto close_victim;
1798         }
1799
1800         /* Atomatically put lease, split layouts and close. */
1801         data = malloc(offsetof(typeof(*data), lil_ids[2]));
1802         if (!data) {
1803                 rc = -ENOMEM;
1804                 goto close_victim;
1805         }
1806
1807         data->lil_mode = LL_LEASE_UNLCK;
1808         data->lil_flags = LL_LEASE_LAYOUT_SPLIT;
1809         data->lil_count = 2;
1810         data->lil_ids[0] = fdv;
1811         data->lil_ids[1] = mirror_id;
1812         rc = llapi_lease_set(fd, data);
1813         if (rc <= 0) {
1814                 if (rc == 0) /* lost lease lock */
1815                         rc = -EBUSY;
1816                 fprintf(stderr,
1817                         "error %s: cannot split '%s': %s\n",
1818                         progname, fname, strerror(-rc));
1819         } else {
1820                 rc = 0;
1821         }
1822         free(data);
1823
1824 close_victim:
1825         close(fdv);
1826 close_fd:
1827         close(fd);
1828 free_layout:
1829         llapi_layout_free(layout);
1830         return rc;
1831 }
1832
1833 /**
1834  * Parse a string containing an target index list into an array of integers.
1835  *
1836  * The input string contains a comma delimited list of individual
1837  * indices and ranges, for example "1,2-4,7". Add the indices into the
1838  * \a tgts array and remove duplicates.
1839  *
1840  * \param[out] tgts    array to store indices in
1841  * \param[in] size     size of \a tgts array
1842  * \param[in] offset   starting index in \a tgts
1843  * \param[in] arg      string containing OST index list
1844  *
1845  * \retval positive    number of indices in \a tgts
1846  * \retval -EINVAL     unable to parse \a arg
1847  */
1848 static int parse_targets(__u32 *tgts, int size, int offset, char *arg)
1849 {
1850         int rc;
1851         int nr = offset;
1852         int slots = size - offset;
1853         char *ptr = NULL;
1854         bool end_of_loop;
1855
1856         if (arg == NULL)
1857                 return -EINVAL;
1858
1859         end_of_loop = false;
1860         while (!end_of_loop) {
1861                 int start_index;
1862                 int end_index;
1863                 int i;
1864                 char *endptr = NULL;
1865
1866                 rc = -EINVAL;
1867
1868                 ptr = strchrnul(arg, ',');
1869
1870                 end_of_loop = *ptr == '\0';
1871                 *ptr = '\0';
1872
1873                 start_index = strtol(arg, &endptr, 0);
1874                 if (endptr == arg) /* no data at all */
1875                         break;
1876                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
1877                         break;
1878
1879                 end_index = start_index;
1880                 if (*endptr == '-') {
1881                         end_index = strtol(endptr + 1, &endptr, 0);
1882                         if (*endptr != '\0')
1883                                 break;
1884                         if (end_index < start_index)
1885                                 break;
1886                 }
1887
1888                 for (i = start_index; i <= end_index && slots > 0; i++) {
1889                         int j;
1890
1891                         /* remove duplicate */
1892                         for (j = 0; j < offset; j++) {
1893                                 if (tgts[j] == i)
1894                                         break;
1895                         }
1896                         if (j == offset) { /* no duplicate */
1897                                 tgts[nr++] = i;
1898                                 --slots;
1899                         }
1900                 }
1901                 if (slots == 0 && i < end_index)
1902                         break;
1903
1904                 *ptr = ',';
1905                 arg = ++ptr;
1906                 offset = nr;
1907                 rc = 0;
1908         }
1909         if (!end_of_loop && ptr != NULL)
1910                 *ptr = ',';
1911
1912         return rc < 0 ? rc : nr;
1913 }
1914
1915 struct lfs_setstripe_args {
1916         unsigned long long       lsa_comp_end;
1917         unsigned long long       lsa_stripe_size;
1918         long long                lsa_stripe_count;
1919         long long                lsa_stripe_off;
1920         __u32                    lsa_comp_flags;
1921         __u32                    lsa_comp_neg_flags;
1922         unsigned long long       lsa_pattern;
1923         unsigned int             lsa_mirror_count;
1924         int                      lsa_nr_tgts;
1925         bool                     lsa_first_comp;
1926         __u32                   *lsa_tgts;
1927         char                    *lsa_pool_name;
1928 };
1929
1930 static inline void setstripe_args_init(struct lfs_setstripe_args *lsa)
1931 {
1932         unsigned int mirror_count = lsa->lsa_mirror_count;
1933         bool first_comp = lsa->lsa_first_comp;
1934
1935         memset(lsa, 0, sizeof(*lsa));
1936
1937         lsa->lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
1938         lsa->lsa_stripe_count = LLAPI_LAYOUT_DEFAULT;
1939         lsa->lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
1940         lsa->lsa_pattern = LLAPI_LAYOUT_RAID0;
1941         lsa->lsa_pool_name = NULL;
1942
1943         lsa->lsa_mirror_count = mirror_count;
1944         lsa->lsa_first_comp = first_comp;
1945 }
1946
1947 /**
1948  * setstripe_args_init_inherit() - Initialize and inherit stripe options.
1949  * @lsa: Stripe options to be initialized and inherited.
1950  *
1951  * This function initializes stripe options in @lsa and inherit
1952  * stripe_size, stripe_count and OST pool_name options.
1953  *
1954  * Return: void.
1955  */
1956 static inline void setstripe_args_init_inherit(struct lfs_setstripe_args *lsa)
1957 {
1958         unsigned long long stripe_size;
1959         long long stripe_count;
1960         char *pool_name = NULL;
1961
1962         stripe_size = lsa->lsa_stripe_size;
1963         stripe_count = lsa->lsa_stripe_count;
1964         pool_name = lsa->lsa_pool_name;
1965
1966         setstripe_args_init(lsa);
1967
1968         lsa->lsa_stripe_size = stripe_size;
1969         lsa->lsa_stripe_count = stripe_count;
1970         lsa->lsa_pool_name = pool_name;
1971 }
1972
1973 static inline bool setstripe_args_specified(struct lfs_setstripe_args *lsa)
1974 {
1975         return (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT ||
1976                 lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ||
1977                 lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
1978                 lsa->lsa_pattern != LLAPI_LAYOUT_RAID0 ||
1979                 lsa->lsa_pool_name != NULL ||
1980                 lsa->lsa_comp_end != 0);
1981 }
1982
1983 /**
1984  * comp_args_to_layout() - Create or extend a composite layout.
1985  * @composite:       Pointer to the composite layout.
1986  * @lsa:             Stripe options for the new component.
1987  *
1988  * This function creates or extends a composite layout by adding a new
1989  * component with stripe options from @lsa.
1990  *
1991  * Return: 0 on success or an error code on failure.
1992  */
1993 static int comp_args_to_layout(struct llapi_layout **composite,
1994                                struct lfs_setstripe_args *lsa,
1995                                bool set_extent)
1996 {
1997         struct llapi_layout *layout = *composite;
1998         uint64_t prev_end = 0;
1999         int i = 0, rc;
2000
2001         if (layout == NULL) {
2002                 layout = llapi_layout_alloc();
2003                 if (layout == NULL) {
2004                         fprintf(stderr, "Alloc llapi_layout failed. %s\n",
2005                                 strerror(errno));
2006                         return -ENOMEM;
2007                 }
2008                 *composite = layout;
2009         } else {
2010                 uint64_t start;
2011
2012                 /* Get current component extent, current component
2013                  * must be the tail component. */
2014                 rc = llapi_layout_comp_extent_get(layout, &start, &prev_end);
2015                 if (rc) {
2016                         fprintf(stderr, "Get comp extent failed. %s\n",
2017                                 strerror(errno));
2018                         return rc;
2019                 }
2020
2021                 if (lsa->lsa_first_comp)
2022                         prev_end = 0;
2023
2024                 if (lsa->lsa_first_comp)
2025                         rc = llapi_layout_add_first_comp(layout);
2026                 else
2027                         rc = llapi_layout_comp_add(layout);
2028                 if (rc) {
2029                         fprintf(stderr, "Add component failed. %s\n",
2030                                 strerror(errno));
2031                         return rc;
2032                 }
2033         }
2034         /* reset lsa_first_comp */
2035         lsa->lsa_first_comp = false;
2036
2037         if (set_extent) {
2038                 rc = llapi_layout_comp_extent_set(layout, prev_end,
2039                                                   lsa->lsa_comp_end);
2040                 if (rc) {
2041                         fprintf(stderr, "Set extent [%lu, %llu) failed. %s\n",
2042                                 prev_end, lsa->lsa_comp_end, strerror(errno));
2043                         return rc;
2044                 }
2045         }
2046
2047         /* Data-on-MDT component setting */
2048         if (lsa->lsa_pattern == LLAPI_LAYOUT_MDT) {
2049                 /* In case of Data-on-MDT patterns the only extra option
2050                  * applicable is stripe size option. */
2051                 if (lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
2052                         fprintf(stderr, "Option 'stripe-count' can't be "
2053                                 "specified with Data-on-MDT component: %lld\n",
2054                                 lsa->lsa_stripe_count);
2055                         return -EINVAL;
2056                 }
2057                 if (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT) {
2058                         fprintf(stderr, "Option 'stripe-size' can't be "
2059                                 "specified with Data-on-MDT component: %llu\n",
2060                                 lsa->lsa_stripe_size);
2061                         return -EINVAL;
2062                 }
2063                 if (lsa->lsa_nr_tgts != 0) {
2064                         fprintf(stderr, "Option 'ost-list' can't be specified "
2065                                 "with Data-on-MDT component: '%i'\n",
2066                                 lsa->lsa_nr_tgts);
2067                         return -EINVAL;
2068                 }
2069                 if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT) {
2070                         fprintf(stderr, "Option 'stripe-offset' can't be "
2071                                 "specified with Data-on-MDT component: %lld\n",
2072                                 lsa->lsa_stripe_off);
2073                         return -EINVAL;
2074                 }
2075                 if (lsa->lsa_pool_name != 0) {
2076                         fprintf(stderr, "Option 'pool' can't be specified "
2077                                 "with Data-on-MDT component: '%s'\n",
2078                                 lsa->lsa_pool_name);
2079                         return -EINVAL;
2080                 }
2081
2082                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2083                 if (rc) {
2084                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2085                                 lsa->lsa_pattern, strerror(errno));
2086                         return rc;
2087                 }
2088                 /* Data-on-MDT component has always single stripe up to end */
2089                 lsa->lsa_stripe_size = lsa->lsa_comp_end;
2090         }
2091
2092         rc = llapi_layout_stripe_size_set(layout, lsa->lsa_stripe_size);
2093         if (rc) {
2094                 fprintf(stderr, "Set stripe size %llu failed: %s\n",
2095                         lsa->lsa_stripe_size, strerror(errno));
2096                 return rc;
2097         }
2098
2099         rc = llapi_layout_stripe_count_set(layout, lsa->lsa_stripe_count);
2100         if (rc) {
2101                 fprintf(stderr, "Set stripe count %lld failed: %s\n",
2102                         lsa->lsa_stripe_count, strerror(errno));
2103                 return rc;
2104         }
2105
2106         rc = llapi_layout_comp_flags_set(layout, lsa->lsa_comp_flags);
2107         if (rc) {
2108                 fprintf(stderr, "Set flags 0x%x failed: %s\n",
2109                         lsa->lsa_comp_flags, strerror(errno));
2110                 return rc;
2111         }
2112
2113         if (lsa->lsa_pool_name != NULL) {
2114                 rc = llapi_layout_pool_name_set(layout, lsa->lsa_pool_name);
2115                 if (rc) {
2116                         fprintf(stderr, "Set pool name: %s failed. %s\n",
2117                                 lsa->lsa_pool_name, strerror(errno));
2118                         return rc;
2119                 }
2120         } else {
2121                 rc = llapi_layout_pool_name_set(layout, "");
2122                 if (rc) {
2123                         fprintf(stderr, "Clear pool name failed: %s\n",
2124                                 strerror(errno));
2125                         return rc;
2126                 }
2127         }
2128
2129         if (lsa->lsa_nr_tgts > 0) {
2130                 if (lsa->lsa_stripe_count > 0 &&
2131                     lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
2132                     lsa->lsa_stripe_count != LLAPI_LAYOUT_WIDE &&
2133                     lsa->lsa_nr_tgts != lsa->lsa_stripe_count) {
2134                         fprintf(stderr, "stripe_count(%lld) != nr_tgts(%d)\n",
2135                                 lsa->lsa_stripe_count, lsa->lsa_nr_tgts);
2136                         return -EINVAL;
2137                 }
2138                 for (i = 0; i < lsa->lsa_nr_tgts; i++) {
2139                         rc = llapi_layout_ost_index_set(layout, i,
2140                                                         lsa->lsa_tgts[i]);
2141                         if (rc)
2142                                 break;
2143                 }
2144         } else if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT &&
2145                    lsa->lsa_stripe_off != -1) {
2146                 rc = llapi_layout_ost_index_set(layout, 0, lsa->lsa_stripe_off);
2147         }
2148         if (rc) {
2149                 fprintf(stderr, "Set ost index %d failed. %s\n",
2150                         i, strerror(errno));
2151                 return rc;
2152         }
2153
2154         return 0;
2155 }
2156
2157 static int build_component(struct llapi_layout **layout,
2158                            struct lfs_setstripe_args *lsa, bool set_extent)
2159 {
2160         int rc;
2161
2162         rc = comp_args_to_layout(layout, lsa, set_extent);
2163         if (rc)
2164                 return rc;
2165
2166         if (lsa->lsa_mirror_count > 0) {
2167                 rc = llapi_layout_mirror_count_set(*layout,
2168                                                    lsa->lsa_mirror_count);
2169                 if (rc)
2170                         return rc;
2171
2172                 rc = llapi_layout_flags_set(*layout, LCM_FL_RDONLY);
2173                 if (rc)
2174                         return rc;
2175                 lsa->lsa_mirror_count = 0;
2176         }
2177
2178         return rc;
2179 }
2180
2181 static int build_layout_from_yaml_node(struct cYAML *node,
2182                                        struct llapi_layout **layout,
2183                                        struct lfs_setstripe_args *lsa,
2184                                        __u32 *osts)
2185 {
2186         char *string;
2187         int rc = 0;
2188
2189         while (node) {
2190                 string = node->cy_string;
2191                 /* skip leading lmm_ if present, to simplify parsing */
2192                 if (string != NULL && strncmp(string, "lmm_", 4) == 0)
2193                         string += 4;
2194
2195                 if (node->cy_type == CYAML_TYPE_STRING) {
2196                         if (!strcmp(string, "lcme_extent.e_end")) {
2197                                 if (!strcmp(node->cy_valuestring, "EOF") ||
2198                                     !strcmp(node->cy_valuestring, "eof"))
2199                                         lsa->lsa_comp_end = LUSTRE_EOF;
2200                         } else if (!strcmp(string, "pool")) {
2201                                 lsa->lsa_pool_name = node->cy_valuestring;
2202                         } else if (!strcmp(string, "pattern")) {
2203                                 if (!strcmp(node->cy_valuestring, "mdt"))
2204                                         lsa->lsa_pattern = LLAPI_LAYOUT_MDT;
2205                         }
2206                 } else if (node->cy_type == CYAML_TYPE_NUMBER) {
2207                         if (!strcmp(string, "lcm_mirror_count")) {
2208                                 lsa->lsa_mirror_count = node->cy_valueint;
2209                         } else if (!strcmp(string, "lcme_extent.e_start")) {
2210                                 if (node->cy_valueint != 0 || *layout != NULL) {
2211                                         rc = build_component(layout, lsa, true);
2212                                         if (rc)
2213                                                 return rc;
2214                                 }
2215
2216                                 if (node->cy_valueint == 0)
2217                                         lsa->lsa_first_comp = true;
2218
2219                                 /* initialize lsa */
2220                                 setstripe_args_init(lsa);
2221                                 lsa->lsa_tgts = osts;
2222                         } else if (!strcmp(string, "lcme_extent.e_end")) {
2223                                 if (node->cy_valueint == -1)
2224                                         lsa->lsa_comp_end = LUSTRE_EOF;
2225                                 else
2226                                         lsa->lsa_comp_end = node->cy_valueint;
2227                         } else if (!strcmp(string, "stripe_count")) {
2228                                 lsa->lsa_stripe_count = node->cy_valueint;
2229                         } else if (!strcmp(string, "stripe_size")) {
2230                                 lsa->lsa_stripe_size = node->cy_valueint;
2231                         } else if (!strcmp(string, "stripe_offset")) {
2232                                 lsa->lsa_stripe_off = node->cy_valueint;
2233                         } else if (!strcmp(string, "l_ost_idx")) {
2234                                 osts[lsa->lsa_nr_tgts] = node->cy_valueint;
2235                                 lsa->lsa_nr_tgts++;
2236                         }
2237                 } else if (node->cy_type == CYAML_TYPE_OBJECT) {
2238                         /* go deep to sub blocks */
2239                         rc = build_layout_from_yaml_node(node->cy_child, layout,
2240                                                          lsa, osts);
2241                         if (rc)
2242                                 return rc;
2243                 }
2244                 node = node->cy_next;
2245         }
2246
2247         return rc;
2248 }
2249
2250 static int lfs_comp_create_from_yaml(char *template,
2251                                      struct llapi_layout **layout,
2252                                      struct lfs_setstripe_args *lsa,
2253                                      __u32 *osts)
2254 {
2255         struct cYAML *tree = NULL, *err_rc = NULL;
2256         int rc = 0;
2257
2258         tree = cYAML_build_tree(template, NULL, 0, &err_rc, false);
2259         if (!tree) {
2260                 fprintf(stderr, "%s: cannot parse YAML file %s\n",
2261                         progname, template);
2262                 cYAML_build_error(-EINVAL, -1, "yaml", "from comp yaml",
2263                                   "can't parse", &err_rc);
2264                 cYAML_print_tree2file(stderr, err_rc);
2265                 cYAML_free_tree(err_rc);
2266                 rc = -EINVAL;
2267                 goto err;
2268         }
2269
2270         /* initialize lsa for plain file */
2271         setstripe_args_init(lsa);
2272         lsa->lsa_tgts = osts;
2273
2274         rc = build_layout_from_yaml_node(tree, layout, lsa, osts);
2275         if (rc) {
2276                 fprintf(stderr, "%s: cannot build layout from YAML file %s.\n",
2277                         progname, template);
2278                 goto err;
2279         } else {
2280                 rc = build_component(layout, lsa, *layout != NULL);
2281         }
2282         /* clean clean lsa */
2283         setstripe_args_init(lsa);
2284
2285 err:
2286         if (tree)
2287                 cYAML_free_tree(tree);
2288         return rc;
2289 }
2290
2291 /* In 'lfs setstripe --component-add' mode, we need to fetch the extent
2292  * end of the last component in the existing file, and adjust the
2293  * first extent start of the components to be added accordingly. */
2294 static int adjust_first_extent(char *fname, struct llapi_layout *layout)
2295 {
2296         struct llapi_layout *head;
2297         uint64_t start, end, stripe_size, prev_end = 0;
2298         int rc;
2299
2300         if (layout == NULL) {
2301                 fprintf(stderr,
2302                         "%s setstripe: layout must be specified\n",
2303                         progname);
2304                 return -EINVAL;
2305         }
2306
2307         errno = 0;
2308         head = llapi_layout_get_by_path(fname, 0);
2309         if (head == NULL) {
2310                 fprintf(stderr,
2311                         "%s setstripe: cannot read layout from '%s': %s\n",
2312                         progname, fname, strerror(errno));
2313                 return -EINVAL;
2314         } else if (errno == ENODATA) {
2315                 /* file without LOVEA, this component-add will be turned
2316                  * into a component-create. */
2317                 llapi_layout_free(head);
2318                 return -ENODATA;
2319         } else if (!llapi_layout_is_composite(head)) {
2320                 fprintf(stderr, "%s setstripe: '%s' not a composite file\n",
2321                         progname, fname);
2322                 llapi_layout_free(head);
2323                 return -EINVAL;
2324         }
2325
2326         rc = llapi_layout_comp_extent_get(head, &start, &prev_end);
2327         if (rc) {
2328                 fprintf(stderr, "%s setstripe: cannot get prev extent: %s\n",
2329                         progname, strerror(errno));
2330                 llapi_layout_free(head);
2331                 return rc;
2332         }
2333
2334         llapi_layout_free(head);
2335
2336         /* Make sure we use the first component of the layout to be added. */
2337         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
2338         if (rc < 0) {
2339                 fprintf(stderr,
2340                         "%s setstripe: cannot move component cursor: %s\n",
2341                         progname, strerror(errno));
2342                 return rc;
2343         }
2344
2345         rc = llapi_layout_comp_extent_get(layout, &start, &end);
2346         if (rc) {
2347                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
2348                         progname, strerror(errno));
2349                 return rc;
2350         }
2351
2352         if (start > prev_end || end <= prev_end) {
2353                 fprintf(stderr,
2354                         "%s setstripe: first extent [%lu, %lu) not adjacent with extent end %lu\n",
2355                         progname, start, end, prev_end);
2356                 return -EINVAL;
2357         }
2358
2359         rc = llapi_layout_stripe_size_get(layout, &stripe_size);
2360         if (rc) {
2361                 fprintf(stderr, "%s setstripe: cannot get stripe size: %s\n",
2362                         progname, strerror(errno));
2363                 return rc;
2364         }
2365
2366         if (stripe_size != LLAPI_LAYOUT_DEFAULT &&
2367             (prev_end & (stripe_size - 1))) {
2368                 fprintf(stderr,
2369                         "%s setstripe: stripe size %lu not aligned with %lu\n",
2370                         progname, stripe_size, prev_end);
2371                 return -EINVAL;
2372         }
2373
2374         rc = llapi_layout_comp_extent_set(layout, prev_end, end);
2375         if (rc) {
2376                 fprintf(stderr,
2377                         "%s setstripe: cannot set component extent [%lu, %lu): %s\n",
2378                         progname, prev_end, end, strerror(errno));
2379                 return rc;
2380         }
2381
2382         return 0;
2383 }
2384
2385 static inline bool arg_is_eof(char *arg)
2386 {
2387         return !strncmp(arg, "-1", strlen("-1")) ||
2388                !strncmp(arg, "EOF", strlen("EOF")) ||
2389                !strncmp(arg, "eof", strlen("eof"));
2390 }
2391
2392 /**
2393  * lfs_mirror_alloc() - Allocate a mirror argument structure.
2394  *
2395  * Return: Valid mirror_args pointer on success and
2396  *         NULL if memory allocation fails.
2397  */
2398 static struct mirror_args *lfs_mirror_alloc(void)
2399 {
2400         struct mirror_args *mirror = NULL;
2401
2402         while (1) {
2403                 mirror = calloc(1, sizeof(*mirror));
2404                 if (mirror != NULL)
2405                         break;
2406
2407                 sleep(1);
2408         }
2409
2410         return mirror;
2411 }
2412
2413 /**
2414  * lfs_mirror_free() - Free memory allocated for a mirror argument
2415  *                     structure.
2416  * @mirror: Previously allocated mirror argument structure by
2417  *          lfs_mirror_alloc().
2418  *
2419  * Free memory allocated for @mirror.
2420  *
2421  * Return: void.
2422  */
2423 static void lfs_mirror_free(struct mirror_args *mirror)
2424 {
2425         if (mirror->m_layout != NULL)
2426                 llapi_layout_free(mirror->m_layout);
2427         free(mirror);
2428 }
2429
2430 /**
2431  * lfs_mirror_list_free() - Free memory allocated for a mirror list.
2432  * @mirror_list: Previously allocated mirror list.
2433  *
2434  * Free memory allocated for @mirror_list.
2435  *
2436  * Return: void.
2437  */
2438 static void lfs_mirror_list_free(struct mirror_args *mirror_list)
2439 {
2440         struct mirror_args *next_mirror = NULL;
2441
2442         while (mirror_list != NULL) {
2443                 next_mirror = mirror_list->m_next;
2444                 lfs_mirror_free(mirror_list);
2445                 mirror_list = next_mirror;
2446         }
2447 }
2448
2449 enum {
2450         LFS_POOL_OPT = 3,
2451         LFS_COMP_COUNT_OPT,
2452         LFS_COMP_START_OPT,
2453         LFS_COMP_FLAGS_OPT,
2454         LFS_COMP_DEL_OPT,
2455         LFS_COMP_SET_OPT,
2456         LFS_COMP_ADD_OPT,
2457         LFS_COMP_NO_VERIFY_OPT,
2458         LFS_PROJID_OPT,
2459         LFS_MIRROR_FLAGS_OPT,
2460         LFS_MIRROR_ID_OPT,
2461         LFS_MIRROR_STATE_OPT,
2462 };
2463
2464 /* functions */
2465 static int lfs_setstripe_internal(int argc, char **argv,
2466                                   enum setstripe_origin opc)
2467 {
2468         struct lfs_setstripe_args        lsa = { 0 };
2469         struct llapi_stripe_param       *param = NULL;
2470         struct find_param                migrate_mdt_param = {
2471                 .fp_max_depth = -1,
2472                 .fp_mdt_index = -1,
2473         };
2474         char                            *fname;
2475         int                              result = 0;
2476         int                              result2 = 0;
2477         char                            *end;
2478         int                              c;
2479         int                              delete = 0;
2480         char                            *mdt_idx_arg = NULL;
2481         unsigned long long               size_units = 1;
2482         bool                             migrate_mode = false;
2483         bool                             migration_block = false;
2484         __u64                            migration_flags = 0;
2485         __u32                            osts[LOV_MAX_STRIPE_COUNT] = { 0 };
2486         int                              comp_del = 0, comp_set = 0;
2487         int                              comp_add = 0;
2488         __u32                            comp_id = 0;
2489         struct llapi_layout             *layout = NULL;
2490         struct llapi_layout             **lpp = &layout;
2491         bool                             mirror_mode = false;
2492         bool                             has_m_file = false;
2493         __u32                            mirror_count = 0;
2494         enum mirror_flags                mirror_flags = 0;
2495         struct mirror_args              *mirror_list = NULL;
2496         struct mirror_args              *new_mirror = NULL;
2497         struct mirror_args              *last_mirror = NULL;
2498         __u16                            mirror_id = 0;
2499         char                             cmd[PATH_MAX];
2500         bool from_yaml = false;
2501         char *template = NULL;
2502
2503         struct option long_opts[] = {
2504 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
2505         /* --block is only valid in migrate mode */
2506         { .val = 'b',   .name = "block",        .has_arg = no_argument },
2507         { .val = LFS_COMP_ADD_OPT,
2508                         .name = "comp-add",     .has_arg = no_argument },
2509         { .val = LFS_COMP_ADD_OPT,
2510                         .name = "component-add", .has_arg = no_argument },
2511         { .val = LFS_COMP_DEL_OPT,
2512                         .name = "comp-del",     .has_arg = no_argument },
2513         { .val = LFS_COMP_DEL_OPT,
2514                         .name = "component-del", .has_arg = no_argument },
2515         { .val = LFS_COMP_FLAGS_OPT,
2516                         .name = "comp-flags",   .has_arg = required_argument },
2517         { .val = LFS_COMP_FLAGS_OPT,
2518                         .name = "component-flags",
2519                                                 .has_arg = required_argument },
2520         { .val = LFS_COMP_SET_OPT,
2521                         .name = "comp-set",     .has_arg = no_argument },
2522         { .val = LFS_COMP_SET_OPT,
2523                         .name = "component-set",
2524                                                 .has_arg = no_argument},
2525         { .val = LFS_COMP_NO_VERIFY_OPT,
2526                         .name = "no-verify",    .has_arg = no_argument},
2527         { .val = LFS_MIRROR_FLAGS_OPT,
2528                         .name = "flags",        .has_arg = required_argument},
2529         { .val = LFS_MIRROR_ID_OPT,
2530                         .name = "mirror-id",    .has_arg = required_argument},
2531         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument},
2532         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument},
2533 /* find { .val = 'C',   .name = "ctime",        .has_arg = required_argument }*/
2534         { .val = 'd',   .name = "delete",       .has_arg = no_argument},
2535         { .val = 'd',   .name = "destroy",      .has_arg = no_argument},
2536         /* --non-direct is only valid in migrate mode */
2537         { .val = 'D',   .name = "non-direct",   .has_arg = no_argument },
2538         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument},
2539         { .val = 'E',   .name = "component-end",
2540                                                 .has_arg = required_argument},
2541         { .val = 'f',   .name = "file",         .has_arg = required_argument },
2542 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
2543 /* find { .val = 'g',   .name = "gid",          .has_arg = no_argument }, */
2544 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
2545 /* dirstripe { .val = 'H', .name = "mdt-hash",  .has_arg = required_argument }*/
2546         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument},
2547         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument},
2548         { .val = 'I',   .name = "comp-id",      .has_arg = required_argument},
2549         { .val = 'I',   .name = "component-id", .has_arg = required_argument},
2550         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
2551         { .val = 'm',   .name = "mdt",          .has_arg = required_argument},
2552         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument},
2553         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument},
2554         /* --non-block is only valid in migrate mode */
2555         { .val = 'n',   .name = "non-block",    .has_arg = no_argument },
2556         { .val = 'N',   .name = "mirror-count", .has_arg = optional_argument},
2557         { .val = 'o',   .name = "ost",          .has_arg = required_argument },
2558 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
2559         { .val = 'o',   .name = "ost-list",     .has_arg = required_argument },
2560         { .val = 'o',   .name = "ost_list",     .has_arg = required_argument },
2561 #endif
2562         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
2563 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
2564 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
2565 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
2566 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
2567         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
2568         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
2569 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
2570 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
2571 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
2572 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
2573         /* --verbose is only valid in migrate mode */
2574         { .val = 'v',   .name = "verbose",      .has_arg = no_argument},
2575         { .val = 'y',   .name = "yaml",         .has_arg = required_argument },
2576         { .name = NULL } };
2577
2578         setstripe_args_init(&lsa);
2579
2580         migrate_mode = (opc == SO_MIGRATE);
2581         mirror_mode = (opc == SO_MIRROR_CREATE || opc == SO_MIRROR_EXTEND);
2582
2583         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
2584         progname = cmd;
2585         while ((c = getopt_long(argc, argv, "bc:dDE:f:i:I:m:N::no:p:L:s:S:vy:",
2586                                 long_opts, NULL)) >= 0) {
2587                 switch (c) {
2588                 case 0:
2589                         /* Long options. */
2590                         break;
2591                 case LFS_COMP_ADD_OPT:
2592                         comp_add = 1;
2593                         break;
2594                 case LFS_COMP_DEL_OPT:
2595                         comp_del = 1;
2596                         break;
2597                 case LFS_COMP_FLAGS_OPT:
2598                         result = comp_str2flags(optarg, &lsa.lsa_comp_flags,
2599                                                 &lsa.lsa_comp_neg_flags);
2600                         if (result != 0)
2601                                 goto usage_error;
2602                         if (mirror_mode && lsa.lsa_comp_neg_flags) {
2603                                 fprintf(stderr, "%s: inverted flags are not supported\n",
2604                                         progname);
2605                                 goto usage_error;
2606                         }
2607                         if (lsa.lsa_comp_neg_flags & LCME_FL_STALE) {
2608                                 fprintf(stderr,
2609                                         "%s: cannot clear 'stale' flags from component. Please use lfs-mirror-resync(1) instead\n",
2610                                         progname);
2611                                 result = -EINVAL;
2612                                 goto error;
2613                         }
2614
2615                         break;
2616                 case LFS_COMP_SET_OPT:
2617                         comp_set = 1;
2618                         break;
2619                 case LFS_COMP_NO_VERIFY_OPT:
2620                         mirror_flags |= MF_NO_VERIFY;
2621                         break;
2622                 case LFS_MIRROR_ID_OPT:
2623                         mirror_id = strtoul(optarg, &end, 0);
2624                         if (*end != '\0' || mirror_id == 0) {
2625                                 fprintf(stderr,
2626                                         "%s %s: invalid mirror ID '%s'\n",
2627                                         progname, argv[0], optarg);
2628                                 goto usage_error;
2629                         }
2630                         break;
2631                 case LFS_MIRROR_FLAGS_OPT: {
2632                         __u32 flags;
2633
2634                         if (!mirror_mode || !last_mirror) {
2635                                 fprintf(stderr, "error: %s: --flags must be specified with --mirror-count|-N option\n",
2636                                         progname);
2637                                 goto usage_error;
2638                         }
2639
2640                         result = comp_str2flags(optarg, &last_mirror->m_flags,
2641                                                 &flags);
2642                         if (result != 0)
2643                                 goto usage_error;
2644
2645                         if (flags) {
2646                                 fprintf(stderr, "%s: inverted flags are not supported\n",
2647                                         progname);
2648                                 result = -EINVAL;
2649                                 goto usage_error;
2650                         }
2651                         if (last_mirror->m_flags & ~LCME_USER_FLAGS) {
2652                                 fprintf(stderr,
2653                                         "%s: unsupported mirror flags: %s\n",
2654                                         progname, optarg);
2655                                 result = -EINVAL;
2656                                 goto error;
2657                         }
2658                         break;
2659                 }
2660                 case 'b':
2661                         if (!migrate_mode) {
2662                                 fprintf(stderr,
2663                                         "%s %s: -b|--block valid only for migrate command\n",
2664                                         progname, argv[0]);
2665                                 goto usage_error;
2666                         }
2667                         migration_block = true;
2668                         break;
2669                 case 'c':
2670                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
2671                         if (*end != '\0') {
2672                                 fprintf(stderr,
2673                                         "%s %s: invalid stripe count '%s'\n",
2674                                         progname, argv[0], optarg);
2675                                 goto usage_error;
2676                         }
2677
2678                         if (lsa.lsa_stripe_count == -1)
2679                                 lsa.lsa_stripe_count = LLAPI_LAYOUT_WIDE;
2680                         break;
2681                 case 'd':
2682                         /* delete the default striping pattern */
2683                         delete = 1;
2684                         if (opc == SO_MIRROR_SPLIT) {
2685                                 if (has_m_file) {
2686                                         fprintf(stderr,
2687                                               "%s %s: -d cannot used with -f\n",
2688                                                 progname, argv[0]);
2689                                         goto usage_error;
2690                                 }
2691                                 mirror_flags |= MF_DESTROY;
2692                         }
2693                         break;
2694                 case 'D':
2695                         if (!migrate_mode) {
2696                                 fprintf(stderr,
2697                                         "%s %s: -D|--non-direct is valid "
2698                                         "only for migrate command\n",
2699                                         progname, argv[0]);
2700                                 goto usage_error;
2701                         }
2702                         migration_flags |= MIGRATION_NONDIRECT;
2703                         break;
2704                 case 'E':
2705                         if (lsa.lsa_comp_end != 0) {
2706                                 result = comp_args_to_layout(lpp, &lsa, true);
2707                                 if (result) {
2708                                         fprintf(stderr,
2709                                                 "%s %s: invalid layout\n",
2710                                                 progname, argv[0]);
2711                                         goto usage_error;
2712                                 }
2713
2714                                 setstripe_args_init_inherit(&lsa);
2715                         }
2716
2717                         if (arg_is_eof(optarg)) {
2718                                 lsa.lsa_comp_end = LUSTRE_EOF;
2719                         } else {
2720                                 result = llapi_parse_size(optarg,
2721                                                         &lsa.lsa_comp_end,
2722                                                         &size_units, 0);
2723                                 if (result) {
2724                                         fprintf(stderr,
2725                                                 "%s %s: invalid component end '%s'\n",
2726                                                 progname, argv[0], optarg);
2727                                         goto usage_error;
2728                                 }
2729                         }
2730                         break;
2731                 case 'i':
2732                         lsa.lsa_stripe_off = strtol(optarg, &end, 0);
2733                         if (*end != '\0') {
2734                                 fprintf(stderr,
2735                                         "%s %s: invalid stripe offset '%s'\n",
2736                                         progname, argv[0], optarg);
2737                                 goto usage_error;
2738                         }
2739                         if (lsa.lsa_stripe_off == -1)
2740                                 lsa.lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2741                         break;
2742                 case 'I':
2743                         comp_id = strtoul(optarg, &end, 0);
2744                         if (*end != '\0' || comp_id == 0 ||
2745                             comp_id > LCME_ID_MAX) {
2746                                 fprintf(stderr,
2747                                         "%s %s: invalid component ID '%s'\n",
2748                                         progname, argv[0], optarg);
2749                                 goto usage_error;
2750                         }
2751                         break;
2752                 case 'f':
2753                         if (opc != SO_MIRROR_EXTEND && opc != SO_MIRROR_SPLIT) {
2754                                 fprintf(stderr,
2755                                         "error: %s: invalid option: %s\n",
2756                                         progname, argv[optopt + 1]);
2757                                 goto usage_error;
2758                         }
2759                         if (opc == SO_MIRROR_EXTEND) {
2760                                 if (last_mirror == NULL) {
2761                                         fprintf(stderr,
2762                                 "error: %s: '-N' must exist in front of '%s'\n",
2763                                                 progname, argv[optopt + 1]);
2764                                         goto usage_error;
2765                                 }
2766                                 last_mirror->m_file = optarg;
2767                                 last_mirror->m_count = 1;
2768                         } else {
2769                                 /* mirror split */
2770                                 if (mirror_list == NULL)
2771                                         mirror_list = lfs_mirror_alloc();
2772                                 mirror_list->m_file = optarg;
2773                         }
2774                         has_m_file = true;
2775                         break;
2776                 case 'L':
2777                         if (strcmp(argv[optind - 1], "mdt") == 0) {
2778                                 /* Can be only the first component */
2779                                 if (layout != NULL) {
2780                                         result = -EINVAL;
2781                                         fprintf(stderr, "error: 'mdt' layout "
2782                                                 "can be only the first one\n");
2783                                         goto error;
2784                                 }
2785                                 if (lsa.lsa_comp_end > (1ULL << 30)) { /* 1Gb */
2786                                         result = -EFBIG;
2787                                         fprintf(stderr, "error: 'mdt' layout "
2788                                                 "size is too big\n");
2789                                         goto error;
2790                                 }
2791                                 lsa.lsa_pattern = LLAPI_LAYOUT_MDT;
2792                         } else if (strcmp(argv[optind - 1], "raid0") != 0) {
2793                                 result = -EINVAL;
2794                                 fprintf(stderr, "error: layout '%s' is "
2795                                         "unknown, supported layouts are: "
2796                                         "'mdt', 'raid0'\n", argv[optind]);
2797                                 goto error;
2798                         }
2799                         break;
2800                 case 'm':
2801                         if (!migrate_mode) {
2802                                 fprintf(stderr,
2803                                         "%s %s: -m|--mdt-index valid only for migrate command\n",
2804                                         progname, argv[0]);
2805                                 goto usage_error;
2806                         }
2807                         mdt_idx_arg = optarg;
2808                         break;
2809                 case 'n':
2810                         if (!migrate_mode) {
2811                                 fprintf(stderr,
2812                                         "%s %s: -n|--non-block valid only for migrate command\n",
2813                                         progname, argv[0]);
2814                                 goto usage_error;
2815                         }
2816                         migration_flags |= MIGRATION_NONBLOCK;
2817                         break;
2818                 case 'N':
2819                         if (opc == SO_SETSTRIPE) {
2820                                 opc = SO_MIRROR_CREATE;
2821                                 mirror_mode = true;
2822                         }
2823                         mirror_count = 1;
2824                         if (optarg != NULL) {
2825                                 mirror_count = strtoul(optarg, &end, 0);
2826                                 if (*end != '\0' || mirror_count == 0) {
2827                                         fprintf(stderr,
2828                                                 "error: %s: bad mirror count: %s\n",
2829                                                 progname, optarg);
2830                                         result = -EINVAL;
2831                                         goto error;
2832                                 }
2833                         }
2834
2835                         new_mirror = lfs_mirror_alloc();
2836                         new_mirror->m_count = mirror_count;
2837
2838                         if (mirror_list == NULL)
2839                                 mirror_list = new_mirror;
2840
2841                         if (last_mirror != NULL) {
2842                                 /* wrap up last mirror */
2843                                 if (lsa.lsa_comp_end == 0)
2844                                         lsa.lsa_comp_end = LUSTRE_EOF;
2845
2846                                 result = comp_args_to_layout(lpp, &lsa, true);
2847                                 if (result) {
2848                                         lfs_mirror_free(new_mirror);
2849                                         goto error;
2850                                 }
2851
2852                                 setstripe_args_init_inherit(&lsa);
2853
2854                                 last_mirror->m_next = new_mirror;
2855                         }
2856
2857                         last_mirror = new_mirror;
2858                         lpp = &last_mirror->m_layout;
2859                         break;
2860                 case 'o':
2861 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
2862                         if (strcmp(argv[optind - 1], "--ost-list") == 0)
2863                                 fprintf(stderr, "warning: '--ost-list' is "
2864                                         "deprecated, use '--ost' instead\n");
2865 #endif
2866                         lsa.lsa_nr_tgts = parse_targets(osts,
2867                                                 sizeof(osts) / sizeof(__u32),
2868                                                 lsa.lsa_nr_tgts, optarg);
2869                         if (lsa.lsa_nr_tgts < 0) {
2870                                 fprintf(stderr,
2871                                         "%s %s: invalid OST target(s) '%s'\n",
2872                                         progname, argv[0], optarg);
2873                                 goto usage_error;
2874                         }
2875
2876                         lsa.lsa_tgts = osts;
2877                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
2878                                 lsa.lsa_stripe_off = osts[0];
2879                         break;
2880                 case 'p':
2881                         if (optarg == NULL)
2882                                 goto usage_error;
2883                         lsa.lsa_pool_name = optarg;
2884
2885                         if (strlen(lsa.lsa_pool_name) == 0 ||
2886                             strncmp(lsa.lsa_pool_name, "none",
2887                                     LOV_MAXPOOLNAME) == 0)
2888                                 lsa.lsa_pool_name = NULL;
2889                         break;
2890                 case 'S':
2891                         result = llapi_parse_size(optarg, &lsa.lsa_stripe_size,
2892                                                   &size_units, 0);
2893                         if (result) {
2894                                 fprintf(stderr,
2895                                         "%s %s: invalid stripe size '%s'\n",
2896                                         progname, argv[0], optarg);
2897                                 goto usage_error;
2898                         }
2899                         break;
2900                 case 'v':
2901                         if (!migrate_mode) {
2902                                 fprintf(stderr,
2903                                         "%s %s: -v|--verbose valid only for migrate command\n",
2904                                         progname, argv[0]);
2905                                 goto usage_error;
2906                         }
2907                         migrate_mdt_param.fp_verbose = VERBOSE_DETAIL;
2908                         break;
2909                 case 'y':
2910                         from_yaml = true;
2911                         template = optarg;
2912                         break;
2913                 default:
2914                         fprintf(stderr, "%s %s: unrecognized option '%s'\n",
2915                                 progname, argv[0], argv[optind - 1]);
2916                         goto usage_error;
2917                 }
2918         }
2919
2920         fname = argv[optind];
2921
2922         if (optind == argc) {
2923                 fprintf(stderr, "%s %s: FILE must be specified\n",
2924                         progname, argv[0]);
2925                 goto usage_error;
2926         }
2927
2928         if (mirror_mode && mirror_count == 0) {
2929                 fprintf(stderr,
2930                         "error: %s: --mirror-count|-N option is required\n",
2931                         progname);
2932                 result = -EINVAL;
2933                 goto error;
2934         }
2935
2936         if (mirror_mode) {
2937                 if (lsa.lsa_comp_end == 0)
2938                         lsa.lsa_comp_end = LUSTRE_EOF;
2939         }
2940
2941         if (lsa.lsa_comp_end != 0) {
2942                 result = comp_args_to_layout(lpp, &lsa, true);
2943                 if (result)
2944                         goto error;
2945         }
2946
2947         if (mirror_flags & MF_NO_VERIFY) {
2948                 if (opc != SO_MIRROR_EXTEND) {
2949                         fprintf(stderr,
2950                                 "error: %s: --no-verify is valid only for lfs mirror extend command\n",
2951                                 progname);
2952                         result = -EINVAL;
2953                         goto error;
2954                 } else if (!has_m_file) {
2955                         fprintf(stderr,
2956                                 "error: %s: --no-verify must be specified with -f <victim_file> option\n",
2957                                 progname);
2958                         result = -EINVAL;
2959                         goto error;
2960                 }
2961         }
2962
2963         /* Only LCME_FL_INIT flags is used in PFL, and it shouldn't be
2964          * altered by user space tool, so we don't need to support the
2965          * --component-set for this moment. */
2966         if (comp_set && !comp_id) {
2967                 fprintf(stderr, "%s %s: --component-set doesn't have component-id set\n",
2968                         progname, argv[0]);
2969                 goto usage_error;
2970         }
2971
2972         if ((delete + comp_set + comp_del + comp_add) > 1) {
2973                 fprintf(stderr,
2974                         "%s %s: options --component-set, --component-del, --component-add and -d are mutually exclusive\n",
2975                         progname, argv[0]);
2976                 goto usage_error;
2977         }
2978
2979         if (delete && (setstripe_args_specified(&lsa) || comp_id != 0 ||
2980                        lsa.lsa_comp_flags != 0 || layout != NULL)) {
2981                 fprintf(stderr,
2982                         "%s %s: option -d is mutually exclusive with -s, -c, -o, -p, -I, -F and -E options\n",
2983                         progname, argv[0]);
2984                 goto usage_error;
2985         }
2986
2987         if ((comp_set || comp_del) &&
2988             (setstripe_args_specified(&lsa) || layout != NULL)) {
2989                 fprintf(stderr,
2990                         "%s %s: options --component-del and --component-set are mutually exclusive when used with -c, -E, -o, -p, or -s\n",
2991                         progname, argv[0]);
2992                 goto usage_error;
2993         }
2994
2995         if (comp_del && comp_id != 0 && lsa.lsa_comp_flags != 0) {
2996                 fprintf(stderr,
2997                         "%s %s: options -I and -F are mutually exclusive when used with --component-del\n",
2998                         progname, argv[0]);
2999                 goto usage_error;
3000         }
3001
3002         if (comp_add || comp_del) {
3003                 struct stat st;
3004
3005                 result = lstat(fname, &st);
3006                 if (result == 0 && S_ISDIR(st.st_mode)) {
3007                         fprintf(stderr,
3008                                 "%s setstripe: cannot use --component-add or --component-del for directory\n",
3009                                 progname);
3010                         goto usage_error;
3011                 }
3012
3013                 if (mirror_mode) {
3014                         fprintf(stderr, "error: %s: can't use --component-add "
3015                                 "or --component-del for mirror operation\n",
3016                                 progname);
3017                         goto usage_error;
3018                 }
3019         }
3020
3021         if (comp_add) {
3022                 if (layout == NULL) {
3023                         fprintf(stderr,
3024                                 "%s %s: option -E must be specified with --component-add\n",
3025                                 progname, argv[0]);
3026                         goto usage_error;
3027                 }
3028
3029                 result = adjust_first_extent(fname, layout);
3030                 if (result == -ENODATA)
3031                         comp_add = 0;
3032                 else if (result != 0)
3033                         goto error;
3034         }
3035
3036         if (from_yaml && (setstripe_args_specified(&lsa) || layout != NULL)) {
3037                 fprintf(stderr, "error: %s: can't specify --yaml with "
3038                         "-c, -S, -i, -o, -p or -E options.\n",
3039                         argv[0]);
3040                 goto error;
3041         }
3042
3043         if (mdt_idx_arg != NULL && optind > 3) {
3044                 fprintf(stderr,
3045                         "%s %s: option -m cannot be used with other options\n",
3046                         progname, argv[0]);
3047                 goto usage_error;
3048         }
3049
3050         if ((migration_flags & MIGRATION_NONBLOCK) && migration_block) {
3051                 fprintf(stderr,
3052                         "%s %s: options --non-block and --block are mutually exclusive\n",
3053                         progname, argv[0]);
3054                 goto usage_error;
3055         }
3056
3057         if (!comp_del && !comp_set && comp_id != 0) {
3058                 fprintf(stderr,
3059                         "%s %s: option -I can only be used with --component-del\n",
3060                         progname, argv[0]);
3061                 goto usage_error;
3062         }
3063
3064         if (mdt_idx_arg != NULL) {
3065                 /* initialize migrate mdt parameters */
3066                 migrate_mdt_param.fp_mdt_index = strtoul(mdt_idx_arg, &end, 0);
3067                 if (*end != '\0') {
3068                         fprintf(stderr, "%s %s: invalid MDT index '%s'\n",
3069                                 progname, argv[0], mdt_idx_arg);
3070                         goto usage_error;
3071                 }
3072                 migrate_mdt_param.fp_migrate = 1;
3073         } else if (layout == NULL) {
3074                 /* initialize stripe parameters */
3075                 param = calloc(1, offsetof(typeof(*param),
3076                                lsp_osts[lsa.lsa_nr_tgts]));
3077                 if (param == NULL) {
3078                         fprintf(stderr,
3079                                 "%s %s: cannot allocate memory for parameters: %s\n",
3080                                 progname, argv[0], strerror(ENOMEM));
3081                         result = -ENOMEM;
3082                         goto error;
3083                 }
3084
3085                 if (lsa.lsa_stripe_size != LLAPI_LAYOUT_DEFAULT)
3086                         param->lsp_stripe_size = lsa.lsa_stripe_size;
3087                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
3088                         if (lsa.lsa_stripe_count == LLAPI_LAYOUT_WIDE)
3089                                 param->lsp_stripe_count = -1;
3090                         else
3091                                 param->lsp_stripe_count = lsa.lsa_stripe_count;
3092                 }
3093                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
3094                         param->lsp_stripe_offset = -1;
3095                 else
3096                         param->lsp_stripe_offset = lsa.lsa_stripe_off;
3097                 param->lsp_pool = lsa.lsa_pool_name;
3098                 param->lsp_is_specific = false;
3099                 if (lsa.lsa_nr_tgts > 0) {
3100                         if (lsa.lsa_stripe_count > 0 &&
3101                             lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
3102                             lsa.lsa_stripe_count != LLAPI_LAYOUT_WIDE &&
3103                             lsa.lsa_nr_tgts != lsa.lsa_stripe_count) {
3104                                 fprintf(stderr, "error: %s: stripe count %lld "
3105                                         "doesn't match the number of OSTs: %d\n"
3106                                         , argv[0], lsa.lsa_stripe_count,
3107                                         lsa.lsa_nr_tgts);
3108                                 free(param);
3109                                 goto usage_error;
3110                         }
3111
3112                         param->lsp_is_specific = true;
3113                         param->lsp_stripe_count = lsa.lsa_nr_tgts;
3114                         memcpy(param->lsp_osts, osts,
3115                                sizeof(*osts) * lsa.lsa_nr_tgts);
3116                 }
3117         }
3118
3119         if (from_yaml) {
3120                 /* generate a layout from a YAML template */
3121                 result = lfs_comp_create_from_yaml(template, &layout,
3122                                                    &lsa, osts);
3123                 if (result) {
3124                         fprintf(stderr, "error: %s: can't create composite "
3125                                 "layout from template file %s\n",
3126                                 argv[0], template);
3127                         goto error;
3128                 }
3129         }
3130
3131         for (fname = argv[optind]; fname != NULL; fname = argv[++optind]) {
3132                 if (mdt_idx_arg != NULL) {
3133                         result = llapi_migrate_mdt(fname, &migrate_mdt_param);
3134                 } else if (migrate_mode) {
3135                         result = lfs_migrate(fname, migration_flags, param,
3136                                              layout);
3137                 } else if (comp_set != 0) {
3138                         result = lfs_component_set(fname, comp_id,
3139                                                    lsa.lsa_comp_flags,
3140                                                    lsa.lsa_comp_neg_flags);
3141                 } else if (comp_del != 0) {
3142                         result = lfs_component_del(fname, comp_id,
3143                                                    lsa.lsa_comp_flags,
3144                                                    lsa.lsa_comp_neg_flags);
3145                 } else if (comp_add != 0) {
3146                         result = lfs_component_add(fname, layout);
3147                 } else if (opc == SO_MIRROR_CREATE) {
3148                         result = mirror_create(fname, mirror_list);
3149                 } else if (opc == SO_MIRROR_EXTEND) {
3150                         result = mirror_extend(fname, mirror_list,
3151                                                mirror_flags);
3152                 } else if (opc == SO_MIRROR_SPLIT) {
3153                         if (mirror_id == 0) {
3154                                 fprintf(stderr,
3155                                         "%s %s: no mirror id is specified\n",
3156                                         progname, argv[0]);
3157                                 goto usage_error;
3158                         }
3159                         result = mirror_split(fname, mirror_id, mirror_flags,
3160                                               has_m_file ? mirror_list->m_file :
3161                                               NULL);
3162                 } else if (layout != NULL) {
3163                         result = lfs_component_create(fname, O_CREAT | O_WRONLY,
3164                                                       0644, layout);
3165                         if (result >= 0) {
3166                                 close(result);
3167                                 result = 0;
3168                         }
3169                 } else {
3170                         result = llapi_file_open_param(fname,
3171                                                        O_CREAT | O_WRONLY,
3172                                                        0644, param);
3173                         if (result >= 0) {
3174                                 close(result);
3175                                 result = 0;
3176                         }
3177                 }
3178                 if (result) {
3179                         /* Save the first error encountered. */
3180                         if (result2 == 0)
3181                                 result2 = result;
3182                         continue;
3183                 }
3184         }
3185
3186         free(param);
3187         llapi_layout_free(layout);
3188         lfs_mirror_list_free(mirror_list);
3189         return result2;
3190 usage_error:
3191         result = CMD_HELP;
3192 error:
3193         llapi_layout_free(layout);
3194         lfs_mirror_list_free(mirror_list);
3195         return result;
3196 }
3197
3198 static int lfs_poollist(int argc, char **argv)
3199 {
3200         if (argc != 2)
3201                 return CMD_HELP;
3202
3203         return llapi_poollist(argv[1]);
3204 }
3205
3206 static int set_time(time_t *time, time_t *set, char *str)
3207 {
3208         time_t t;
3209         int res = 0;
3210
3211         if (str[0] == '+')
3212                 res = 1;
3213         else if (str[0] == '-')
3214                 res = -1;
3215
3216         if (res)
3217                 str++;
3218
3219         t = strtol(str, NULL, 0);
3220         if (*time < t * 24 * 60 * 60) {
3221                 if (res)
3222                         str--;
3223                 fprintf(stderr, "Wrong time '%s' is specified.\n", str);
3224                 return INT_MAX;
3225         }
3226
3227         *set = *time - t * 24 * 60 * 60;
3228         return res;
3229 }
3230 static int name2uid(unsigned int *id, const char *name)
3231 {
3232         struct passwd *passwd;
3233
3234         passwd = getpwnam(name);
3235         if (passwd == NULL)
3236                 return -ENOENT;
3237         *id = passwd->pw_uid;
3238
3239         return 0;
3240 }
3241
3242 static int name2gid(unsigned int *id, const char *name)
3243 {
3244         struct group *group;
3245
3246         group = getgrnam(name);
3247         if (group == NULL)
3248                 return -ENOENT;
3249         *id = group->gr_gid;
3250
3251         return 0;
3252 }
3253
3254 static inline int name2projid(unsigned int *id, const char *name)
3255 {
3256         return -ENOTSUP;
3257 }
3258
3259 static int uid2name(char **name, unsigned int id)
3260 {
3261         struct passwd *passwd;
3262
3263         passwd = getpwuid(id);
3264         if (passwd == NULL)
3265                 return -ENOENT;
3266         *name = passwd->pw_name;
3267
3268         return 0;
3269 }
3270
3271 static inline int gid2name(char **name, unsigned int id)
3272 {
3273         struct group *group;
3274
3275         group = getgrgid(id);
3276         if (group == NULL)
3277                 return -ENOENT;
3278         *name = group->gr_name;
3279
3280         return 0;
3281 }
3282
3283 static int name2layout(__u32 *layout, char *name)
3284 {
3285         char *ptr, *layout_name;
3286
3287         *layout = 0;
3288         for (ptr = name; ; ptr = NULL) {
3289                 layout_name = strtok(ptr, ",");
3290                 if (layout_name == NULL)
3291                         break;
3292                 if (strcmp(layout_name, "released") == 0)
3293                         *layout |= LOV_PATTERN_F_RELEASED;
3294                 else if (strcmp(layout_name, "raid0") == 0)
3295                         *layout |= LOV_PATTERN_RAID0;
3296                 else if (strcmp(layout_name, "mdt") == 0)
3297                         *layout |= LOV_PATTERN_MDT;
3298                 else
3299                         return -1;
3300         }
3301         return 0;
3302 }
3303
3304 static int lfs_find(int argc, char **argv)
3305 {
3306         int c, rc;
3307         int ret = 0;
3308         time_t t;
3309         struct find_param param = {
3310                 .fp_max_depth = -1,
3311                 .fp_quiet = 1,
3312         };
3313         struct option long_opts[] = {
3314         { .val = 'A',   .name = "atime",        .has_arg = required_argument },
3315         { .val = LFS_COMP_COUNT_OPT,
3316                         .name = "comp-count",   .has_arg = required_argument },
3317         { .val = LFS_COMP_COUNT_OPT,
3318                         .name = "component-count",
3319                                                 .has_arg = required_argument },
3320         { .val = LFS_COMP_FLAGS_OPT,
3321                         .name = "comp-flags",   .has_arg = required_argument },
3322         { .val = LFS_COMP_FLAGS_OPT,
3323                         .name = "component-flags",
3324                                                 .has_arg = required_argument },
3325         { .val = LFS_COMP_START_OPT,
3326                         .name = "comp-start",   .has_arg = required_argument },
3327         { .val = LFS_COMP_START_OPT,
3328                         .name = "component-start",
3329                                                 .has_arg = required_argument },
3330         { .val = LFS_MIRROR_STATE_OPT,
3331                         .name = "mirror-state", .has_arg = required_argument },
3332         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument },
3333         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument },
3334         { .val = 'C',   .name = "ctime",        .has_arg = required_argument },
3335 /* getstripe { .val = 'd', .name = "directory", .has_arg = no_argument }, */
3336         { .val = 'D',   .name = "maxdepth",     .has_arg = required_argument },
3337         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument },
3338         { .val = 'E',   .name = "component-end",
3339                                                 .has_arg = required_argument },
3340 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
3341         { .val = 'g',   .name = "gid",          .has_arg = required_argument },
3342         { .val = 'G',   .name = "group",        .has_arg = required_argument },
3343         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
3344         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument },
3345         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument },
3346 /* getstripe { .val = 'I', .name = "comp-id",   .has_arg = required_argument }*/
3347         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
3348         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
3349         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
3350         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument },
3351         { .val = 'M',   .name = "mtime",        .has_arg = required_argument },
3352         { .val = 'n',   .name = "name",         .has_arg = required_argument },
3353         { .val = 'N',   .name = "mirror-count", .has_arg = required_argument },
3354 /* find { .val = 'o'    .name = "or", .has_arg = no_argument }, like find(1) */
3355         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
3356         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
3357         /* no short option for pool yet, can be 'p' after 2.18 */
3358         { .val = LFS_POOL_OPT,
3359                         .name = "pool",         .has_arg = required_argument },
3360         { .val = '0',   .name = "print0",       .has_arg = no_argument },
3361         { .val = 'P',   .name = "print",        .has_arg = no_argument },
3362         { .val = LFS_PROJID_OPT,
3363                         .name = "projid",       .has_arg = required_argument },
3364 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
3365 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
3366 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
3367         { .val = 's',   .name = "size",         .has_arg = required_argument },
3368         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
3369         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
3370         { .val = 't',   .name = "type",         .has_arg = required_argument },
3371         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
3372         { .val = 'u',   .name = "uid",          .has_arg = required_argument },
3373         { .val = 'U',   .name = "user",         .has_arg = required_argument },
3374 /* getstripe { .val = 'v', .name = "verbose",   .has_arg = no_argument }, */
3375 /* getstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
3376         { .name = NULL } };
3377         int pathstart = -1;
3378         int pathend = -1;
3379         int neg_opt = 0;
3380         time_t *xtime;
3381         int *xsign;
3382         int isoption;
3383         char *endptr;
3384
3385         time(&t);
3386
3387         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
3388         while ((c = getopt_long_only(argc, argv,
3389                         "-0A:c:C:D:E:g:G:H:i:L:m:M:n:N:O:Ppqrs:S:t:T:u:U:v",
3390                         long_opts, NULL)) >= 0) {
3391                 xtime = NULL;
3392                 xsign = NULL;
3393                 if (neg_opt)
3394                         --neg_opt;
3395                 /* '!' is part of option */
3396                 /* when getopt_long_only() finds a string which is not
3397                  * an option nor a known option argument it returns 1
3398                  * in that case if we already have found pathstart and pathend
3399                  * (i.e. we have the list of pathnames),
3400                  * the only supported value is "!"
3401                  */
3402                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
3403                 if (!isoption && pathend != -1) {
3404                         fprintf(stderr, "err: %s: filename|dirname must either "
3405                                         "precede options or follow options\n",
3406                                         argv[0]);
3407                         ret = CMD_HELP;
3408                         goto err;
3409                 }
3410                 if (!isoption && pathstart == -1)
3411                         pathstart = optind - 1;
3412                 if (isoption && pathstart != -1 && pathend == -1)
3413                         pathend = optind - 2;
3414                 switch (c) {
3415                 case 0:
3416                         /* Long options. */
3417                         break;
3418                 case 1:
3419                         /* unknown; opt is "!" or path component,
3420                          * checking done above.
3421                          */
3422                         if (strcmp(optarg, "!") == 0)
3423                                 neg_opt = 2;
3424                         break;
3425                 case 'A':
3426                         xtime = &param.fp_atime;
3427                         xsign = &param.fp_asign;
3428                         param.fp_exclude_atime = !!neg_opt;
3429                         /* no break, this falls through to 'C' for ctime */
3430                 case 'C':
3431                         if (c == 'C') {
3432                                 xtime = &param.fp_ctime;
3433                                 xsign = &param.fp_csign;
3434                                 param.fp_exclude_ctime = !!neg_opt;
3435                         }
3436                         /* no break, this falls through to 'M' for mtime */
3437                 case 'M':
3438                         if (c == 'M') {
3439                                 xtime = &param.fp_mtime;
3440                                 xsign = &param.fp_msign;
3441                                 param.fp_exclude_mtime = !!neg_opt;
3442                         }
3443                         rc = set_time(&t, xtime, optarg);
3444                         if (rc == INT_MAX) {
3445                                 ret = -1;
3446                                 goto err;
3447                         }
3448                         if (rc)
3449                                 *xsign = rc;
3450                         break;
3451                 case LFS_COMP_COUNT_OPT:
3452                         if (optarg[0] == '+') {
3453                                 param.fp_comp_count_sign = -1;
3454                                 optarg++;
3455                         } else if (optarg[0] == '-') {
3456                                 param.fp_comp_count_sign =  1;
3457                                 optarg++;
3458                         }
3459
3460                         param.fp_comp_count = strtoul(optarg, &endptr, 0);
3461                         if (*endptr != '\0') {
3462                                 fprintf(stderr, "error: bad component count "
3463                                         "'%s'\n", optarg);
3464                                 goto err;
3465                         }
3466                         param.fp_check_comp_count = 1;
3467                         param.fp_exclude_comp_count = !!neg_opt;
3468                         break;
3469                 case LFS_COMP_FLAGS_OPT:
3470                         rc = comp_str2flags(optarg, &param.fp_comp_flags,
3471                                             &param.fp_comp_neg_flags);
3472                         if (rc) {
3473                                 fprintf(stderr, "error: bad component flags "
3474                                         "'%s'\n", optarg);
3475                                 goto err;
3476                         }
3477                         param.fp_check_comp_flags = 1;
3478                         if (neg_opt) {
3479                                 __u32 flags = param.fp_comp_neg_flags;
3480                                 param.fp_comp_neg_flags = param.fp_comp_flags;
3481                                 param.fp_comp_flags = flags;
3482                         }
3483                         break;
3484                 case LFS_COMP_START_OPT:
3485                         if (optarg[0] == '+') {
3486                                 param.fp_comp_start_sign = -1;
3487                                 optarg++;
3488                         } else if (optarg[0] == '-') {
3489                                 param.fp_comp_start_sign =  1;
3490                                 optarg++;
3491                         }
3492
3493                         rc = llapi_parse_size(optarg, &param.fp_comp_start,
3494                                               &param.fp_comp_start_units, 0);
3495                         if (rc) {
3496                                 fprintf(stderr, "error: bad component start "
3497                                         "'%s'\n", optarg);
3498                                 goto err;
3499                         }
3500                         param.fp_check_comp_start = 1;
3501                         param.fp_exclude_comp_start = !!neg_opt;
3502                         break;
3503                 case LFS_MIRROR_STATE_OPT:
3504                         rc = mirror_str2state(optarg, &param.fp_mirror_state,
3505                                               &param.fp_mirror_neg_state);
3506                         if (rc) {
3507                                 fprintf(stderr,
3508                                         "error: bad mirrored file state '%s'\n",
3509                                         optarg);
3510                                 goto err;
3511                         }
3512                         param.fp_check_mirror_state = 1;
3513                         if (neg_opt) {
3514                                 __u16 state = param.fp_mirror_neg_state;
3515                                 param.fp_mirror_neg_state =
3516                                         param.fp_mirror_state;
3517                                 param.fp_mirror_state = state;
3518                         }
3519                         break;
3520                 case 'c':
3521                         if (optarg[0] == '+') {
3522                                 param.fp_stripe_count_sign = -1;
3523                                 optarg++;
3524                         } else if (optarg[0] == '-') {
3525                                 param.fp_stripe_count_sign =  1;
3526                                 optarg++;
3527                         }
3528
3529                         param.fp_stripe_count = strtoul(optarg, &endptr, 0);
3530                         if (*endptr != '\0') {
3531                                 fprintf(stderr,"error: bad stripe_count '%s'\n",
3532                                         optarg);
3533                                 ret = -1;
3534                                 goto err;
3535                         }
3536                         param.fp_check_stripe_count = 1;
3537                         param.fp_exclude_stripe_count = !!neg_opt;
3538                         break;
3539                 case 'D':
3540                         param.fp_max_depth = strtol(optarg, 0, 0);
3541                         break;
3542                 case 'E':
3543                         if (optarg[0] == '+') {
3544                                 param.fp_comp_end_sign = -1;
3545                                 optarg++;
3546                         } else if (optarg[0] == '-') {
3547                                 param.fp_comp_end_sign =  1;
3548                                 optarg++;
3549                         }
3550
3551                         if (arg_is_eof(optarg)) {
3552                                 param.fp_comp_end = LUSTRE_EOF;
3553                                 param.fp_comp_end_units = 1;
3554                                 rc = 0;
3555                         } else {
3556                                 rc = llapi_parse_size(optarg,
3557                                                 &param.fp_comp_end,
3558                                                 &param.fp_comp_end_units, 0);
3559                         }
3560                         if (rc) {
3561                                 fprintf(stderr, "error: bad component end "
3562                                         "'%s'\n", optarg);
3563                                 goto err;
3564                         }
3565                         param.fp_check_comp_end = 1;
3566                         param.fp_exclude_comp_end = !!neg_opt;
3567                         break;
3568                 case 'g':
3569                 case 'G':
3570                         rc = name2gid(&param.fp_gid, optarg);
3571                         if (rc) {
3572                                 param.fp_gid = strtoul(optarg, &endptr, 10);
3573                                 if (*endptr != '\0') {
3574                                         fprintf(stderr, "Group/GID: %s cannot "
3575                                                 "be found.\n", optarg);
3576                                         ret = -1;
3577                                         goto err;
3578                                 }
3579                         }
3580                         param.fp_exclude_gid = !!neg_opt;
3581                         param.fp_check_gid = 1;
3582                         break;
3583                 case 'H':
3584                         param.fp_hash_type = check_hashtype(optarg);
3585                         if (param.fp_hash_type == 0) {
3586                                 fprintf(stderr, "error: bad hash_type '%s'\n",
3587                                         optarg);
3588                                 ret = -1;
3589                                 goto err;
3590                         }
3591                         param.fp_check_hash_type = 1;
3592                         param.fp_exclude_hash_type = !!neg_opt;
3593                         break;
3594                 case 'L':
3595                         ret = name2layout(&param.fp_layout, optarg);
3596                         if (ret)
3597                                 goto err;
3598                         param.fp_exclude_layout = !!neg_opt;
3599                         param.fp_check_layout = 1;
3600                         break;
3601                 case 'u':
3602                 case 'U':
3603                         rc = name2uid(&param.fp_uid, optarg);
3604                         if (rc) {
3605                                 param.fp_uid = strtoul(optarg, &endptr, 10);
3606                                 if (*endptr != '\0') {
3607                                         fprintf(stderr, "User/UID: %s cannot "
3608                                                 "be found.\n", optarg);
3609                                         ret = -1;
3610                                         goto err;
3611                                 }
3612                         }
3613                         param.fp_exclude_uid = !!neg_opt;
3614                         param.fp_check_uid = 1;
3615                         break;
3616                 case 'n':
3617                         param.fp_pattern = (char *)optarg;
3618                         param.fp_exclude_pattern = !!neg_opt;
3619                         break;
3620                 case 'N':
3621                         if (optarg[0] == '+') {
3622                                 param.fp_mirror_count_sign = -1;
3623                                 optarg++;
3624                         } else if (optarg[0] == '-') {
3625                                 param.fp_mirror_count_sign =  1;
3626                                 optarg++;
3627                         }
3628
3629                         param.fp_mirror_count = strtoul(optarg, &endptr, 0);
3630                         if (*endptr != '\0') {
3631                                 fprintf(stderr,
3632                                         "error: bad mirror count '%s'\n",
3633                                         optarg);
3634                                 goto err;
3635                         }
3636                         param.fp_check_mirror_count = 1;
3637                         param.fp_exclude_mirror_count = !!neg_opt;
3638                         break;
3639                 case 'm':
3640                 case 'i':
3641                 case 'O': {
3642                         char *buf, *token, *next, *p;
3643                         int len = 1;
3644                         void *tmp;
3645
3646                         buf = strdup(optarg);
3647                         if (buf == NULL) {
3648                                 ret = -ENOMEM;
3649                                 goto err;
3650                         }
3651
3652                         param.fp_exclude_obd = !!neg_opt;
3653
3654                         token = buf;
3655                         while (token && *token) {
3656                                 token = strchr(token, ',');
3657                                 if (token) {
3658                                         len++;
3659                                         token++;
3660                                 }
3661                         }
3662                         if (c == 'm') {
3663                                 param.fp_exclude_mdt = !!neg_opt;
3664                                 param.fp_num_alloc_mdts += len;
3665                                 tmp = realloc(param.fp_mdt_uuid,
3666                                               param.fp_num_alloc_mdts *
3667                                               sizeof(*param.fp_mdt_uuid));
3668                                 if (tmp == NULL) {
3669                                         ret = -ENOMEM;
3670                                         goto err_free;
3671                                 }
3672
3673                                 param.fp_mdt_uuid = tmp;
3674                         } else {
3675                                 param.fp_exclude_obd = !!neg_opt;
3676                                 param.fp_num_alloc_obds += len;
3677                                 tmp = realloc(param.fp_obd_uuid,
3678                                               param.fp_num_alloc_obds *
3679                                               sizeof(*param.fp_obd_uuid));
3680                                 if (tmp == NULL) {
3681                                         ret = -ENOMEM;
3682                                         goto err_free;
3683                                 }
3684
3685                                 param.fp_obd_uuid = tmp;
3686                         }
3687                         for (token = buf; token && *token; token = next) {
3688                                 struct obd_uuid *puuid;
3689                                 if (c == 'm') {
3690                                         puuid =
3691                                         &param.fp_mdt_uuid[param.fp_num_mdts++];
3692                                 } else {
3693                                         puuid =
3694                                         &param.fp_obd_uuid[param.fp_num_obds++];
3695                                 }
3696                                 p = strchr(token, ',');
3697                                 next = 0;
3698                                 if (p) {
3699                                         *p = 0;
3700                                         next = p+1;
3701                                 }
3702
3703                                 if (strlen(token) > sizeof(puuid->uuid) - 1) {
3704                                         ret = -E2BIG;
3705                                         goto err_free;
3706                                 }
3707
3708                                 strncpy(puuid->uuid, token,
3709                                         sizeof(puuid->uuid));
3710                         }
3711 err_free:
3712                         if (buf)
3713                                 free(buf);
3714                         break;
3715                 }
3716 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 18, 53, 0)
3717                 case 'p':
3718 #endif
3719                 case LFS_POOL_OPT:
3720                         if (strlen(optarg) > LOV_MAXPOOLNAME) {
3721                                 fprintf(stderr,
3722                                         "Pool name %s is too long (max %d)\n",
3723                                         optarg, LOV_MAXPOOLNAME);
3724                                 ret = -1;
3725                                 goto err;
3726                         }
3727                         /*
3728                          * We do check for empty pool because empty pool
3729                          * is used to find V1 LOV attributes
3730                          */
3731                         strncpy(param.fp_poolname, optarg, LOV_MAXPOOLNAME);
3732                         param.fp_poolname[LOV_MAXPOOLNAME] = '\0';
3733                         param.fp_exclude_pool = !!neg_opt;
3734                         param.fp_check_pool = 1;
3735                         break;
3736 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 14, 53, 0)
3737                 case 'p': /* want this for --pool, to match getstripe/find */
3738                         fprintf(stderr,
3739                                 "warning: -p deprecated, use --print0 or -0\n");
3740 #endif
3741                 case '0':
3742                         param.fp_zero_end = 1;
3743                         break;
3744                 case 'P': /* we always print, this option is a no-op */
3745                         break;
3746                 case LFS_PROJID_OPT:
3747                         rc = name2projid(&param.fp_projid, optarg);
3748                         if (rc) {
3749                                 param.fp_projid = strtoul(optarg, &endptr, 10);
3750                                 if (*endptr != '\0') {
3751                                         fprintf(stderr,
3752                                                 "Invalid project ID: %s",
3753                                                 optarg);
3754                                         ret = -1;
3755                                         goto err;
3756                                 }
3757                         }
3758                         param.fp_exclude_projid = !!neg_opt;
3759                         param.fp_check_projid = 1;
3760                         break;
3761                 case 's':
3762                         if (optarg[0] == '+') {
3763                                 param.fp_size_sign = -1;
3764                                 optarg++;
3765                         } else if (optarg[0] == '-') {
3766                                 param.fp_size_sign =  1;
3767                                 optarg++;
3768                         }
3769
3770                         ret = llapi_parse_size(optarg, &param.fp_size,
3771                                                &param.fp_size_units, 0);
3772                         if (ret) {
3773                                 fprintf(stderr, "error: bad file size '%s'\n",
3774                                         optarg);
3775                                 goto err;
3776                         }
3777                         param.fp_check_size = 1;
3778                         param.fp_exclude_size = !!neg_opt;
3779                         break;
3780                 case 'S':
3781                         if (optarg[0] == '+') {
3782                                 param.fp_stripe_size_sign = -1;
3783                                 optarg++;
3784                         } else if (optarg[0] == '-') {
3785                                 param.fp_stripe_size_sign =  1;
3786                                 optarg++;
3787                         }
3788
3789                         ret = llapi_parse_size(optarg, &param.fp_stripe_size,
3790                                                &param.fp_stripe_size_units, 0);
3791                         if (ret) {
3792                                 fprintf(stderr, "error: bad stripe_size '%s'\n",
3793                                         optarg);
3794                                 goto err;
3795                         }
3796                         param.fp_check_stripe_size = 1;
3797                         param.fp_exclude_stripe_size = !!neg_opt;
3798                         break;
3799                 case 't':
3800                         param.fp_exclude_type = !!neg_opt;
3801                         switch (optarg[0]) {
3802                         case 'b':
3803                                 param.fp_type = S_IFBLK;
3804                                 break;
3805                         case 'c':
3806                                 param.fp_type = S_IFCHR;
3807                                 break;
3808                         case 'd':
3809                                 param.fp_type = S_IFDIR;
3810                                 break;
3811                         case 'f':
3812                                 param.fp_type = S_IFREG;
3813                                 break;
3814                         case 'l':
3815                                 param.fp_type = S_IFLNK;
3816                                 break;
3817                         case 'p':
3818                                 param.fp_type = S_IFIFO;
3819                                 break;
3820                         case 's':
3821                                 param.fp_type = S_IFSOCK;
3822                                 break;
3823                         default:
3824                                 fprintf(stderr, "error: %s: bad type '%s'\n",
3825                                         argv[0], optarg);
3826                                 ret = CMD_HELP;
3827                                 goto err;
3828                         };
3829                         break;
3830                 case 'T':
3831                         if (optarg[0] == '+') {
3832                                 param.fp_mdt_count_sign = -1;
3833                                 optarg++;
3834                         } else if (optarg[0] == '-') {
3835                                 param.fp_mdt_count_sign =  1;
3836                                 optarg++;
3837                         }
3838
3839                         param.fp_mdt_count = strtoul(optarg, &endptr, 0);
3840                         if (*endptr != '\0') {
3841                                 fprintf(stderr, "error: bad mdt_count '%s'\n",
3842                                         optarg);
3843                                 ret = -1;
3844                                 goto err;
3845                         }
3846                         param.fp_check_mdt_count = 1;
3847                         param.fp_exclude_mdt_count = !!neg_opt;
3848                         break;
3849                 default:
3850                         ret = CMD_HELP;
3851                         goto err;
3852                 };
3853         }
3854
3855         if (pathstart == -1) {
3856                 fprintf(stderr, "error: %s: no filename|pathname\n",
3857                         argv[0]);
3858                 ret = CMD_HELP;
3859                 goto err;
3860         } else if (pathend == -1) {
3861                 /* no options */
3862                 pathend = argc;
3863         }
3864
3865         do {
3866                 rc = llapi_find(argv[pathstart], &param);
3867                 if (rc != 0 && ret == 0)
3868                         ret = rc;
3869         } while (++pathstart < pathend);
3870
3871         if (ret)
3872                 fprintf(stderr, "error: %s failed for %s.\n",
3873                         argv[0], argv[optind - 1]);
3874 err:
3875         if (param.fp_obd_uuid && param.fp_num_alloc_obds)
3876                 free(param.fp_obd_uuid);
3877
3878         if (param.fp_mdt_uuid && param.fp_num_alloc_mdts)
3879                 free(param.fp_mdt_uuid);
3880
3881         return ret;
3882 }
3883
3884 static int lfs_getstripe_internal(int argc, char **argv,
3885                                   struct find_param *param)
3886 {
3887         struct option long_opts[] = {
3888 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
3889         { .val = LFS_COMP_COUNT_OPT,
3890                         .name = "comp-count",   .has_arg = no_argument },
3891         { .val = LFS_COMP_COUNT_OPT,
3892                 .name = "component-count",      .has_arg = no_argument },
3893         { .val = LFS_COMP_FLAGS_OPT,
3894                         .name = "comp-flags",   .has_arg = optional_argument },
3895         { .val = LFS_COMP_FLAGS_OPT,
3896                 .name = "component-flags",      .has_arg = optional_argument },
3897         { .val = LFS_COMP_START_OPT,
3898                         .name = "comp-start",   .has_arg = optional_argument },
3899         { .val = LFS_COMP_START_OPT,
3900                 .name = "component-start",      .has_arg = optional_argument },
3901         { .val = 'c',   .name = "stripe-count", .has_arg = no_argument },
3902         { .val = 'c',   .name = "stripe_count", .has_arg = no_argument },
3903 /* find { .val = 'C',   .name = "ctime",        .has_arg = required_argument }*/
3904         { .val = 'd',   .name = "directory",    .has_arg = no_argument },
3905         { .val = 'D',   .name = "default",      .has_arg = no_argument },
3906         { .val = 'E',   .name = "comp-end",     .has_arg = optional_argument },
3907         { .val = 'E',   .name = "component-end", .has_arg = optional_argument },
3908         { .val = 'F',   .name = "fid",          .has_arg = no_argument },
3909         { .val = 'g',   .name = "generation",   .has_arg = no_argument },
3910 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
3911 /* dirstripe { .val = 'H', .name = "mdt-hash",  .has_arg = required_argument }*/
3912         { .val = 'i',   .name = "stripe-index", .has_arg = no_argument },
3913         { .val = 'i',   .name = "stripe_index", .has_arg = no_argument },
3914         { .val = 'I',   .name = "comp-id",      .has_arg = optional_argument },
3915         { .val = 'I',   .name = "component-id", .has_arg = optional_argument },
3916         { .val = 'L',   .name = "layout",       .has_arg = no_argument },
3917         { .val = 'm',   .name = "mdt",          .has_arg = no_argument },
3918         { .val = 'm',   .name = "mdt-index",    .has_arg = no_argument },
3919         { .val = 'm',   .name = "mdt_index",    .has_arg = no_argument },
3920 /* find { .val = 'M',   .name = "mtime",        .has_arg = required_argument }*/
3921 /* find { .val = 'n',   .name = "name",         .has_arg = required_argument }*/
3922         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
3923         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
3924         { .val = 'p',   .name = "pool",         .has_arg = no_argument },
3925 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
3926         { .val = 'q',   .name = "quiet",        .has_arg = no_argument },
3927         { .val = 'r',   .name = "recursive",    .has_arg = no_argument },
3928         { .val = 'R',   .name = "raw",          .has_arg = no_argument },
3929         { .val = 'S',   .name = "stripe-size",  .has_arg = no_argument },
3930         { .val = 'S',   .name = "stripe_size",  .has_arg = no_argument },
3931 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
3932 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
3933 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
3934 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
3935         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
3936         { .val = 'y',   .name = "yaml",         .has_arg = no_argument },
3937         { .name = NULL } };
3938         int c, rc;
3939         char *end, *tmp;
3940
3941         while ((c = getopt_long(argc, argv, "cdDE::FghiI::LmMoO:pqrRsSvy",
3942                                 long_opts, NULL)) != -1) {
3943                 switch (c) {
3944                 case 'c':
3945                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
3946                                 param->fp_verbose |= VERBOSE_COUNT;
3947                                 param->fp_max_depth = 0;
3948                         }
3949                         break;
3950                 case LFS_COMP_COUNT_OPT:
3951                         param->fp_verbose |= VERBOSE_COMP_COUNT;
3952                         param->fp_max_depth = 0;
3953                         break;
3954                 case LFS_COMP_FLAGS_OPT:
3955                         if (optarg != NULL) {
3956                                 rc = comp_str2flags(optarg,
3957                                                     &param->fp_comp_flags,
3958                                                     &param->fp_comp_neg_flags);
3959                                 if (rc != 0) {
3960                                         fprintf(stderr, "error: %s bad "
3961                                                 "component flags '%s'.\n",
3962                                                 argv[0], optarg);
3963                                         return CMD_HELP;
3964                                 }
3965                                 param->fp_check_comp_flags = 1;
3966                         } else {
3967                                 param->fp_verbose |= VERBOSE_COMP_FLAGS;
3968                                 param->fp_max_depth = 0;
3969                         }
3970                         break;
3971                 case LFS_COMP_START_OPT:
3972                         if (optarg != NULL) {
3973                                 tmp = optarg;
3974                                 if (tmp[0] == '+') {
3975                                         param->fp_comp_start_sign = -1;
3976                                         tmp++;
3977                                 } else if (tmp[0] == '-') {
3978                                         param->fp_comp_start_sign = 1;
3979                                         tmp++;
3980                                 }
3981                                 rc = llapi_parse_size(tmp,
3982                                                 &param->fp_comp_start,
3983                                                 &param->fp_comp_start_units, 0);
3984                                 if (rc != 0) {
3985                                         fprintf(stderr, "error: %s bad "
3986                                                 "component start '%s'.\n",
3987                                                 argv[0], tmp);
3988                                         return CMD_HELP;
3989                                 } else {
3990                                         param->fp_check_comp_start = 1;
3991                                 }
3992                         } else {
3993                                 param->fp_verbose |= VERBOSE_COMP_START;
3994                                 param->fp_max_depth = 0;
3995                         }
3996                         break;
3997                 case 'd':
3998                         param->fp_max_depth = 0;
3999                         break;
4000                 case 'D':
4001                         param->fp_get_default_lmv = 1;
4002                         break;
4003                 case 'E':
4004                         if (optarg != NULL) {
4005                                 tmp = optarg;
4006                                 if (tmp[0] == '+') {
4007                                         param->fp_comp_end_sign = -1;
4008                                         tmp++;
4009                                 } else if (tmp[0] == '-') {
4010                                         param->fp_comp_end_sign = 1;
4011                                         tmp++;
4012                                 }
4013
4014                                 if (arg_is_eof(tmp)) {
4015                                         param->fp_comp_end = LUSTRE_EOF;
4016                                         param->fp_comp_end_units = 1;
4017                                         rc = 0;
4018                                 } else {
4019                                         rc = llapi_parse_size(tmp,
4020                                                 &param->fp_comp_end,
4021                                                 &param->fp_comp_end_units, 0);
4022                                 }
4023                                 if (rc != 0) {
4024                                         fprintf(stderr, "error: %s bad "
4025                                                 "component end '%s'.\n",
4026                                                 argv[0], tmp);
4027                                         return CMD_HELP;
4028                                 }
4029                                 param->fp_check_comp_end = 1;
4030                         } else {
4031                                 param->fp_verbose |= VERBOSE_COMP_END;
4032                                 param->fp_max_depth = 0;
4033                         }
4034                         break;
4035                 case 'F':
4036                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4037                                 param->fp_verbose |= VERBOSE_DFID;
4038                                 param->fp_max_depth = 0;
4039                         }
4040                         break;
4041                 case 'g':
4042                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4043                                 param->fp_verbose |= VERBOSE_GENERATION;
4044                                 param->fp_max_depth = 0;
4045                         }
4046                         break;
4047                 case 'i':
4048                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4049                                 param->fp_verbose |= VERBOSE_OFFSET;
4050                                 param->fp_max_depth = 0;
4051                         }
4052                         break;
4053                 case 'I':
4054                         if (optarg != NULL) {
4055                                 param->fp_comp_id = strtoul(optarg, &end, 0);
4056                                 if (*end != '\0' || param->fp_comp_id == 0 ||
4057                                     param->fp_comp_id > LCME_ID_MAX) {
4058                                         fprintf(stderr, "error: %s bad "
4059                                                 "component id '%s'\n",
4060                                                 argv[0], optarg);
4061                                         return CMD_HELP;
4062                                 } else {
4063                                         param->fp_check_comp_id = 1;
4064                                 }
4065                         } else {
4066                                 param->fp_max_depth = 0;
4067                                 param->fp_verbose |= VERBOSE_COMP_ID;
4068                         }
4069                         break;
4070                 case 'L':
4071                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4072                                 param->fp_verbose |= VERBOSE_LAYOUT;
4073                                 param->fp_max_depth = 0;
4074                         }
4075                         break;
4076 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4077                 case 'M':
4078                         fprintf(stderr, "warning: '-M' deprecated"
4079                                 ", use '--mdt-index' or '-m' instead\n");
4080 #endif
4081                 case 'm':
4082                         if (!(param->fp_verbose & VERBOSE_DETAIL))
4083                                 param->fp_max_depth = 0;
4084                         param->fp_verbose |= VERBOSE_MDTINDEX;
4085                         break;
4086                 case 'O':
4087                         if (param->fp_obd_uuid) {
4088                                 fprintf(stderr,
4089                                         "error: %s: only one obduuid allowed",
4090                                         argv[0]);
4091                                 return CMD_HELP;
4092                         }
4093                         param->fp_obd_uuid = (struct obd_uuid *)optarg;
4094                         break;
4095                 case 'p':
4096                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4097                                 param->fp_verbose |= VERBOSE_POOL;
4098                                 param->fp_max_depth = 0;
4099                         }
4100                         break;
4101                 case 'q':
4102                         param->fp_quiet++;
4103                         break;
4104                 case 'r':
4105                         param->fp_recursive = 1;
4106                         break;
4107                 case 'R':
4108                         param->fp_raw = 1;
4109                         break;
4110                 case 'S':
4111                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
4112                                 param->fp_verbose |= VERBOSE_SIZE;
4113                                 param->fp_max_depth = 0;
4114                         }
4115                         break;
4116                 case 'v':
4117                         param->fp_verbose = VERBOSE_DEFAULT | VERBOSE_DETAIL;
4118                         break;
4119                 case 'y':
4120                         param->fp_yaml = 1;
4121                         break;
4122                 default:
4123                         return CMD_HELP;
4124                 }
4125         }
4126
4127         if (optind >= argc)
4128                 return CMD_HELP;
4129
4130         if (param->fp_recursive)
4131                 param->fp_max_depth = -1;
4132         else if (param->fp_verbose & VERBOSE_DETAIL)
4133                 param->fp_max_depth = 1;
4134
4135         if (!param->fp_verbose)
4136                 param->fp_verbose = VERBOSE_DEFAULT;
4137         if (param->fp_quiet)
4138                 param->fp_verbose = VERBOSE_OBJID;
4139
4140         do {
4141                 rc = llapi_getstripe(argv[optind], param);
4142         } while (++optind < argc && !rc);
4143
4144         if (rc)
4145                 fprintf(stderr, "error: %s failed for %s.\n",
4146                         argv[0], argv[optind - 1]);
4147         return rc;
4148 }
4149
4150 static int lfs_tgts(int argc, char **argv)
4151 {
4152         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
4153         struct find_param param;
4154         int index = 0, rc=0;
4155
4156         if (argc > 2)
4157                 return CMD_HELP;
4158
4159         if (argc == 2 && !realpath(argv[1], path)) {
4160                 rc = -errno;
4161                 fprintf(stderr, "error: invalid path '%s': %s\n",
4162                         argv[1], strerror(-rc));
4163                 return rc;
4164         }
4165
4166         while (!llapi_search_mounts(path, index++, mntdir, NULL)) {
4167                 /* Check if we have a mount point */
4168                 if (mntdir[0] == '\0')
4169                         continue;
4170
4171                 memset(&param, 0, sizeof(param));
4172                 if (!strcmp(argv[0], "mdts"))
4173                         param.fp_get_lmv = 1;
4174
4175                 rc = llapi_ostlist(mntdir, &param);
4176                 if (rc) {
4177                         fprintf(stderr, "error: %s: failed on %s\n",
4178                                 argv[0], mntdir);
4179                 }
4180                 if (path[0] != '\0')
4181                         break;
4182                 memset(mntdir, 0, PATH_MAX);
4183         }
4184
4185         return rc;
4186 }
4187
4188 static int lfs_getstripe(int argc, char **argv)
4189 {
4190         struct find_param param = { 0 };
4191
4192         param.fp_max_depth = 1;
4193         return lfs_getstripe_internal(argc, argv, &param);
4194 }
4195
4196 /* functions */
4197 static int lfs_getdirstripe(int argc, char **argv)
4198 {
4199         struct find_param param = { 0 };
4200         struct option long_opts[] = {
4201         { .val = 'c',   .name = "mdt-count",    .has_arg = no_argument },
4202         { .val = 'D',   .name = "default",      .has_arg = no_argument },
4203         { .val = 'H',   .name = "mdt-hash",     .has_arg = no_argument },
4204         { .val = 'i',   .name = "mdt-index",    .has_arg = no_argument },
4205         { .val = 'm',   .name = "mdt-index",    .has_arg = no_argument },
4206         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
4207         { .val = 'r',   .name = "recursive",    .has_arg = no_argument },
4208         { .val = 'T',   .name = "mdt-count",    .has_arg = no_argument },
4209         { .val = 'y',   .name = "yaml",         .has_arg = no_argument },
4210         { .name = NULL } };
4211         int c, rc;
4212
4213         param.fp_get_lmv = 1;
4214
4215         while ((c = getopt_long(argc, argv,
4216                                 "cDHimO:rtTy", long_opts, NULL)) != -1)
4217         {
4218                 switch (c) {
4219                 case 'c':
4220                 case 'T':
4221                         param.fp_verbose |= VERBOSE_COUNT;
4222                         break;
4223                 case 'D':
4224                         param.fp_get_default_lmv = 1;
4225                         break;
4226                 case 'i':
4227                 case 'm':
4228                         param.fp_verbose |= VERBOSE_OFFSET;
4229                         break;
4230 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4231                 case 't':
4232                         fprintf(stderr, "warning: '-t' deprecated, "
4233                                 "use '--mdt-hash' or '-H' instead\n");
4234 #endif
4235                 case 'H':
4236                         param.fp_verbose |= VERBOSE_HASH_TYPE;
4237                         break;
4238                 case 'O':
4239                         if (param.fp_obd_uuid) {
4240                                 fprintf(stderr,
4241                                         "error: %s: only one obduuid allowed",
4242                                         argv[0]);
4243                                 return CMD_HELP;
4244                         }
4245                         param.fp_obd_uuid = (struct obd_uuid *)optarg;
4246                         break;
4247                 case 'r':
4248                         param.fp_recursive = 1;
4249                         break;
4250                 case 'y':
4251                         param.fp_yaml = 1;
4252                         break;
4253                 default:
4254                         return CMD_HELP;
4255                 }
4256         }
4257
4258         if (optind >= argc)
4259                 return CMD_HELP;
4260
4261         if (param.fp_recursive)
4262                 param.fp_max_depth = -1;
4263
4264         if (!param.fp_verbose)
4265                 param.fp_verbose = VERBOSE_DEFAULT;
4266
4267         do {
4268                 rc = llapi_getstripe(argv[optind], &param);
4269         } while (++optind < argc && !rc);
4270
4271         if (rc)
4272                 fprintf(stderr, "error: %s failed for %s.\n",
4273                         argv[0], argv[optind - 1]);
4274         return rc;
4275 }
4276
4277 enum mntdf_flags {
4278         MNTDF_INODES    = 0x0001,
4279         MNTDF_COOKED    = 0x0002,
4280         MNTDF_LAZY      = 0x0004,
4281         MNTDF_VERBOSE   = 0x0008,
4282         MNTDF_SHOW      = 0x0010,
4283 };
4284
4285 #define COOK(value)                                             \
4286 ({                                                              \
4287         int radix = 0;                                          \
4288         while (value > 1024) {                                  \
4289                 value /= 1024;                                  \
4290                 radix++;                                        \
4291         }                                                       \
4292         radix;                                                  \
4293 })
4294 #define UUF     "%-20s"
4295 #define CSF     "%11s"
4296 #define CDF     "%11llu"
4297 #define HDF     "%8.1f%c"
4298 #define RSF     "%4s"
4299 #define RDF     "%3d%%"
4300
4301 static inline int obd_statfs_ratio(const struct obd_statfs *st)
4302 {
4303         double avail, used, ratio = 0;
4304
4305         avail = st->os_bavail;
4306         used  = st->os_blocks - st->os_bfree;
4307         if (avail + used > 0)
4308                 ratio = used / (used + avail) * 100 + 0.5;
4309
4310         return (int)ratio;
4311 }
4312
4313 static int showdf(char *mntdir, struct obd_statfs *stat,
4314                   char *uuid, enum mntdf_flags flags,
4315                   char *type, int index, int rc)
4316 {
4317         long long avail, used, total;
4318         int ratio = 0;
4319         char *suffix = "KMGTPEZY";
4320         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
4321         char tbuf[3 * sizeof(__u64)];
4322         char ubuf[3 * sizeof(__u64)];
4323         char abuf[3 * sizeof(__u64)];
4324         char rbuf[3 * sizeof(__u64)];
4325
4326         if (!uuid || !stat)
4327                 return -EINVAL;
4328
4329         switch (rc) {
4330         case 0:
4331                 if (flags & MNTDF_INODES) {
4332                         avail = stat->os_ffree;
4333                         used = stat->os_files - stat->os_ffree;
4334                         total = stat->os_files;
4335                 } else {
4336                         int shift = flags & MNTDF_COOKED ? 0 : 10;
4337
4338                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
4339                         used  = ((stat->os_blocks - stat->os_bfree) *
4340                                  stat->os_bsize) >> shift;
4341                         total = (stat->os_blocks * stat->os_bsize) >> shift;
4342                 }
4343
4344                 ratio = obd_statfs_ratio(stat);
4345
4346                 if (flags & MNTDF_COOKED) {
4347                         int i;
4348                         double cook_val;
4349
4350                         cook_val = (double)total;
4351                         i = COOK(cook_val);
4352                         if (i > 0)
4353                                 snprintf(tbuf, sizeof(tbuf), HDF, cook_val,
4354                                          suffix[i - 1]);
4355                         else
4356                                 snprintf(tbuf, sizeof(tbuf), CDF, total);
4357
4358                         cook_val = (double)used;
4359                         i = COOK(cook_val);
4360                         if (i > 0)
4361                                 snprintf(ubuf, sizeof(ubuf), HDF, cook_val,
4362                                          suffix[i - 1]);
4363                         else
4364                                 snprintf(ubuf, sizeof(ubuf), CDF, used);
4365
4366                         cook_val = (double)avail;
4367                         i = COOK(cook_val);
4368                         if (i > 0)
4369                                 snprintf(abuf, sizeof(abuf), HDF, cook_val,
4370                                          suffix[i - 1]);
4371                         else
4372                                 snprintf(abuf, sizeof(abuf), CDF, avail);
4373                 } else {
4374                         snprintf(tbuf, sizeof(tbuf), CDF, total);
4375                         snprintf(ubuf, sizeof(tbuf), CDF, used);
4376                         snprintf(abuf, sizeof(tbuf), CDF, avail);
4377                 }
4378
4379                 sprintf(rbuf, RDF, ratio);
4380                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
4381                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
4382                 if (type)
4383                         printf("[%s:%d]", type, index);
4384
4385                 if (stat->os_state) {
4386                         /*
4387                          * Each character represents the matching
4388                          * OS_STATE_* bit.
4389                          */
4390                         const char state_names[] = "DRSI";
4391                         __u32      state;
4392                         __u32      i;
4393
4394                         printf(" ");
4395                         for (i = 0, state = stat->os_state;
4396                              state && i < sizeof(state_names); i++) {
4397                                 if (!(state & (1 << i)))
4398                                         continue;
4399                                 printf("%c", state_names[i]);
4400                                 state ^= 1 << i;
4401                         }
4402                 }
4403
4404                 printf("\n");
4405                 break;
4406         case -ENODATA:
4407                 printf(UUF": inactive device\n", uuid);
4408                 break;
4409         default:
4410                 printf(UUF": %s\n", uuid, strerror(-rc));
4411                 break;
4412         }
4413
4414         return 0;
4415 }
4416
4417 struct ll_stat_type {
4418         int   st_op;
4419         char *st_name;
4420 };
4421
4422 #define LL_STATFS_MAX   LOV_MAX_STRIPE_COUNT
4423
4424 struct ll_statfs_data {
4425         int                     sd_index;
4426         struct obd_statfs       sd_st;
4427 };
4428
4429 struct ll_statfs_buf {
4430         int                     sb_count;
4431         struct ll_statfs_data   sb_buf[LL_STATFS_MAX];
4432 };
4433
4434 static int mntdf(char *mntdir, char *fsname, char *pool, enum mntdf_flags flags,
4435                  int ops, struct ll_statfs_buf *lsb)
4436 {
4437         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
4438         struct obd_uuid uuid_buf;
4439         char *poolname = NULL;
4440         struct ll_stat_type types[] = {
4441                 { .st_op = LL_STATFS_LMV,       .st_name = "MDT" },
4442                 { .st_op = LL_STATFS_LOV,       .st_name = "OST" },
4443                 { .st_name = NULL } };
4444         struct ll_stat_type *tp;
4445         __u64 ost_ffree = 0;
4446         __u32 index;
4447         __u32 type;
4448         int fd;
4449         int rc = 0;
4450         int rc2;
4451
4452         if (pool) {
4453                 poolname = strchr(pool, '.');
4454                 if (poolname != NULL) {
4455                         if (strncmp(fsname, pool, strlen(fsname))) {
4456                                 fprintf(stderr, "filesystem name incorrect\n");
4457                                 return -ENODEV;
4458                         }
4459                         poolname++;
4460                 } else
4461                         poolname = pool;
4462         }
4463
4464         fd = open(mntdir, O_RDONLY);
4465         if (fd < 0) {
4466                 rc = -errno;
4467                 fprintf(stderr, "%s: cannot open '%s': %s\n", progname, mntdir,
4468                         strerror(errno));
4469                 return rc;
4470         }
4471
4472         if (flags & MNTDF_SHOW) {
4473                 if (flags & MNTDF_INODES)
4474                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
4475                                "UUID", "Inodes", "IUsed", "IFree",
4476                                "IUse%", "Mounted on");
4477                 else
4478                         printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
4479                                "UUID",
4480                                flags & MNTDF_COOKED ? "bytes" : "1K-blocks",
4481                                "Used", "Available", "Use%", "Mounted on");
4482         }
4483
4484         for (tp = types; tp->st_name != NULL; tp++) {
4485                 if (!(tp->st_op & ops))
4486                         continue;
4487
4488                 for (index = 0; ; index++) {
4489                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
4490                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
4491                         type = flags & MNTDF_LAZY ?
4492                                 tp->st_op | LL_STATFS_NODELAY : tp->st_op;
4493                         rc2 = llapi_obd_fstatfs(fd, type, index,
4494                                                &stat_buf, &uuid_buf);
4495                         if (rc2 == -ENODEV)
4496                                 break;
4497                         if (rc2 == -EAGAIN)
4498                                 continue;
4499                         if (rc2 == -ENODATA) { /* Inactive device, OK. */
4500                                 if (!(flags & MNTDF_VERBOSE))
4501                                         continue;
4502                         } else if (rc2 < 0 && rc == 0) {
4503                                 rc = rc2;
4504                         }
4505
4506                         if (poolname && tp->st_op == LL_STATFS_LOV &&
4507                             llapi_search_ost(fsname, poolname,
4508                                              obd_uuid2str(&uuid_buf)) != 1)
4509                                 continue;
4510
4511                         /* the llapi_obd_statfs() call may have returned with
4512                          * an error, but if it filled in uuid_buf we will at
4513                          * lease use that to print out a message for that OBD.
4514                          * If we didn't get anything in the uuid_buf, then fill
4515                          * it in so that we can print an error message. */
4516                         if (uuid_buf.uuid[0] == '\0')
4517                                 snprintf(uuid_buf.uuid, sizeof(uuid_buf.uuid),
4518                                          "%s%04x", tp->st_name, index);
4519                         if (!rc && lsb) {
4520                                 lsb->sb_buf[lsb->sb_count].sd_index = index;
4521                                 lsb->sb_buf[lsb->sb_count].sd_st = stat_buf;
4522                                 lsb->sb_count++;
4523                         }
4524                         if (flags & MNTDF_SHOW)
4525                                 showdf(mntdir, &stat_buf,
4526                                        obd_uuid2str(&uuid_buf), flags,
4527                                        tp->st_name, index, rc2);
4528
4529                         if (rc2 == 0) {
4530                                 if (tp->st_op == LL_STATFS_LMV) {
4531                                         sum.os_ffree += stat_buf.os_ffree;
4532                                         sum.os_files += stat_buf.os_files;
4533                                 } else /* if (tp->st_op == LL_STATFS_LOV) */ {
4534                                         sum.os_blocks += stat_buf.os_blocks *
4535                                                 stat_buf.os_bsize;
4536                                         sum.os_bfree  += stat_buf.os_bfree *
4537                                                 stat_buf.os_bsize;
4538                                         sum.os_bavail += stat_buf.os_bavail *
4539                                                 stat_buf.os_bsize;
4540                                         ost_ffree += stat_buf.os_ffree;
4541                                 }
4542                         }
4543                 }
4544         }
4545
4546         close(fd);
4547
4548         /* If we don't have as many objects free on the OST as inodes
4549          * on the MDS, we reduce the total number of inodes to
4550          * compensate, so that the "inodes in use" number is correct.
4551          * Matches ll_statfs_internal() so the results are consistent. */
4552         if (ost_ffree < sum.os_ffree) {
4553                 sum.os_files = (sum.os_files - sum.os_ffree) + ost_ffree;
4554                 sum.os_ffree = ost_ffree;
4555         }
4556         if (flags & MNTDF_SHOW) {
4557                 printf("\n");
4558                 showdf(mntdir, &sum, "filesystem_summary:", flags, NULL, 0, 0);
4559                 printf("\n");
4560         }
4561
4562         return rc;
4563 }
4564
4565 static int ll_statfs_data_comp(const void *sd1, const void *sd2)
4566 {
4567         const struct obd_statfs *st1 = &((const struct ll_statfs_data *)sd1)->
4568                                                 sd_st;
4569         const struct obd_statfs *st2 = &((const struct ll_statfs_data *)sd2)->
4570                                                 sd_st;
4571         int r1 = obd_statfs_ratio(st1);
4572         int r2 = obd_statfs_ratio(st2);
4573         int64_t result = r1 - r2;
4574
4575         /* if both space usage are above 90, compare free inodes */
4576         if (r1 > 90 && r2 > 90)
4577                 result = st2->os_ffree - st1->os_ffree;
4578
4579         if (result < 0)
4580                 return -1;
4581         else if (result == 0)
4582                 return 0;
4583         else
4584                 return 1;
4585 }
4586
4587 /* functions */
4588 static int lfs_setdirstripe(int argc, char **argv)
4589 {
4590         char                    *dname;
4591         int                     result;
4592         struct lfs_setstripe_args        lsa = { 0 };
4593         struct llapi_stripe_param       *param = NULL;
4594         __u32                   mdts[LMV_MAX_STRIPE_COUNT] = { 0 };
4595         char                    *end;
4596         int                     c;
4597         char                    *mode_opt = NULL;
4598         bool                    default_stripe = false;
4599         mode_t                  mode = S_IRWXU | S_IRWXG | S_IRWXO;
4600         mode_t                  previous_mode = 0;
4601         bool                    delete = false;
4602         struct ll_statfs_buf    *lsb = NULL;
4603         char                    mntdir[PATH_MAX] = "";
4604         bool                    auto_distributed = false;
4605
4606         struct option long_opts[] = {
4607         { .val = 'c',   .name = "count",        .has_arg = required_argument },
4608         { .val = 'c',   .name = "mdt-count",    .has_arg = required_argument },
4609         { .val = 'd',   .name = "delete",       .has_arg = no_argument },
4610         { .val = 'D',   .name = "default",      .has_arg = no_argument },
4611         { .val = 'D',   .name = "default_stripe", .has_arg = no_argument },
4612         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
4613         { .val = 'i',   .name = "mdt-index",    .has_arg = required_argument },
4614 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4615         { .val = 'i',   .name = "index",        .has_arg = required_argument },
4616 #endif
4617         { .val = 'o',   .name = "mode",         .has_arg = required_argument },
4618 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4619         { .val = 't',   .name = "hash-type",    .has_arg = required_argument },
4620 #endif
4621         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
4622 /* setstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
4623         { .name = NULL } };
4624
4625         setstripe_args_init(&lsa);
4626
4627         while ((c = getopt_long(argc, argv, "c:dDi:H:m:o:t:T:", long_opts,
4628                                 NULL)) >= 0) {
4629                 switch (c) {
4630                 case 0:
4631                         /* Long options. */
4632                         break;
4633                 case 'c':
4634                 case 'T':
4635                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
4636                         if (*end != '\0') {
4637                                 fprintf(stderr,
4638                                         "%s %s: invalid stripe count '%s'\n",
4639                                         progname, argv[0], optarg);
4640                                 return CMD_HELP;
4641                         }
4642                         break;
4643                 case 'd':
4644                         delete = true;
4645                         default_stripe = true;
4646                         break;
4647                 case 'D':
4648                         default_stripe = true;
4649                         break;
4650 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4651                 case 't':
4652                         fprintf(stderr, "warning: '--hash-type' and '-t' "
4653                               "deprecated, use '--mdt-hash' or '-H' instead\n");
4654 #endif
4655                 case 'H':
4656                         lsa.lsa_pattern = check_hashtype(optarg);
4657                         if (lsa.lsa_pattern == 0) {
4658                                 fprintf(stderr,
4659                                         "%s %s: bad stripe hash type '%s'\n",
4660                                         progname, argv[0], optarg);
4661                                 return CMD_HELP;
4662                         }
4663                         break;
4664                 case 'i':
4665 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4666                         if (strcmp(argv[optind - 1], "--index") == 0)
4667                                 fprintf(stderr,
4668                                         "%s %s: warning: '--index' deprecated, use '--mdt-index' instead\n",
4669                                         progname, argv[0]);
4670 #endif
4671                         lsa.lsa_nr_tgts = parse_targets(mdts,
4672                                                 sizeof(mdts) / sizeof(__u32),
4673                                                 lsa.lsa_nr_tgts, optarg);
4674                         if (lsa.lsa_nr_tgts < 0) {
4675                                 fprintf(stderr,
4676                                         "%s %s: invalid MDT target(s) '%s'\n",
4677                                         progname, argv[0], optarg);
4678                                 return CMD_HELP;
4679                         }
4680
4681                         lsa.lsa_tgts = mdts;
4682                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
4683                                 lsa.lsa_stripe_off = mdts[0];
4684                         break;
4685 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 16, 53, 0)
4686                 case 'm':
4687                         fprintf(stderr, "warning: '-m' is deprecated, "
4688                                 "use '--mode' or '-o' instead\n");
4689 #endif
4690                 case 'o':
4691                         mode_opt = optarg;
4692                         break;
4693                 default:
4694                         fprintf(stderr, "%s %s: unrecognized option '%s'\n",
4695                                 progname, argv[0], argv[optind - 1]);
4696                         return CMD_HELP;
4697                 }
4698         }
4699
4700         if (optind == argc) {
4701                 fprintf(stderr, "%s %s: DIR must be specified\n",
4702                         progname, argv[0]);
4703                 return CMD_HELP;
4704         }
4705
4706         if (!delete && lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT &&
4707             lsa.lsa_stripe_count == LLAPI_LAYOUT_DEFAULT) {
4708                 fprintf(stderr,
4709                         "%s %s: stripe offset and count must be specified\n",
4710                         progname, argv[0]);
4711                 return CMD_HELP;
4712         }
4713
4714         if (delete &&
4715             (lsa.lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
4716              lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)) {
4717                 fprintf(stderr,
4718                         "%s %s: cannot specify -d with -c or -i options\n",
4719                         progname, argv[0]);
4720                 return CMD_HELP;
4721         }
4722
4723         if (mode_opt != NULL) {
4724                 mode = strtoul(mode_opt, &end, 8);
4725                 if (*end != '\0') {
4726                         fprintf(stderr,
4727                                 "%s %s: bad MODE '%s'\n",
4728                                 progname, argv[0], mode_opt);
4729                         return CMD_HELP;
4730                 }
4731                 previous_mode = umask(0);
4732         }
4733
4734         /*
4735          * initialize stripe parameters, in case param is converted to specific,
4736          * i.e, 'lfs mkdir -i -1 -c N', always allocate space for lsp_tgts.
4737          */
4738         param = calloc(1, offsetof(typeof(*param),
4739                        lsp_tgts[lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ?
4740                                 lsa.lsa_stripe_count : lsa.lsa_nr_tgts]));
4741         if (param == NULL) {
4742                 fprintf(stderr,
4743                         "%s %s: cannot allocate memory for parameters: %s\n",
4744                         progname, argv[0], strerror(ENOMEM));
4745                 return CMD_HELP;
4746         }
4747
4748         if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT)
4749                 param->lsp_stripe_count = lsa.lsa_stripe_count;
4750         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
4751                 param->lsp_stripe_offset = -1;
4752         else
4753                 param->lsp_stripe_offset = lsa.lsa_stripe_off;
4754         if (lsa.lsa_pattern != LLAPI_LAYOUT_RAID0)
4755                 param->lsp_stripe_pattern = lsa.lsa_pattern;
4756         else
4757                 param->lsp_stripe_pattern = LMV_HASH_TYPE_FNV_1A_64;
4758         param->lsp_pool = lsa.lsa_pool_name;
4759         param->lsp_is_specific = false;
4760         if (lsa.lsa_nr_tgts > 1) {
4761                 if (lsa.lsa_stripe_count > 0 &&
4762                     lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
4763                     lsa.lsa_stripe_count != lsa.lsa_nr_tgts) {
4764                         fprintf(stderr, "error: %s: stripe count %lld doesn't "
4765                                 "match the number of MDTs: %d\n",
4766                                 argv[0], lsa.lsa_stripe_count, lsa.lsa_nr_tgts);
4767                         free(param);
4768                         return CMD_HELP;
4769                 }
4770
4771                 param->lsp_is_specific = true;
4772                 param->lsp_stripe_count = lsa.lsa_nr_tgts;
4773                 memcpy(param->lsp_tgts, mdts, sizeof(*mdts) * lsa.lsa_nr_tgts);
4774         }
4775
4776         dname = argv[optind];
4777         do {
4778                 if (default_stripe) {
4779                         result = llapi_dir_set_default_lmv(dname, param);
4780                 } else {
4781                         /* if current \a dname isn't under the same \a mntdir
4782                          * as the last one, and the last one was
4783                          * auto-distributed, restore \a param.
4784                          */
4785                         if (mntdir[0] != '\0' &&
4786                             strncmp(dname, mntdir, strlen(mntdir)) &&
4787                             auto_distributed) {
4788                                 param->lsp_is_specific = false;
4789                                 param->lsp_stripe_offset = -1;
4790                                 auto_distributed = false;
4791                         }
4792
4793                         if (!param->lsp_is_specific &&
4794                             param->lsp_stripe_offset == -1) {
4795                                 char path[PATH_MAX] = "";
4796
4797                                 if (!lsb) {
4798                                         lsb = malloc(sizeof(*lsb));
4799                                         if (!lsb) {
4800                                                 result = -ENOMEM;
4801                                                 break;
4802                                         }
4803                                 }
4804                                 lsb->sb_count = 0;
4805
4806                                 /* use mntdir for dirname() temporarily */
4807                                 strncpy(mntdir, dname, sizeof(mntdir));
4808                                 if (!realpath(dirname(mntdir), path)) {
4809                                         result = -errno;
4810                                         fprintf(stderr,
4811                                                 "error: invalid path '%s': %s\n",
4812                                                 argv[optind], strerror(errno));
4813                                         break;
4814                                 }
4815                                 mntdir[0] = '\0';
4816
4817                                 result = llapi_search_mounts(path, 0, mntdir,
4818                                                              NULL);
4819                                 if (result < 0 || mntdir[0] == '\0') {
4820                                         fprintf(stderr,
4821                                                 "No suitable Lustre mount found\n");
4822                                         break;
4823                                 }
4824
4825                                 result = mntdf(mntdir, NULL, NULL, 0,
4826                                                LL_STATFS_LMV, lsb);
4827                                 if (result < 0)
4828                                         break;
4829
4830                                 if (param->lsp_stripe_count > lsb->sb_count) {
4831                                         fprintf(stderr,
4832                                                 "error: stripe count %d is too big\n",
4833                                                 param->lsp_stripe_count);
4834                                         result = -ERANGE;
4835                                         break;
4836                                 }
4837
4838                                 qsort(lsb->sb_buf, lsb->sb_count,
4839                                       sizeof(struct ll_statfs_data),
4840                                       ll_statfs_data_comp);
4841
4842                                 auto_distributed = true;
4843                         }
4844
4845                         if (auto_distributed) {
4846                                 int r;
4847                                 int nr = MAX(param->lsp_stripe_count,
4848                                              lsb->sb_count / 2);
4849
4850                                 /* don't use server whose usage is above 90% */
4851                                 while (nr != param->lsp_stripe_count &&
4852                                        obd_statfs_ratio(&lsb->sb_buf[nr].sd_st)
4853                                        > 90)
4854                                         nr = MAX(param->lsp_stripe_count,
4855                                                  nr / 2);
4856
4857                                 /* get \a r between [0, nr) */
4858                                 r = rand() % nr;
4859
4860                                 param->lsp_stripe_offset =
4861                                         lsb->sb_buf[r].sd_index;
4862                                 if (param->lsp_stripe_count > 1) {
4863                                         int i = 0;
4864
4865                                         param->lsp_is_specific = true;
4866                                         for (; i < param->lsp_stripe_count; i++)
4867                                                 param->lsp_tgts[(i + r) % nr] =
4868                                                         lsb->sb_buf[i].sd_index;
4869                                 }
4870                         }
4871
4872                         result = llapi_dir_create(dname, mode, param);
4873                 }
4874
4875                 if (result) {
4876                         fprintf(stderr,
4877                                 "%s setdirstripe: cannot create stripe dir '%s': %s\n",
4878                                 progname, dname, strerror(-result));
4879                         break;
4880                 }
4881                 dname = argv[++optind];
4882         } while (dname != NULL);
4883
4884         if (mode_opt != NULL)
4885                 umask(previous_mode);
4886
4887         free(lsb);
4888         free(param);
4889         return result;
4890 }
4891
4892 /* functions */
4893 static int lfs_rmentry(int argc, char **argv)
4894 {
4895         char *dname;
4896         int   index;
4897         int   result = 0;
4898
4899         if (argc <= 1) {
4900                 fprintf(stderr, "error: %s: missing dirname\n",
4901                         argv[0]);
4902                 return CMD_HELP;
4903         }
4904
4905         index = 1;
4906         dname = argv[index];
4907         while (dname != NULL) {
4908                 result = llapi_direntry_remove(dname);
4909                 if (result) {
4910                         fprintf(stderr, "error: %s: remove dir entry '%s' "
4911                                 "failed\n", argv[0], dname);
4912                         break;
4913                 }
4914                 dname = argv[++index];
4915         }
4916         return result;
4917 }
4918
4919 static int lfs_mv(int argc, char **argv)
4920 {
4921         struct  find_param param = {
4922                 .fp_max_depth = -1,
4923                 .fp_mdt_index = -1,
4924         };
4925         char   *end;
4926         int     c;
4927         int     rc = 0;
4928         struct option long_opts[] = {
4929         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
4930         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
4931         { .name = NULL } };
4932
4933         while ((c = getopt_long(argc, argv, "m:M:v", long_opts, NULL)) != -1) {
4934                 switch (c) {
4935 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
4936                 case 'M':
4937                         fprintf(stderr, "warning: '-M' deprecated"
4938                                 ", use '--mdt-index' or '-m' instead\n");
4939 #endif
4940                 case 'm':
4941                         param.fp_mdt_index = strtoul(optarg, &end, 0);
4942                         if (*end != '\0') {
4943                                 fprintf(stderr, "%s: invalid MDT index'%s'\n",
4944                                         argv[0], optarg);
4945                                 return CMD_HELP;
4946                         }
4947                         break;
4948                 case 'v':
4949                         param.fp_verbose = VERBOSE_DETAIL;
4950                         break;
4951                 default:
4952                         fprintf(stderr, "error: %s: unrecognized option '%s'\n",
4953                                 argv[0], argv[optind - 1]);
4954                         return CMD_HELP;
4955                 }
4956         }
4957
4958         if (param.fp_mdt_index == -1) {
4959                 fprintf(stderr, "%s: MDT index must be specified\n", argv[0]);
4960                 return CMD_HELP;
4961         }
4962
4963         if (optind >= argc) {
4964                 fprintf(stderr, "%s: missing operand path\n", argv[0]);
4965                 return CMD_HELP;
4966         }
4967
4968         param.fp_migrate = 1;
4969         rc = llapi_migrate_mdt(argv[optind], &param);
4970         if (rc != 0)
4971                 fprintf(stderr, "%s: cannot migrate '%s' to MDT%04x: %s\n",
4972                         argv[0], argv[optind], param.fp_mdt_index,
4973                         strerror(-rc));
4974         return rc;
4975 }
4976
4977 static int lfs_osts(int argc, char **argv)
4978 {
4979         return lfs_tgts(argc, argv);
4980 }
4981
4982 static int lfs_mdts(int argc, char **argv)
4983 {
4984         return lfs_tgts(argc, argv);
4985 }
4986
4987 static int lfs_df(int argc, char **argv)
4988 {
4989         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
4990         enum mntdf_flags flags = MNTDF_SHOW;
4991         int ops = LL_STATFS_LMV | LL_STATFS_LOV;
4992         int c, rc = 0, index = 0;
4993         char fsname[PATH_MAX] = "", *pool_name = NULL;
4994         struct option long_opts[] = {
4995         { .val = 'h',   .name = "human-readable",
4996                                                 .has_arg = no_argument },
4997         { .val = 'i',   .name = "inodes",       .has_arg = no_argument },
4998         { .val = 'l',   .name = "lazy",         .has_arg = no_argument },
4999         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
5000         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
5001         { .name = NULL} };
5002
5003         while ((c = getopt_long(argc, argv, "hilp:v", long_opts, NULL)) != -1) {
5004                 switch (c) {
5005                 case 'h':
5006                         flags |= MNTDF_COOKED;
5007                         break;
5008                 case 'i':
5009                         flags |= MNTDF_INODES;
5010                         break;
5011                 case 'l':
5012                         flags |= MNTDF_LAZY;
5013                         break;
5014                 case 'p':
5015                         pool_name = optarg;
5016                         break;
5017                 case 'v':
5018                         flags |= MNTDF_VERBOSE;
5019                         break;
5020                 default:
5021                         return CMD_HELP;
5022                 }
5023         }
5024         if (optind < argc && !realpath(argv[optind], path)) {
5025                 rc = -errno;
5026                 fprintf(stderr, "error: invalid path '%s': %s\n",
5027                         argv[optind], strerror(-rc));
5028                 return rc;
5029         }
5030
5031         while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
5032                 /* Check if we have a mount point */
5033                 if (mntdir[0] == '\0')
5034                         continue;
5035
5036                 rc = mntdf(mntdir, fsname, pool_name, flags, ops, NULL);
5037                 if (rc || path[0] != '\0')
5038                         break;
5039                 fsname[0] = '\0'; /* avoid matching in next loop */
5040                 mntdir[0] = '\0'; /* avoid matching in next loop */
5041         }
5042
5043         return rc;
5044 }
5045
5046 static int lfs_getname(int argc, char **argv)
5047 {
5048         char mntdir[PATH_MAX] = "", path[PATH_MAX] = "", fsname[PATH_MAX] = "";
5049         int rc = 0, index = 0, c;
5050         char buf[sizeof(struct obd_uuid)];
5051
5052         while ((c = getopt(argc, argv, "h")) != -1)
5053                 return CMD_HELP;
5054
5055         if (optind == argc) { /* no paths specified, get all paths. */
5056                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
5057                         rc = llapi_getname(mntdir, buf, sizeof(buf));
5058                         if (rc < 0) {
5059                                 fprintf(stderr,
5060                                         "cannot get name for `%s': %s\n",
5061                                         mntdir, strerror(-rc));
5062                                 break;
5063                         }
5064
5065                         printf("%s %s\n", buf, mntdir);
5066
5067                         path[0] = fsname[0] = mntdir[0] = 0;
5068                 }
5069         } else { /* paths specified, only attempt to search these. */
5070                 for (; optind < argc; optind++) {
5071                         rc = llapi_getname(argv[optind], buf, sizeof(buf));
5072                         if (rc < 0) {
5073                                 fprintf(stderr,
5074                                         "cannot get name for `%s': %s\n",
5075                                         argv[optind], strerror(-rc));
5076                                 break;
5077                         }
5078
5079                         printf("%s %s\n", buf, argv[optind]);
5080                 }
5081         }
5082         return rc;
5083 }
5084
5085 static int lfs_check(int argc, char **argv)
5086 {
5087         int rc;
5088         char mntdir[PATH_MAX] = {'\0'};
5089         int num_types = 1;
5090         char *obd_types[2];
5091         char obd_type1[4];
5092         char obd_type2[4];
5093
5094         if (argc != 2) {
5095                 fprintf(stderr, "%s check: server type must be specified\n",
5096                         progname);
5097                 return CMD_HELP;
5098         }
5099
5100         obd_types[0] = obd_type1;
5101         obd_types[1] = obd_type2;
5102
5103         if (strcmp(argv[1], "osts") == 0) {
5104                 strcpy(obd_types[0], "osc");
5105         } else if (strcmp(argv[1], "mds") == 0) {
5106                 strcpy(obd_types[0], "mdc");
5107         } else if (strcmp(argv[1], "servers") == 0) {
5108                 num_types = 2;
5109                 strcpy(obd_types[0], "osc");
5110                 strcpy(obd_types[1], "mdc");
5111         } else {
5112                 fprintf(stderr, "%s check: unrecognized option '%s'\n",
5113                         progname, argv[1]);
5114                 return CMD_HELP;
5115         }
5116
5117         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
5118         if (rc < 0 || mntdir[0] == '\0') {
5119                 fprintf(stderr,
5120                         "%s check: cannot find mounted Lustre filesystem: %s\n",
5121                         progname, (rc < 0) ? strerror(-rc) : strerror(ENODEV));
5122                 return rc;
5123         }
5124
5125         rc = llapi_target_check(num_types, obd_types, mntdir);
5126         if (rc)
5127                 fprintf(stderr, "%s check: cannot check target '%s': %s\n",
5128                         progname, argv[1], strerror(-rc));
5129
5130         return rc;
5131
5132 }
5133
5134 #ifdef HAVE_SYS_QUOTA_H
5135 #define ARG2INT(nr, str, msg)                                           \
5136 do {                                                                    \
5137         char *endp;                                                     \
5138         nr = strtol(str, &endp, 0);                                     \
5139         if (*endp != '\0') {                                            \
5140                 fprintf(stderr, "%s: bad %s '%s'\n",                    \
5141                         progname, msg, str);                            \
5142                 return CMD_HELP;                                        \
5143         }                                                               \
5144 } while (0)
5145
5146 #define ADD_OVERFLOW(a,b) ((a + b) < a) ? (a = ULONG_MAX) : (a = a + b)
5147
5148 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
5149  * returns the value or ULONG_MAX on integer overflow or incorrect format
5150  * Notes:
5151  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
5152  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
5153  *        3. empty integer value is interpreted as 0
5154  */
5155 static unsigned long str2sec(const char* timestr)
5156 {
5157         const char spec[] = "smhdw";
5158         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
5159         unsigned long val = 0;
5160         char *tail;
5161
5162         if (strpbrk(timestr, spec) == NULL) {
5163                 /* no specifiers inside the time string,
5164                    should treat it as an integer value */
5165                 val = strtoul(timestr, &tail, 10);
5166                 return *tail ? ULONG_MAX : val;
5167         }
5168
5169         /* format string is XXwXXdXXhXXmXXs */
5170         while (*timestr) {
5171                 unsigned long v;
5172                 int ind;
5173                 char* ptr;
5174
5175                 v = strtoul(timestr, &tail, 10);
5176                 if (v == ULONG_MAX || *tail == '\0')
5177                         /* value too large (ULONG_MAX or more)
5178                            or missing specifier */
5179                         goto error;
5180
5181                 ptr = strchr(spec, *tail);
5182                 if (ptr == NULL)
5183                         /* unknown specifier */
5184                         goto error;
5185
5186                 ind = ptr - spec;
5187
5188                 /* check if product will overflow the type */
5189                 if (!(v < ULONG_MAX / mult[ind]))
5190                         goto error;
5191
5192                 ADD_OVERFLOW(val, mult[ind] * v);
5193                 if (val == ULONG_MAX)
5194                         goto error;
5195
5196                 timestr = tail + 1;
5197         }
5198
5199         return val;
5200
5201 error:
5202         return ULONG_MAX;
5203 }
5204
5205 #define ARG2ULL(nr, str, def_units)                                     \
5206 do {                                                                    \
5207         unsigned long long limit, units = def_units;                    \
5208         int rc;                                                         \
5209                                                                         \
5210         rc = llapi_parse_size(str, &limit, &units, 1);                  \
5211         if (rc < 0) {                                                   \
5212                 fprintf(stderr, "%s: invalid limit '%s'\n",             \
5213                         progname, str);                                 \
5214                 return CMD_HELP;                                        \
5215         }                                                               \
5216         nr = limit;                                                     \
5217 } while (0)
5218
5219 static inline int has_times_option(int argc, char **argv)
5220 {
5221         int i;
5222
5223         for (i = 1; i < argc; i++)
5224                 if (!strcmp(argv[i], "-t"))
5225                         return 1;
5226
5227         return 0;
5228 }
5229
5230 int lfs_setquota_times(int argc, char **argv)
5231 {
5232         int c, rc;
5233         struct if_quotactl qctl;
5234         char *mnt, *obd_type = (char *)qctl.obd_type;
5235         struct obd_dqblk *dqb = &qctl.qc_dqblk;
5236         struct obd_dqinfo *dqi = &qctl.qc_dqinfo;
5237         struct option long_opts[] = {
5238         { .val = 'b',   .name = "block-grace",  .has_arg = required_argument },
5239         { .val = 'g',   .name = "group",        .has_arg = no_argument },
5240         { .val = 'i',   .name = "inode-grace",  .has_arg = required_argument },
5241         { .val = 'p',   .name = "projid",       .has_arg = no_argument },
5242         { .val = 't',   .name = "times",        .has_arg = no_argument },
5243         { .val = 'u',   .name = "user",         .has_arg = no_argument },
5244         { .name = NULL } };
5245         int qtype;
5246
5247         memset(&qctl, 0, sizeof(qctl));
5248         qctl.qc_cmd  = LUSTRE_Q_SETINFO;
5249         qctl.qc_type = ALLQUOTA;
5250
5251         while ((c = getopt_long(argc, argv, "b:gi:ptu",
5252                                 long_opts, NULL)) != -1) {
5253                 switch (c) {
5254                 case 'u':
5255                         qtype = USRQUOTA;
5256                         goto quota_type;
5257                 case 'g':
5258                         qtype = GRPQUOTA;
5259                         goto quota_type;
5260                 case 'p':
5261                         qtype = PRJQUOTA;
5262 quota_type:
5263                         if (qctl.qc_type != ALLQUOTA) {
5264                                 fprintf(stderr, "error: -u/g/p can't be used "
5265                                                 "more than once\n");
5266                                 return CMD_HELP;
5267                         }
5268                         qctl.qc_type = qtype;
5269                         break;
5270                 case 'b':
5271                         if ((dqi->dqi_bgrace = str2sec(optarg)) == ULONG_MAX) {
5272                                 fprintf(stderr, "error: bad block-grace: %s\n",
5273                                         optarg);
5274                                 return CMD_HELP;
5275                         }
5276                         dqb->dqb_valid |= QIF_BTIME;
5277                         break;
5278                 case 'i':
5279                         if ((dqi->dqi_igrace = str2sec(optarg)) == ULONG_MAX) {
5280                                 fprintf(stderr, "error: bad inode-grace: %s\n",
5281                                         optarg);
5282                                 return CMD_HELP;
5283                         }
5284                         dqb->dqb_valid |= QIF_ITIME;
5285                         break;
5286                 case 't': /* Yes, of course! */
5287                         break;
5288                 default: /* getopt prints error message for us when opterr != 0 */
5289                         return CMD_HELP;
5290                 }
5291         }
5292
5293         if (qctl.qc_type == ALLQUOTA) {
5294                 fprintf(stderr, "error: neither -u, -g nor -p specified\n");
5295                 return CMD_HELP;
5296         }
5297
5298         if (optind != argc - 1) {
5299                 fprintf(stderr, "error: unexpected parameters encountered\n");
5300                 return CMD_HELP;
5301         }
5302
5303         mnt = argv[optind];
5304         rc = llapi_quotactl(mnt, &qctl);
5305         if (rc) {
5306                 if (*obd_type)
5307                         fprintf(stderr, "%s %s ", obd_type,
5308                                 obd_uuid2str(&qctl.obd_uuid));
5309                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
5310                 return rc;
5311         }
5312
5313         return 0;
5314 }
5315
5316 #define BSLIMIT (1 << 0)
5317 #define BHLIMIT (1 << 1)
5318 #define ISLIMIT (1 << 2)
5319 #define IHLIMIT (1 << 3)
5320
5321 int lfs_setquota(int argc, char **argv)
5322 {
5323         int c, rc;
5324         struct if_quotactl qctl;
5325         char *mnt, *obd_type = (char *)qctl.obd_type;
5326         struct obd_dqblk *dqb = &qctl.qc_dqblk;
5327         struct option long_opts[] = {
5328         { .val = 'b',   .name = "block-softlimit",
5329                                                 .has_arg = required_argument },
5330         { .val = 'B',   .name = "block-hardlimit",
5331                                                 .has_arg = required_argument },
5332         { .val = 'g',   .name = "group",        .has_arg = required_argument },
5333         { .val = 'i',   .name = "inode-softlimit",
5334                                                 .has_arg = required_argument },
5335         { .val = 'I',   .name = "inode-hardlimit",
5336                                                 .has_arg = required_argument },
5337         { .val = 'p',   .name = "projid",       .has_arg = required_argument },
5338         { .val = 'u',   .name = "user",         .has_arg = required_argument },
5339         { .name = NULL } };
5340         unsigned limit_mask = 0;
5341         char *endptr;
5342         int qtype;
5343
5344         if (has_times_option(argc, argv))
5345                 return lfs_setquota_times(argc, argv);
5346
5347         memset(&qctl, 0, sizeof(qctl));
5348         qctl.qc_cmd  = LUSTRE_Q_SETQUOTA;
5349         qctl.qc_type = ALLQUOTA; /* ALLQUOTA makes no sense for setquota,
5350                                   * so it can be used as a marker that qc_type
5351                                   * isn't reinitialized from command line */
5352
5353         while ((c = getopt_long(argc, argv, "b:B:g:i:I:p:u:",
5354                 long_opts, NULL)) != -1) {
5355                 switch (c) {
5356                 case 'u':
5357                         qtype = USRQUOTA;
5358                         rc = name2uid(&qctl.qc_id, optarg);
5359                         goto quota_type;
5360                 case 'g':
5361                         qtype = GRPQUOTA;
5362                         rc = name2gid(&qctl.qc_id, optarg);
5363                         goto quota_type;
5364                 case 'p':
5365                         qtype = PRJQUOTA;
5366                         rc = name2projid(&qctl.qc_id, optarg);
5367 quota_type:
5368                         if (qctl.qc_type != ALLQUOTA) {
5369                                 fprintf(stderr,
5370                                         "%s setquota: only one of -u, -g or -p may be specified\n",
5371                                         progname);
5372                                 return CMD_HELP;
5373                         }
5374                         qctl.qc_type = qtype;
5375                         if (rc) {
5376                                 qctl.qc_id = strtoul(optarg, &endptr, 10);
5377                                 if (*endptr != '\0') {
5378                                         fprintf(stderr,
5379                                                 "%s setquota: invalid id '%s'\n",
5380                                                 progname, optarg);
5381                                         return -1;
5382                                 }
5383                         }
5384                         break;
5385                 case 'b':
5386                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
5387                         dqb->dqb_bsoftlimit >>= 10;
5388                         limit_mask |= BSLIMIT;
5389                         if (dqb->dqb_bsoftlimit &&
5390                             dqb->dqb_bsoftlimit <= 1024) /* <= 1M? */
5391                                 fprintf(stderr,
5392                                         "%s setquota: warning: block softlimit '%llu' smaller than minimum qunit size\n"
5393                                         "See '%s help setquota' or Lustre manual for details\n",
5394                                         progname, dqb->dqb_bsoftlimit,
5395                                         progname);
5396                         break;
5397                 case 'B':
5398                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
5399                         dqb->dqb_bhardlimit >>= 10;
5400                         limit_mask |= BHLIMIT;
5401                         if (dqb->dqb_bhardlimit &&
5402                             dqb->dqb_bhardlimit <= 1024) /* <= 1M? */
5403                                 fprintf(stderr,
5404                                         "%s setquota: warning: block hardlimit '%llu' smaller than minimum qunit size\n"
5405                                         "See '%s help setquota' or Lustre manual for details\n",
5406                                         progname, dqb->dqb_bhardlimit,
5407                                         progname);
5408                         break;
5409                 case 'i':
5410                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
5411                         limit_mask |= ISLIMIT;
5412                         if (dqb->dqb_isoftlimit &&
5413                             dqb->dqb_isoftlimit <= 1024) /* <= 1K inodes? */
5414                                 fprintf(stderr,
5415                                         "%s setquota: warning: inode softlimit '%llu' smaller than minimum qunit size\n"
5416                                         "See '%s help setquota' or Lustre manual for details\n",
5417                                         progname, dqb->dqb_isoftlimit,
5418                                         progname);
5419                         break;
5420                 case 'I':
5421                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
5422                         limit_mask |= IHLIMIT;
5423                         if (dqb->dqb_ihardlimit &&
5424                             dqb->dqb_ihardlimit <= 1024) /* <= 1K inodes? */
5425                                 fprintf(stderr,
5426                                         "%s setquota: warning: inode hardlimit '%llu' smaller than minimum qunit size\n"
5427                                         "See '%s help setquota' or Lustre manual for details\n",
5428                                         progname, dqb->dqb_ihardlimit,
5429                                         progname);
5430                         break;
5431                 default:
5432                         fprintf(stderr,
5433                                 "%s setquota: unrecognized option '%s'\n",
5434                                 progname, argv[optind - 1]);
5435                         return CMD_HELP;
5436                 }
5437         }
5438
5439         if (qctl.qc_type == ALLQUOTA) {
5440                 fprintf(stderr,
5441                         "%s setquota: either -u or -g must be specified\n",
5442                         progname);
5443                 return CMD_HELP;
5444         }
5445
5446         if (limit_mask == 0) {
5447                 fprintf(stderr,
5448                         "%s setquota: at least one limit must be specified\n",
5449                         progname);
5450                 return CMD_HELP;
5451         }
5452
5453         if (optind != argc - 1) {
5454                 fprintf(stderr,
5455                         "%s setquota: filesystem not specified or unexpected argument '%s'\n",
5456                         progname, argv[optind]);
5457                 return CMD_HELP;
5458         }
5459
5460         mnt = argv[optind];
5461
5462         if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
5463             (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
5464                 /* sigh, we can't just set blimits/ilimits */
5465                 struct if_quotactl tmp_qctl = {.qc_cmd  = LUSTRE_Q_GETQUOTA,
5466                                                .qc_type = qctl.qc_type,
5467                                                .qc_id   = qctl.qc_id};
5468
5469                 rc = llapi_quotactl(mnt, &tmp_qctl);
5470                 if (rc < 0)
5471                         return rc;
5472
5473                 if (!(limit_mask & BHLIMIT))
5474                         dqb->dqb_bhardlimit = tmp_qctl.qc_dqblk.dqb_bhardlimit;
5475                 if (!(limit_mask & BSLIMIT))
5476                         dqb->dqb_bsoftlimit = tmp_qctl.qc_dqblk.dqb_bsoftlimit;
5477                 if (!(limit_mask & IHLIMIT))
5478                         dqb->dqb_ihardlimit = tmp_qctl.qc_dqblk.dqb_ihardlimit;
5479                 if (!(limit_mask & ISLIMIT))
5480                         dqb->dqb_isoftlimit = tmp_qctl.qc_dqblk.dqb_isoftlimit;
5481
5482                 /* Keep grace times if we have got no softlimit arguments */
5483                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
5484                         dqb->dqb_valid |= QIF_BTIME;
5485                         dqb->dqb_btime = tmp_qctl.qc_dqblk.dqb_btime;
5486                 }
5487
5488                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
5489                         dqb->dqb_valid |= QIF_ITIME;
5490                         dqb->dqb_itime = tmp_qctl.qc_dqblk.dqb_itime;
5491                 }
5492         }
5493
5494         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
5495         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
5496
5497         rc = llapi_quotactl(mnt, &qctl);
5498         if (rc) {
5499                 if (*obd_type)
5500                         fprintf(stderr,
5501                                 "%s setquota: cannot quotactl '%s' '%s': %s",
5502                                 progname, obd_type,
5503                                 obd_uuid2str(&qctl.obd_uuid), strerror(-rc));
5504                 return rc;
5505         }
5506
5507         return 0;
5508 }
5509
5510 /* Converts seconds value into format string
5511  * result is returned in buf
5512  * Notes:
5513  *        1. result is in descenting order: 1w2d3h4m5s
5514  *        2. zero fields are not filled (except for p. 3): 5d1s
5515  *        3. zero seconds value is presented as "0s"
5516  */
5517 static char * __sec2str(time_t seconds, char *buf)
5518 {
5519         const char spec[] = "smhdw";
5520         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
5521         unsigned long c;
5522         char *tail = buf;
5523         int i;
5524
5525         for (i = sizeof(mult) / sizeof(mult[0]) - 1 ; i >= 0; i--) {
5526                 c = seconds / mult[i];
5527
5528                 if (c > 0 || (i == 0 && buf == tail))
5529                         tail += snprintf(tail, 40-(tail-buf), "%lu%c", c, spec[i]);
5530
5531                 seconds %= mult[i];
5532         }
5533
5534         return tail;
5535 }
5536
5537 static void sec2str(time_t seconds, char *buf, int rc)
5538 {
5539         char *tail = buf;
5540
5541         if (rc)
5542                 *tail++ = '[';
5543
5544         tail = __sec2str(seconds, tail);
5545
5546         if (rc && tail - buf < 39) {
5547                 *tail++ = ']';
5548                 *tail++ = 0;
5549         }
5550 }
5551
5552 static void diff2str(time_t seconds, char *buf, time_t now)
5553 {
5554
5555         buf[0] = 0;
5556         if (!seconds)
5557                 return;
5558         if (seconds <= now) {
5559                 strcpy(buf, "none");
5560                 return;
5561         }
5562         __sec2str(seconds - now, buf);
5563 }
5564
5565 static void print_quota_title(char *name, struct if_quotactl *qctl,
5566                               bool human_readable)
5567 {
5568         printf("Disk quotas for %s %s (%cid %u):\n",
5569                qtype_name(qctl->qc_type), name,
5570                *qtype_name(qctl->qc_type), qctl->qc_id);
5571         printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
5572                "Filesystem", human_readable ? "used" : "kbytes",
5573                "quota", "limit", "grace",
5574                "files", "quota", "limit", "grace");
5575 }
5576
5577 static void kbytes2str(__u64 num, char *buf, int buflen, bool h)
5578 {
5579         if (!h) {
5580                 snprintf(buf, buflen, "%ju", (uintmax_t)num);
5581         } else {
5582                 if (num >> 40)
5583                         snprintf(buf, buflen, "%5.4gP",
5584                                  (double)num / ((__u64)1 << 40));
5585                 else if (num >> 30)
5586                         snprintf(buf, buflen, "%5.4gT",
5587                                  (double)num / (1 << 30));
5588                 else if (num >> 20)
5589                         snprintf(buf, buflen, "%5.4gG",
5590                                  (double)num / (1 << 20));
5591                 else if (num >> 10)
5592                         snprintf(buf, buflen, "%5.4gM",
5593                                  (double)num / (1 << 10));
5594                 else
5595                         snprintf(buf, buflen, "%ju%s", (uintmax_t)num, "k");
5596         }
5597 }
5598
5599 #define STRBUF_LEN      32
5600 static void print_quota(char *mnt, struct if_quotactl *qctl, int type,
5601                         int rc, bool h)
5602 {
5603         time_t now;
5604
5605         time(&now);
5606
5607         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA) {
5608                 int bover = 0, iover = 0;
5609                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
5610                 char numbuf[3][STRBUF_LEN];
5611                 char timebuf[40];
5612                 char strbuf[STRBUF_LEN];
5613
5614                 if (dqb->dqb_bhardlimit &&
5615                     lustre_stoqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
5616                         bover = 1;
5617                 } else if (dqb->dqb_bsoftlimit && dqb->dqb_btime) {
5618                         if (dqb->dqb_btime > now) {
5619                                 bover = 2;
5620                         } else {
5621                                 bover = 3;
5622                         }
5623                 }
5624
5625                 if (dqb->dqb_ihardlimit &&
5626                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
5627                         iover = 1;
5628                 } else if (dqb->dqb_isoftlimit && dqb->dqb_itime) {
5629                         if (dqb->dqb_itime > now) {
5630                                 iover = 2;
5631                         } else {
5632                                 iover = 3;
5633                         }
5634                 }
5635
5636
5637                 if (strlen(mnt) > 15)
5638                         printf("%s\n%15s", mnt, "");
5639                 else
5640                         printf("%15s", mnt);
5641
5642                 if (bover)
5643                         diff2str(dqb->dqb_btime, timebuf, now);
5644
5645                 kbytes2str(lustre_stoqb(dqb->dqb_curspace),
5646                            strbuf, sizeof(strbuf), h);
5647                 if (rc == -EREMOTEIO)
5648                         sprintf(numbuf[0], "%s*", strbuf);
5649                 else
5650                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
5651                                 "%s" : "[%s]", strbuf);
5652
5653                 kbytes2str(dqb->dqb_bsoftlimit, strbuf, sizeof(strbuf), h);
5654                 if (type == QC_GENERAL)
5655                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS) ?
5656                                 "%s" : "[%s]", strbuf);
5657                 else
5658                         sprintf(numbuf[1], "%s", "-");
5659
5660                 kbytes2str(dqb->dqb_bhardlimit, strbuf, sizeof(strbuf), h);
5661                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS) ?
5662                         "%s" : "[%s]", strbuf);
5663
5664                 printf(" %7s%c %6s %7s %7s",
5665                        numbuf[0], bover ? '*' : ' ', numbuf[1],
5666                        numbuf[2], bover > 1 ? timebuf : "-");
5667
5668                 if (iover)
5669                         diff2str(dqb->dqb_itime, timebuf, now);
5670
5671                 sprintf(numbuf[0], (dqb->dqb_valid & QIF_INODES) ?
5672                         "%ju" : "[%ju]", (uintmax_t)dqb->dqb_curinodes);
5673
5674                 if (type == QC_GENERAL)
5675                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS) ?
5676                                 "%ju" : "[%ju]",
5677                                 (uintmax_t)dqb->dqb_isoftlimit);
5678                 else
5679                         sprintf(numbuf[1], "%s", "-");
5680
5681                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
5682                         "%ju" : "[%ju]", (uintmax_t)dqb->dqb_ihardlimit);
5683
5684                 if (type != QC_OSTIDX)
5685                         printf(" %7s%c %6s %7s %7s",
5686                                numbuf[0], iover ? '*' : ' ', numbuf[1],
5687                                numbuf[2], iover > 1 ? timebuf : "-");
5688                 else
5689                         printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
5690                 printf("\n");
5691
5692         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO ||
5693                    qctl->qc_cmd == Q_GETOINFO) {
5694                 char bgtimebuf[40];
5695                 char igtimebuf[40];
5696
5697                 sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
5698                 sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
5699                 printf("Block grace time: %s; Inode grace time: %s\n",
5700                        bgtimebuf, igtimebuf);
5701         }
5702 }
5703
5704 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt,
5705                            bool h, __u64 *total)
5706 {
5707         int rc = 0, rc1 = 0, count = 0;
5708         __u32 valid = qctl->qc_valid;
5709
5710         rc = llapi_get_obd_count(mnt, &count, is_mdt);
5711         if (rc) {
5712                 fprintf(stderr, "can not get %s count: %s\n",
5713                         is_mdt ? "mdt": "ost", strerror(-rc));
5714                 return rc;
5715         }
5716
5717         for (qctl->qc_idx = 0; qctl->qc_idx < count; qctl->qc_idx++) {
5718                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
5719                 rc = llapi_quotactl(mnt, qctl);
5720                 if (rc) {
5721                         /* It is remote client case. */
5722                         if (rc == -EOPNOTSUPP) {
5723                                 rc = 0;
5724                                 goto out;
5725                         }
5726
5727                         if (!rc1)
5728                                 rc1 = rc;
5729                         fprintf(stderr, "quotactl %s%d failed.\n",
5730                                 is_mdt ? "mdt": "ost", qctl->qc_idx);
5731                         continue;
5732                 }
5733
5734                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl,
5735                             qctl->qc_valid, 0, h);
5736                 *total += is_mdt ? qctl->qc_dqblk.dqb_ihardlimit :
5737                                    qctl->qc_dqblk.dqb_bhardlimit;
5738         }
5739 out:
5740         qctl->qc_valid = valid;
5741         return rc ? : rc1;
5742 }
5743
5744 static int get_print_quota(char *mnt, char *name, struct if_quotactl *qctl,
5745                            int verbose, int quiet, bool human_readable)
5746 {
5747         int rc1 = 0, rc2 = 0, rc3 = 0;
5748         char *obd_type = (char *)qctl->obd_type;
5749         char *obd_uuid = (char *)qctl->obd_uuid.uuid;
5750         __u64 total_ialloc = 0, total_balloc = 0;
5751         int inacc;
5752
5753         rc1 = llapi_quotactl(mnt, qctl);
5754         if (rc1 < 0) {
5755                 switch (rc1) {
5756                 case -ESRCH:
5757                         fprintf(stderr, "%s quotas are not enabled.\n",
5758                                 qtype_name(qctl->qc_type));
5759                         goto out;
5760                 case -EPERM:
5761                         fprintf(stderr, "Permission denied.\n");
5762                 case -ENODEV:
5763                 case -ENOENT:
5764                         /* We already got error message. */
5765                         goto out;
5766                 default:
5767                         fprintf(stderr, "Unexpected quotactl error: %s\n",
5768                                 strerror(-rc1));
5769                 }
5770         }
5771
5772         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA && !quiet)
5773                 print_quota_title(name, qctl, human_readable);
5774
5775         if (rc1 && *obd_type)
5776                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
5777
5778         if (qctl->qc_valid != QC_GENERAL)
5779                 mnt = "";
5780
5781         inacc = (qctl->qc_cmd == LUSTRE_Q_GETQUOTA) &&
5782                 ((qctl->qc_dqblk.dqb_valid & (QIF_LIMITS|QIF_USAGE)) !=
5783                  (QIF_LIMITS|QIF_USAGE));
5784
5785         print_quota(mnt, qctl, QC_GENERAL, rc1, human_readable);
5786
5787         if (qctl->qc_valid == QC_GENERAL && qctl->qc_cmd != LUSTRE_Q_GETINFO &&
5788             verbose) {
5789                 char strbuf[STRBUF_LEN];
5790
5791                 rc2 = print_obd_quota(mnt, qctl, 1, human_readable,
5792                                       &total_ialloc);
5793                 rc3 = print_obd_quota(mnt, qctl, 0, human_readable,
5794                                       &total_balloc);
5795                 kbytes2str(total_balloc, strbuf, sizeof(strbuf),
5796                            human_readable);
5797                 printf("Total allocated inode limit: %ju, total "
5798                        "allocated block limit: %s\n", (uintmax_t)total_ialloc,
5799                        strbuf);
5800         }
5801
5802         if (rc1 || rc2 || rc3 || inacc)
5803                 printf("Some errors happened when getting quota info. "
5804                        "Some devices may be not working or deactivated. "
5805                        "The data in \"[]\" is inaccurate.\n");
5806 out:
5807         return rc1;
5808
5809 }
5810
5811 static int lfs_project(int argc, char **argv)
5812 {
5813         int ret = 0, err = 0, c, i;
5814         struct project_handle_control phc = { 0 };
5815         enum lfs_project_ops_t op;
5816
5817         phc.newline = true;
5818         phc.assign_projid = false;
5819         /* default action */
5820         op = LFS_PROJECT_LIST;
5821
5822         while ((c = getopt(argc, argv, "p:cCsdkr0")) != -1) {
5823                 switch (c) {
5824                 case 'c':
5825                         if (op != LFS_PROJECT_LIST) {
5826                                 fprintf(stderr,
5827                                         "%s: cannot specify '-c' '-C' '-s' together\n",
5828                                         progname);
5829                                 return CMD_HELP;
5830                         }
5831
5832                         op = LFS_PROJECT_CHECK;
5833                         break;
5834                 case 'C':
5835                         if (op != LFS_PROJECT_LIST) {
5836                                 fprintf(stderr,
5837                                         "%s: cannot specify '-c' '-C' '-s' together\n",
5838                                         progname);
5839                                 return CMD_HELP;
5840                         }
5841
5842                         op = LFS_PROJECT_CLEAR;
5843                         break;
5844                 case 's':
5845                         if (op != LFS_PROJECT_LIST) {
5846                                 fprintf(stderr,
5847                                         "%s: cannot specify '-c' '-C' '-s' together\n",
5848                                         progname);
5849                                 return CMD_HELP;
5850                         }
5851
5852                         phc.set_inherit = true;
5853                         op = LFS_PROJECT_SET;
5854                         break;
5855                 case 'd':
5856                         phc.dironly = true;
5857                         break;
5858                 case 'k':
5859                         phc.keep_projid = true;
5860                         break;
5861                 case 'r':
5862                         phc.recursive = true;
5863                         break;
5864                 case 'p':
5865                         phc.projid = strtoul(optarg, NULL, 0);
5866                         phc.assign_projid = true;
5867
5868                         break;
5869                 case '0':
5870                         phc.newline = false;
5871                         break;
5872                 default:
5873                         fprintf(stderr, "%s: invalid option '%c'\n",
5874                                 progname, optopt);
5875                         return CMD_HELP;
5876                 }
5877         }
5878
5879         if (phc.assign_projid && op == LFS_PROJECT_LIST) {
5880                 op = LFS_PROJECT_SET;
5881                 phc.set_projid = true;
5882         } else if (phc.assign_projid && op == LFS_PROJECT_SET) {
5883                 phc.set_projid = true;
5884         }
5885
5886         switch (op) {
5887         case LFS_PROJECT_CHECK:
5888                 if (phc.keep_projid) {
5889                         fprintf(stderr,
5890                                 "%s: '-k' is useless together with '-c'\n",
5891                                 progname);
5892                         return CMD_HELP;
5893                 }
5894                 break;
5895         case LFS_PROJECT_CLEAR:
5896                 if (!phc.newline) {
5897                         fprintf(stderr,
5898                                 "%s: '-0' is useless together with '-C'\n",
5899                                 progname);
5900                         return CMD_HELP;
5901                 }
5902                 if (phc.assign_projid) {
5903                         fprintf(stderr,
5904                                 "%s: '-p' is useless together with '-C'\n",
5905                                 progname);
5906                         return CMD_HELP;
5907                 }
5908                 break;
5909         case LFS_PROJECT_SET:
5910                 if (!phc.newline) {
5911                         fprintf(stderr,
5912                                 "%s: '-0' is useless together with '-s'\n",
5913                                 progname);
5914                         return CMD_HELP;
5915                 }
5916                 if (phc.keep_projid) {
5917                         fprintf(stderr,
5918                                 "%s: '-k' is useless together with '-s'\n",
5919                                 progname);
5920                         return CMD_HELP;
5921                 }
5922                 break;
5923         default:
5924                 if (!phc.newline) {
5925                         fprintf(stderr,
5926                                 "%s: '-0' is useless for list operations\n",
5927                                 progname);
5928                         return CMD_HELP;
5929                 }
5930                 break;
5931         }
5932
5933         argv += optind;
5934         argc -= optind;
5935         if (argc == 0) {
5936                 fprintf(stderr, "%s: missing file or directory target(s)\n",
5937                         progname);
5938                 return CMD_HELP;
5939         }
5940
5941         for (i = 0; i < argc; i++) {
5942                 switch (op) {
5943                 case LFS_PROJECT_CHECK:
5944                         err = lfs_project_check(argv[i], &phc);
5945                         break;
5946                 case LFS_PROJECT_LIST:
5947                         err = lfs_project_list(argv[i], &phc);
5948                         break;
5949                 case LFS_PROJECT_CLEAR:
5950                         err = lfs_project_clear(argv[i], &phc);
5951                         break;
5952                 case LFS_PROJECT_SET:
5953                         err = lfs_project_set(argv[i], &phc);
5954                         break;
5955                 default:
5956                         break;
5957                 }
5958                 if (err && !ret)
5959                         ret = err;
5960         }
5961
5962         return ret;
5963 }
5964
5965 static int lfs_quota(int argc, char **argv)
5966 {
5967         int c;
5968         char *mnt, *name = NULL;
5969         struct if_quotactl qctl = { .qc_cmd = LUSTRE_Q_GETQUOTA,
5970                                     .qc_type = ALLQUOTA };
5971         char *obd_uuid = (char *)qctl.obd_uuid.uuid;
5972         int rc = 0, rc1 = 0, verbose = 0, quiet = 0;
5973         char *endptr;
5974         __u32 valid = QC_GENERAL, idx = 0;
5975         bool human_readable = false;
5976         int qtype;
5977
5978         while ((c = getopt(argc, argv, "gi:I:o:pqtuvh")) != -1) {
5979                 switch (c) {
5980                 case 'u':
5981                         qtype = USRQUOTA;
5982                         goto quota_type;
5983                 case 'g':
5984                         qtype = GRPQUOTA;
5985                         goto quota_type;
5986                 case 'p':
5987                         qtype = PRJQUOTA;
5988 quota_type:
5989                         if (qctl.qc_type != ALLQUOTA) {
5990                                 fprintf(stderr,
5991                                         "%s quota: only one of -u, -g, or -p may be specified\n",
5992                                         progname);
5993                                 return CMD_HELP;
5994                         }
5995                         qctl.qc_type = qtype;
5996                         break;
5997                 case 't':
5998                         qctl.qc_cmd = LUSTRE_Q_GETINFO;
5999                         break;
6000                 case 'o':
6001                         valid = qctl.qc_valid = QC_UUID;
6002                         snprintf(obd_uuid, sizeof(qctl.obd_uuid), "%s", optarg);
6003                         break;
6004                 case 'i':
6005                         valid = qctl.qc_valid = QC_MDTIDX;
6006                         idx = qctl.qc_idx = atoi(optarg);
6007                         if (idx == 0 && *optarg != '0') {
6008                                 fprintf(stderr,
6009                                         "%s quota: invalid MDT index '%s'\n",
6010                                         progname, optarg);
6011                                 return CMD_HELP;
6012                         }
6013                         break;
6014                 case 'I':
6015                         valid = qctl.qc_valid = QC_OSTIDX;
6016                         idx = qctl.qc_idx = atoi(optarg);
6017                         if (idx == 0 && *optarg != '0') {
6018                                 fprintf(stderr,
6019                                         "%s quota: invalid OST index '%s'\n",
6020                                         progname, optarg);
6021                                 return CMD_HELP;
6022                         }
6023                         break;
6024                 case 'v':
6025                         verbose = 1;
6026                         break;
6027                 case 'q':
6028                         quiet = 1;
6029                         break;
6030                 case 'h':
6031                         human_readable = true;
6032                         break;
6033                 default:
6034                         fprintf(stderr, "%s quota: unrecognized option '%s'\n",
6035                                 progname, argv[optind - 1]);
6036                         return CMD_HELP;
6037                 }
6038         }
6039
6040         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
6041         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA && qctl.qc_type == ALLQUOTA &&
6042             optind == argc - 1) {
6043
6044                 qctl.qc_cmd = LUSTRE_Q_GETQUOTA;
6045                 qctl.qc_valid = valid;
6046                 qctl.qc_idx = idx;
6047
6048                 for (qtype = USRQUOTA; qtype <= GRPQUOTA; qtype++) {
6049                         qctl.qc_type = qtype;
6050                         if (qtype == USRQUOTA) {
6051                                 qctl.qc_id = geteuid();
6052                                 rc = uid2name(&name, qctl.qc_id);
6053                         } else {
6054                                 qctl.qc_id = getegid();
6055                                 rc = gid2name(&name, qctl.qc_id);
6056                         }
6057                         if (rc)
6058                                 name = "<unknown>";
6059                         mnt = argv[optind];
6060                         rc1 = get_print_quota(mnt, name, &qctl, verbose, quiet,
6061                                               human_readable);
6062                         if (rc1 && !rc)
6063                                 rc = rc1;
6064                 }
6065         /* lfs quota -u username /path/to/lustre/mount */
6066         } else if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) {
6067                 /* options should be followed by u/g-name and mntpoint */
6068                 if (optind + 2 != argc || qctl.qc_type == ALLQUOTA) {
6069                         fprintf(stderr,
6070                                 "%s quota: name and mount point must be specified\n",
6071                                 progname);
6072                         return CMD_HELP;
6073                 }
6074
6075                 name = argv[optind++];
6076                 switch (qctl.qc_type) {
6077                 case USRQUOTA:
6078                         rc = name2uid(&qctl.qc_id, name);
6079                         break;
6080                 case GRPQUOTA:
6081                         rc = name2gid(&qctl.qc_id, name);
6082                         break;
6083                 case PRJQUOTA:
6084                         rc = name2projid(&qctl.qc_id, name);
6085                         break;
6086                 default:
6087                         rc = -ENOTSUP;
6088                         break;
6089                 }
6090                 if (rc) {
6091                         qctl.qc_id = strtoul(name, &endptr, 10);
6092                         if (*endptr != '\0') {
6093                                 fprintf(stderr, "%s quota: invalid id '%s'\n",
6094                                         progname, name);
6095                                 return CMD_HELP;
6096                         }
6097                 }
6098                 mnt = argv[optind];
6099                 rc = get_print_quota(mnt, name, &qctl, verbose, quiet,
6100                                      human_readable);
6101         } else if (optind + 1 != argc || qctl.qc_type == ALLQUOTA) {
6102                 fprintf(stderr, "%s quota: missing quota info argument(s)\n",
6103                         progname);
6104                 return CMD_HELP;
6105         }
6106
6107         return rc;
6108 }
6109 #endif /* HAVE_SYS_QUOTA_H! */
6110
6111 static int flushctx_ioctl(char *mp)
6112 {
6113         int fd, rc;
6114
6115         fd = open(mp, O_RDONLY);
6116         if (fd == -1) {
6117                 fprintf(stderr, "flushctx: error open %s: %s\n",
6118                         mp, strerror(errno));
6119                 return -1;
6120         }
6121
6122         rc = ioctl(fd, LL_IOC_FLUSHCTX);
6123         if (rc == -1)
6124                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
6125                         mp, strerror(errno));
6126
6127         close(fd);
6128         return rc;
6129 }
6130
6131 static int lfs_flushctx(int argc, char **argv)
6132 {
6133         int     kdestroy = 0, c;
6134         char    mntdir[PATH_MAX] = {'\0'};
6135         int     index = 0;
6136         int     rc = 0;
6137
6138         while ((c = getopt(argc, argv, "k")) != -1) {
6139                 switch (c) {
6140                 case 'k':
6141                         kdestroy = 1;
6142                         break;
6143                 default:
6144                         fprintf(stderr, "error: %s: option '-%c' "
6145                                         "unrecognized\n", argv[0], c);
6146                         return CMD_HELP;
6147                 }
6148         }
6149
6150         if (kdestroy) {
6151             if ((rc = system("kdestroy > /dev/null")) != 0) {
6152                 rc = WEXITSTATUS(rc);
6153                 fprintf(stderr, "error destroying tickets: %d, continuing\n", rc);
6154             }
6155         }
6156
6157         if (optind >= argc) {
6158                 /* flush for all mounted lustre fs. */
6159                 while (!llapi_search_mounts(NULL, index++, mntdir, NULL)) {
6160                         /* Check if we have a mount point */
6161                         if (mntdir[0] == '\0')
6162                                 continue;
6163
6164                         if (flushctx_ioctl(mntdir))
6165                                 rc = -1;
6166
6167                         mntdir[0] = '\0'; /* avoid matching in next loop */
6168                 }
6169         } else {
6170                 /* flush fs as specified */
6171                 while (optind < argc) {
6172                         if (flushctx_ioctl(argv[optind++]))
6173                                 rc = -1;
6174                 }
6175         }
6176         return rc;
6177 }
6178
6179 static int lfs_cp(int argc, char **argv)
6180 {
6181         fprintf(stderr, "remote client copy file(s).\n"
6182                 "obsolete, does not support it anymore.\n");
6183         return 0;
6184 }
6185
6186 static int lfs_ls(int argc, char **argv)
6187 {
6188         fprintf(stderr, "remote client lists directory contents.\n"
6189                 "obsolete, does not support it anymore.\n");
6190         return 0;
6191 }
6192
6193 static int lfs_changelog(int argc, char **argv)
6194 {
6195         void *changelog_priv;
6196         struct changelog_rec *rec;
6197         long long startrec = 0, endrec = 0;
6198         char *mdd;
6199         struct option long_opts[] = {
6200                 { .val = 'f', .name = "follow", .has_arg = no_argument },
6201                 { .name = NULL } };
6202         char short_opts[] = "f";
6203         int rc, follow = 0;
6204
6205         while ((rc = getopt_long(argc, argv, short_opts,
6206                 long_opts, NULL)) != -1) {
6207                 switch (rc) {
6208                 case 'f':
6209                         follow++;
6210                         break;
6211                 case '?':
6212                         return CMD_HELP;
6213                 default:
6214                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
6215                                 argv[0], argv[optind - 1]);
6216                         return CMD_HELP;
6217                 }
6218         }
6219         if (optind >= argc)
6220                 return CMD_HELP;
6221
6222         mdd = argv[optind++];
6223         if (argc > optind)
6224                 startrec = strtoll(argv[optind++], NULL, 10);
6225         if (argc > optind)
6226                 endrec = strtoll(argv[optind++], NULL, 10);
6227
6228         rc = llapi_changelog_start(&changelog_priv,
6229                                    CHANGELOG_FLAG_BLOCK |
6230                                    CHANGELOG_FLAG_JOBID |
6231                                    CHANGELOG_FLAG_EXTRA_FLAGS |
6232                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
6233                                    mdd, startrec);
6234         if (rc < 0) {
6235                 fprintf(stderr, "Can't start changelog: %s\n",
6236                         strerror(errno = -rc));
6237                 return rc;
6238         }
6239
6240         rc = llapi_changelog_set_xflags(changelog_priv,
6241                                         CHANGELOG_EXTRA_FLAG_UIDGID |
6242                                         CHANGELOG_EXTRA_FLAG_NID |
6243                                         CHANGELOG_EXTRA_FLAG_OMODE |
6244                                         CHANGELOG_EXTRA_FLAG_XATTR);
6245         if (rc < 0) {
6246                 fprintf(stderr, "Can't set xflags for changelog: %s\n",
6247                         strerror(errno = -rc));
6248                 return rc;
6249         }
6250
6251         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
6252                 time_t secs;
6253                 struct tm ts;
6254
6255                 if (endrec && rec->cr_index > endrec) {
6256                         llapi_changelog_free(&rec);
6257                         break;
6258                 }
6259                 if (rec->cr_index < startrec) {
6260                         llapi_changelog_free(&rec);
6261                         continue;
6262                 }
6263
6264                 secs = rec->cr_time >> 30;
6265                 gmtime_r(&secs, &ts);
6266                 printf("%ju %02d%-5s %02d:%02d:%02d.%09d %04d.%02d.%02d "
6267                        "0x%x t="DFID, (uintmax_t)rec->cr_index, rec->cr_type,
6268                        changelog_type2str(rec->cr_type),
6269                        ts.tm_hour, ts.tm_min, ts.tm_sec,
6270                        (int)(rec->cr_time & ((1 << 30) - 1)),
6271                        ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday,
6272                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
6273
6274                 if (rec->cr_flags & CLF_JOBID) {
6275                         struct changelog_ext_jobid *jid =
6276                                 changelog_rec_jobid(rec);
6277
6278                         if (jid->cr_jobid[0] != '\0')
6279                                 printf(" j=%s", jid->cr_jobid);
6280                 }
6281
6282                 if (rec->cr_flags & CLF_EXTRA_FLAGS) {
6283                         struct changelog_ext_extra_flags *ef =
6284                                 changelog_rec_extra_flags(rec);
6285
6286                         printf(" ef=0x%llx", ef->cr_extra_flags);
6287
6288                         if (ef->cr_extra_flags & CLFE_UIDGID) {
6289                                 struct changelog_ext_uidgid *uidgid =
6290                                         changelog_rec_uidgid(rec);
6291
6292                                 printf(" u=%llu:%llu",
6293                                        uidgid->cr_uid, uidgid->cr_gid);
6294                         }
6295                         if (ef->cr_extra_flags & CLFE_NID) {
6296                                 struct changelog_ext_nid *nid =
6297                                         changelog_rec_nid(rec);
6298
6299                                 printf(" nid=%s",
6300                                        libcfs_nid2str(nid->cr_nid));
6301                         }
6302
6303                         if (ef->cr_extra_flags & CLFE_OPEN) {
6304                                 struct changelog_ext_openmode *omd =
6305                                         changelog_rec_openmode(rec);
6306                                 char mode[] = "---";
6307
6308                                 /* exec mode must be exclusive */
6309                                 if (omd->cr_openflags & MDS_FMODE_EXEC) {
6310                                         mode[2] = 'x';
6311                                 } else {
6312                                         if (omd->cr_openflags & FMODE_READ)
6313                                                 mode[0] = 'r';
6314                                         if (omd->cr_openflags &
6315                                             (FMODE_WRITE |
6316                                              MDS_OPEN_TRUNC |
6317                                              MDS_OPEN_APPEND))
6318                                                 mode[1] = 'w';
6319                                 }
6320
6321                                 if (strcmp(mode, "---") != 0)
6322                                         printf(" m=%s", mode);
6323
6324                         }
6325
6326                         if (ef->cr_extra_flags & CLFE_XATTR) {
6327                                 struct changelog_ext_xattr *xattr =
6328                                         changelog_rec_xattr(rec);
6329
6330                                 if (xattr->cr_xattr[0] != '\0')
6331                                         printf(" x=%s", xattr->cr_xattr);
6332                         }
6333                 }
6334
6335                 if (rec->cr_namelen)
6336                         printf(" p="DFID" %.*s", PFID(&rec->cr_pfid),
6337                                rec->cr_namelen, changelog_rec_name(rec));
6338
6339                 if (rec->cr_flags & CLF_RENAME) {
6340                         struct changelog_ext_rename *rnm =
6341                                 changelog_rec_rename(rec);
6342
6343                         if (!fid_is_zero(&rnm->cr_sfid))
6344                                 printf(" s="DFID" sp="DFID" %.*s",
6345                                        PFID(&rnm->cr_sfid),
6346                                        PFID(&rnm->cr_spfid),
6347                                        (int)changelog_rec_snamelen(rec),
6348                                        changelog_rec_sname(rec));
6349                 }
6350                 printf("\n");
6351
6352                 llapi_changelog_free(&rec);
6353         }
6354
6355         llapi_changelog_fini(&changelog_priv);
6356
6357         if (rc < 0)
6358                 fprintf(stderr, "Changelog: %s\n", strerror(errno = -rc));
6359
6360         return (rc == 1 ? 0 : rc);
6361 }
6362
6363 static int lfs_changelog_clear(int argc, char **argv)
6364 {
6365         long long endrec;
6366         int rc;
6367
6368         if (argc != 4)
6369                 return CMD_HELP;
6370
6371         endrec = strtoll(argv[3], NULL, 10);
6372
6373         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
6374
6375         if (rc == -EINVAL)
6376                 fprintf(stderr, "%s: record out of range: %llu\n",
6377                         argv[0], endrec);
6378         else if (rc == -ENOENT)
6379                 fprintf(stderr, "%s: no changelog user: %s\n",
6380                         argv[0], argv[2]);
6381         else if (rc)
6382                 fprintf(stderr, "%s error: %s\n", argv[0],
6383                         strerror(-rc));
6384
6385         if (rc)
6386                 errno = -rc;
6387
6388         return rc;
6389 }
6390
6391 static int lfs_fid2path(int argc, char **argv)
6392 {
6393         struct option long_opts[] = {
6394                 { .val = 'c',   .name = "cur",  .has_arg = no_argument },
6395                 { .val = 'l',   .name = "link", .has_arg = required_argument },
6396                 { .val = 'r',   .name = "rec",  .has_arg = required_argument },
6397                 { .name = NULL } };
6398         char  short_opts[] = "cl:r:";
6399         char *device, *fid, *path;
6400         long long recno = -1;
6401         int linkno = -1;
6402         int lnktmp;
6403         int printcur = 0;
6404         int rc = 0;
6405
6406         while ((rc = getopt_long(argc, argv, short_opts,
6407                 long_opts, NULL)) != -1) {
6408                 switch (rc) {
6409                 case 'c':
6410                         printcur++;
6411                         break;
6412                 case 'l':
6413                         linkno = strtol(optarg, NULL, 10);
6414                         break;
6415                 case 'r':
6416                         recno = strtoll(optarg, NULL, 10);
6417                         break;
6418                 case '?':
6419                         return CMD_HELP;
6420                 default:
6421                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
6422                                 argv[0], argv[optind - 1]);
6423                         return CMD_HELP;
6424                 }
6425         }
6426
6427         if (argc < 3)
6428                 return CMD_HELP;
6429
6430         device = argv[optind++];
6431         path = calloc(1, PATH_MAX);
6432         if (path == NULL) {
6433                 fprintf(stderr, "error: Not enough memory\n");
6434                 return -errno;
6435         }
6436
6437         rc = 0;
6438         while (optind < argc) {
6439                 fid = argv[optind++];
6440
6441                 lnktmp = (linkno >= 0) ? linkno : 0;
6442                 while (1) {
6443                         int oldtmp = lnktmp;
6444                         long long rectmp = recno;
6445                         int rc2;
6446                         rc2 = llapi_fid2path(device, fid, path, PATH_MAX,
6447                                              &rectmp, &lnktmp);
6448                         if (rc2 < 0) {
6449                                 fprintf(stderr, "%s: error on FID %s: %s\n",
6450                                         argv[0], fid, strerror(errno = -rc2));
6451                                 if (rc == 0)
6452                                         rc = rc2;
6453                                 break;
6454                         }
6455
6456                         if (printcur)
6457                                 fprintf(stdout, "%lld ", rectmp);
6458                         if (device[0] == '/') {
6459                                 fprintf(stdout, "%s", device);
6460                                 if (device[strlen(device) - 1] != '/')
6461                                         fprintf(stdout, "/");
6462                         } else if (path[0] == '\0') {
6463                                 fprintf(stdout, "/");
6464                         }
6465                         fprintf(stdout, "%s\n", path);
6466
6467                         if (linkno >= 0)
6468                                 /* specified linkno */
6469                                 break;
6470                         if (oldtmp == lnktmp)
6471                                 /* no more links */
6472                                 break;
6473                 }
6474         }
6475
6476         free(path);
6477         return rc;
6478 }
6479
6480 static int lfs_path2fid(int argc, char **argv)
6481 {
6482         struct option long_opts[] = {
6483                 { .val = 'p', .name = "parents", .has_arg = no_argument },
6484                 { .name = NULL } };
6485         char            **path;
6486         const char        short_opts[] = "p";
6487         const char       *sep = "";
6488         struct lu_fid     fid;
6489         int               rc = 0;
6490         bool              show_parents = false;
6491
6492         while ((rc = getopt_long(argc, argv, short_opts,
6493                                  long_opts, NULL)) != -1) {
6494                 switch (rc) {
6495                 case 'p':
6496                         show_parents = true;
6497                         break;
6498                 default:
6499                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
6500                                 argv[0], argv[optind - 1]);
6501                         return CMD_HELP;
6502                 }
6503         }
6504
6505         if (optind > argc - 1)
6506                 return CMD_HELP;
6507         else if (optind < argc - 1)
6508                 sep = ": ";
6509
6510         rc = 0;
6511         for (path = argv + optind; *path != NULL; path++) {
6512                 int err = 0;
6513                 if (!show_parents) {
6514                         err = llapi_path2fid(*path, &fid);
6515                         if (!err)
6516                                 printf("%s%s"DFID"\n",
6517                                        *sep != '\0' ? *path : "", sep,
6518                                        PFID(&fid));
6519                 } else {
6520                         char            name[NAME_MAX + 1];
6521                         unsigned int    linkno = 0;
6522
6523                         while ((err = llapi_path2parent(*path, linkno, &fid,
6524                                                 name, sizeof(name))) == 0) {
6525                                 if (*sep != '\0' && linkno == 0)
6526                                         printf("%s%s", *path, sep);
6527
6528                                 printf("%s"DFID"/%s", linkno != 0 ? "\t" : "",
6529                                        PFID(&fid), name);
6530                                 linkno++;
6531                         }
6532
6533                         /* err == -ENODATA is end-of-loop */
6534                         if (linkno > 0 && err == -ENODATA) {
6535                                 printf("\n");
6536                                 err = 0;
6537                         }
6538                 }
6539
6540                 if (err) {
6541                         fprintf(stderr, "%s: can't get %sfid for %s: %s\n",
6542                                 argv[0], show_parents ? "parent " : "", *path,
6543                                 strerror(-err));
6544                         if (rc == 0) {
6545                                 rc = err;
6546                                 errno = -err;
6547                         }
6548                 }
6549         }
6550
6551         return rc;
6552 }
6553
6554 static int lfs_data_version(int argc, char **argv)
6555 {
6556         char *path;
6557         __u64 data_version;
6558         int fd;
6559         int rc;
6560         int c;
6561         int data_version_flags = LL_DV_RD_FLUSH; /* Read by default */
6562
6563         if (argc < 2)
6564                 return CMD_HELP;
6565
6566         while ((c = getopt(argc, argv, "nrw")) != -1) {
6567                 switch (c) {
6568                 case 'n':
6569                         data_version_flags = 0;
6570                         break;
6571                 case 'r':
6572                         data_version_flags |= LL_DV_RD_FLUSH;
6573                         break;
6574                 case 'w':
6575                         data_version_flags |= LL_DV_WR_FLUSH;
6576                         break;
6577                 default:
6578                         return CMD_HELP;
6579                 }
6580         }
6581         if (optind == argc)
6582                 return CMD_HELP;
6583
6584         path = argv[optind];
6585         fd = open(path, O_RDONLY);
6586         if (fd < 0)
6587                 err(errno, "cannot open file %s", path);
6588
6589         rc = llapi_get_data_version(fd, &data_version, data_version_flags);
6590         if (rc < 0)
6591                 err(errno, "cannot get version for %s", path);
6592         else
6593                 printf("%ju" "\n", (uintmax_t)data_version);
6594
6595         close(fd);
6596         return rc;
6597 }
6598
6599 static int lfs_hsm_state(int argc, char **argv)
6600 {
6601         int rc;
6602         int i = 1;
6603         char *path;
6604         struct hsm_user_state hus;
6605
6606         if (argc < 2)
6607                 return CMD_HELP;
6608
6609         do {
6610                 path = argv[i];
6611
6612                 rc = llapi_hsm_state_get(path, &hus);
6613                 if (rc) {
6614                         fprintf(stderr, "can't get hsm state for %s: %s\n",
6615                                 path, strerror(errno = -rc));
6616                         return rc;
6617                 }
6618
6619                 /* Display path name and status flags */
6620                 printf("%s: (0x%08x)", path, hus.hus_states);
6621
6622                 if (hus.hus_states & HS_RELEASED)
6623                         printf(" released");
6624                 if (hus.hus_states & HS_EXISTS)
6625                         printf(" exists");
6626                 if (hus.hus_states & HS_DIRTY)
6627                         printf(" dirty");
6628                 if (hus.hus_states & HS_ARCHIVED)
6629                         printf(" archived");
6630                 /* Display user-settable flags */
6631                 if (hus.hus_states & HS_NORELEASE)
6632                         printf(" never_release");
6633                 if (hus.hus_states & HS_NOARCHIVE)
6634                         printf(" never_archive");
6635                 if (hus.hus_states & HS_LOST)
6636                         printf(" lost_from_hsm");
6637
6638                 if (hus.hus_archive_id != 0)
6639                         printf(", archive_id:%d", hus.hus_archive_id);
6640                 printf("\n");
6641
6642         } while (++i < argc);
6643
6644         return 0;
6645 }
6646
6647 #define LFS_HSM_SET   0
6648 #define LFS_HSM_CLEAR 1
6649
6650 /**
6651  * Generic function to set or clear HSM flags.
6652  * Used by hsm_set and hsm_clear.
6653  *
6654  * @mode  if LFS_HSM_SET, set the flags, if LFS_HSM_CLEAR, clear the flags.
6655  */
6656 static int lfs_hsm_change_flags(int argc, char **argv, int mode)
6657 {
6658         struct option long_opts[] = {
6659         { .val = 'A',   .name = "archived",     .has_arg = no_argument },
6660         { .val = 'a',   .name = "noarchive",    .has_arg = no_argument },
6661         { .val = 'd',   .name = "dirty",        .has_arg = no_argument },
6662         { .val = 'e',   .name = "exists",       .has_arg = no_argument },
6663         { .val = 'l',   .name = "lost",         .has_arg = no_argument },
6664         { .val = 'r',   .name = "norelease",    .has_arg = no_argument },
6665         { .val = 'i',   .name = "archive-id",   .has_arg = required_argument },
6666         { .name = NULL } };
6667         char short_opts[] = "lraAdei:";
6668         __u64 mask = 0;
6669         int c, rc;
6670         char *path;
6671         __u32 archive_id = 0;
6672         char *end = NULL;
6673
6674         if (argc < 3)
6675                 return CMD_HELP;
6676
6677         while ((c = getopt_long(argc, argv, short_opts,
6678                                 long_opts, NULL)) != -1) {
6679                 switch (c) {
6680                 case 'l':
6681                         mask |= HS_LOST;
6682                         break;
6683                 case 'a':
6684                         mask |= HS_NOARCHIVE;
6685                         break;
6686                 case 'A':
6687                         mask |= HS_ARCHIVED;
6688                         break;
6689                 case 'r':
6690                         mask |= HS_NORELEASE;
6691                         break;
6692                 case 'd':
6693                         mask |= HS_DIRTY;
6694                         break;
6695                 case 'e':
6696                         mask |= HS_EXISTS;
6697                         break;
6698                 case 'i':
6699                         archive_id = strtol(optarg, &end, 10);
6700                         if (*end != '\0') {
6701                                 fprintf(stderr, "invalid archive_id: '%s'\n",
6702                                         end);
6703                                 return CMD_HELP;
6704                         }
6705                         break;
6706                 case '?':
6707                         return CMD_HELP;
6708                 default:
6709                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
6710                                 argv[0], argv[optind - 1]);
6711                         return CMD_HELP;
6712                 }
6713         }
6714
6715         /* User should have specified a flag */
6716         if (mask == 0)
6717                 return CMD_HELP;
6718
6719         while (optind < argc) {
6720
6721                 path = argv[optind];
6722
6723                 /* If mode == 0, this means we apply the mask. */
6724                 if (mode == LFS_HSM_SET)
6725                         rc = llapi_hsm_state_set(path, mask, 0, archive_id);
6726                 else
6727                         rc = llapi_hsm_state_set(path, 0, mask, 0);
6728
6729                 if (rc != 0) {
6730                         fprintf(stderr, "Can't change hsm flags for %s: %s\n",
6731                                 path, strerror(errno = -rc));
6732                         return rc;
6733                 }
6734                 optind++;
6735         }
6736
6737         return 0;
6738 }
6739
6740 static int lfs_hsm_action(int argc, char **argv)
6741 {
6742         int                              rc;
6743         int                              i = 1;
6744         char                            *path;
6745         struct hsm_current_action        hca;
6746         struct hsm_extent                he;
6747         enum hsm_user_action             hua;
6748         enum hsm_progress_states         hps;
6749
6750         if (argc < 2)
6751                 return CMD_HELP;
6752
6753         do {
6754                 path = argv[i];
6755
6756                 rc = llapi_hsm_current_action(path, &hca);
6757                 if (rc) {
6758                         fprintf(stderr, "can't get hsm action for %s: %s\n",
6759                                 path, strerror(errno = -rc));
6760                         return rc;
6761                 }
6762                 he = hca.hca_location;
6763                 hua = hca.hca_action;
6764                 hps = hca.hca_state;
6765
6766                 printf("%s: %s", path, hsm_user_action2name(hua));
6767
6768                 /* Skip file without action */
6769                 if (hca.hca_action == HUA_NONE) {
6770                         printf("\n");
6771                         continue;
6772                 }
6773
6774                 printf(" %s ", hsm_progress_state2name(hps));
6775
6776                 if ((hps == HPS_RUNNING) &&
6777                     (hua == HUA_ARCHIVE || hua == HUA_RESTORE))
6778                         printf("(%llu bytes moved)\n",
6779                                (unsigned long long)he.length);
6780                 else if ((he.offset + he.length) == LUSTRE_EOF)
6781                         printf("(from %llu to EOF)\n",
6782                                (unsigned long long)he.offset);
6783                 else
6784                         printf("(from %llu to %llu)\n",
6785                                (unsigned long long)he.offset,
6786                                (unsigned long long)(he.offset + he.length));
6787
6788         } while (++i < argc);
6789
6790         return 0;
6791 }
6792
6793 static int lfs_hsm_set(int argc, char **argv)
6794 {
6795         return lfs_hsm_change_flags(argc, argv, LFS_HSM_SET);
6796 }
6797
6798 static int lfs_hsm_clear(int argc, char **argv)
6799 {
6800         return lfs_hsm_change_flags(argc, argv, LFS_HSM_CLEAR);
6801 }
6802
6803 /**
6804  * Check file state and return its fid, to be used by lfs_hsm_request().
6805  *
6806  * \param[in]     file      Path to file to check
6807  * \param[in,out] fid       Pointer to allocated lu_fid struct.
6808  * \param[in,out] last_dev  Pointer to last device id used.
6809  *
6810  * \return 0 on success.
6811  */
6812 static int lfs_hsm_prepare_file(const char *file, struct lu_fid *fid,
6813                                 dev_t *last_dev)
6814 {
6815         struct stat     st;
6816         int             rc;
6817
6818         rc = lstat(file, &st);
6819         if (rc) {
6820                 fprintf(stderr, "Cannot stat %s: %s\n", file, strerror(errno));
6821                 return -errno;
6822         }
6823         /* Checking for regular file as archiving as posix copytool
6824          * rejects archiving files other than regular files
6825          */
6826         if (!S_ISREG(st.st_mode)) {
6827                 fprintf(stderr, "error: \"%s\" is not a regular file\n", file);
6828                 return CMD_HELP;
6829         }
6830         /* A request should be ... */
6831         if (*last_dev != st.st_dev && *last_dev != 0) {
6832                 fprintf(stderr, "All files should be "
6833                         "on the same filesystem: %s\n", file);
6834                 return -EINVAL;
6835         }
6836         *last_dev = st.st_dev;
6837
6838         rc = llapi_path2fid(file, fid);
6839         if (rc) {
6840                 fprintf(stderr, "Cannot read FID of %s: %s\n",
6841                         file, strerror(-rc));
6842                 return rc;
6843         }
6844         return 0;
6845 }
6846
6847 /* Fill an HSM HUR item with a given file name.
6848  *
6849  * If mntpath is set, then the filename is actually a FID, and no
6850  * lookup on the filesystem will be performed.
6851  *
6852  * \param[in]  hur         the user request to fill
6853  * \param[in]  idx         index of the item inside the HUR to fill
6854  * \param[in]  mntpath     mountpoint of Lustre
6855  * \param[in]  fname       filename (if mtnpath is NULL)
6856  *                         or FID (if mntpath is set)
6857  * \param[in]  last_dev    pointer to last device id used
6858  *
6859  * \retval 0 on success
6860  * \retval CMD_HELP or a negative errno on error
6861  */
6862 static int fill_hur_item(struct hsm_user_request *hur, unsigned int idx,
6863                          const char *mntpath, const char *fname,
6864                          dev_t *last_dev)
6865 {
6866         struct hsm_user_item *hui = &hur->hur_user_item[idx];
6867         int rc;
6868
6869         hui->hui_extent.length = -1;
6870
6871         if (mntpath != NULL) {
6872                 if (*fname == '[')
6873                         fname++;
6874                 rc = sscanf(fname, SFID, RFID(&hui->hui_fid));
6875                 if (rc == 3) {
6876                         rc = 0;
6877                 } else {
6878                         fprintf(stderr, "hsm: '%s' is not a valid FID\n",
6879                                 fname);
6880                         rc = -EINVAL;
6881                 }
6882         } else {
6883                 rc = lfs_hsm_prepare_file(fname, &hui->hui_fid, last_dev);
6884         }
6885
6886         if (rc == 0)
6887                 hur->hur_request.hr_itemcount++;
6888
6889         return rc;
6890 }
6891
6892 static int lfs_hsm_request(int argc, char **argv, int action)
6893 {
6894         struct option long_opts[] = {
6895         { .val = 'a',   .name = "archive",      .has_arg = required_argument },
6896         { .val = 'D',   .name = "data",         .has_arg = required_argument },
6897         { .val = 'l',   .name = "filelist",     .has_arg = required_argument },
6898         { .val = 'm',   .name = "mntpath",      .has_arg = required_argument },
6899         { .name = NULL } };
6900         dev_t                    last_dev = 0;
6901         char                     short_opts[] = "l:D:a:m:";
6902         struct hsm_user_request *hur, *oldhur;
6903         int                      c, i;
6904         size_t                   len;
6905         int                      nbfile;
6906         char                    *line = NULL;
6907         char                    *filelist = NULL;
6908         char                     fullpath[PATH_MAX];
6909         char                    *opaque = NULL;
6910         int                      opaque_len = 0;
6911         int                      archive_id = 0;
6912         FILE                    *fp;
6913         int                      nbfile_alloc = 0;
6914         char                    *some_file = NULL;
6915         char                    *mntpath = NULL;
6916         int                      rc;
6917
6918         if (argc < 2)
6919                 return CMD_HELP;
6920
6921         while ((c = getopt_long(argc, argv, short_opts,
6922                                 long_opts, NULL)) != -1) {
6923                 switch (c) {
6924                 case 'l':
6925                         filelist = optarg;
6926                         break;
6927                 case 'D':
6928                         opaque = optarg;
6929                         break;
6930                 case 'a':
6931                         if (action != HUA_ARCHIVE &&
6932                             action != HUA_REMOVE) {
6933                                 fprintf(stderr,
6934                                         "error: -a is supported only "
6935                                         "when archiving or removing\n");
6936                                 return CMD_HELP;
6937                         }
6938                         archive_id = atoi(optarg);
6939                         break;
6940                 case 'm':
6941                         if (some_file == NULL) {
6942                                 mntpath = optarg;
6943                                 some_file = strdup(optarg);
6944                         }
6945                         break;
6946                 case '?':
6947                         return CMD_HELP;
6948                 default:
6949                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
6950                                 argv[0], argv[optind - 1]);
6951                         return CMD_HELP;
6952                 }
6953         }
6954
6955         /* All remaining args are files, so we have at least nbfile */
6956         nbfile = argc - optind;
6957
6958         if ((nbfile == 0) && (filelist == NULL))
6959                 return CMD_HELP;
6960
6961         if (opaque != NULL)
6962                 opaque_len = strlen(opaque);
6963
6964         /* Alloc the request structure with enough place to store all files
6965          * from command line. */
6966         hur = llapi_hsm_user_request_alloc(nbfile, opaque_len);
6967         if (hur == NULL) {
6968                 fprintf(stderr, "Cannot create the request: %s\n",
6969                         strerror(errno));
6970                 return errno;
6971         }
6972         nbfile_alloc = nbfile;
6973
6974         hur->hur_request.hr_action = action;
6975         hur->hur_request.hr_archive_id = archive_id;
6976         hur->hur_request.hr_flags = 0;
6977
6978         /* All remaining args are files, add them */
6979         if (nbfile != 0 && some_file == NULL)
6980                 some_file = strdup(argv[optind]);
6981
6982         for (i = 0; i < nbfile; i++) {
6983                 rc = fill_hur_item(hur, i, mntpath, argv[optind + i],
6984                                    &last_dev);
6985                 if (rc)
6986                         goto out_free;
6987         }
6988
6989         /* from here stop using nb_file, use hur->hur_request.hr_itemcount */
6990
6991         /* If a filelist was specified, read the filelist from it. */
6992         if (filelist != NULL) {
6993                 fp = fopen(filelist, "r");
6994                 if (fp == NULL) {
6995                         fprintf(stderr, "Cannot read the file list %s: %s\n",
6996                                 filelist, strerror(errno));
6997                         rc = -errno;
6998                         goto out_free;
6999                 }
7000
7001                 while ((rc = getline(&line, &len, fp)) != -1) {
7002                         /* If allocated buffer was too small, get something
7003                          * larger */
7004                         if (nbfile_alloc <= hur->hur_request.hr_itemcount) {
7005                                 ssize_t size;
7006
7007                                 nbfile_alloc = nbfile_alloc * 2 + 1;
7008                                 oldhur = hur;
7009                                 hur = llapi_hsm_user_request_alloc(nbfile_alloc,
7010                                                                    opaque_len);
7011                                 if (hur == NULL) {
7012                                         fprintf(stderr, "hsm: cannot allocate "
7013                                                 "the request: %s\n",
7014                                                 strerror(errno));
7015                                         hur = oldhur;
7016                                         rc = -errno;
7017                                         fclose(fp);
7018                                         goto out_free;
7019                                 }
7020                                 size = hur_len(oldhur);
7021                                 if (size < 0) {
7022                                         fprintf(stderr, "hsm: cannot allocate "
7023                                                 "%u files + %u bytes data\n",
7024                                             oldhur->hur_request.hr_itemcount,
7025                                             oldhur->hur_request.hr_data_len);
7026                                         free(hur);
7027                                         hur = oldhur;
7028                                         rc = -E2BIG;
7029                                         fclose(fp);
7030                                         goto out_free;
7031                                 }
7032                                 memcpy(hur, oldhur, size);
7033                                 free(oldhur);
7034                         }
7035
7036                         /* Chop CR */
7037                         if (line[strlen(line) - 1] == '\n')
7038                                 line[strlen(line) - 1] = '\0';
7039
7040                         rc = fill_hur_item(hur, hur->hur_request.hr_itemcount,
7041                                            mntpath, line, &last_dev);
7042                         if (rc) {
7043                                 fclose(fp);
7044                                 goto out_free;
7045                         }
7046
7047                         if (some_file == NULL) {
7048                                 some_file = line;
7049                                 line = NULL;
7050                         }
7051                 }
7052
7053                 rc = fclose(fp);
7054                 free(line);
7055         }
7056
7057         /* If a --data was used, add it to the request */
7058         hur->hur_request.hr_data_len = opaque_len;
7059         if (opaque != NULL)
7060                 memcpy(hur_data(hur), opaque, opaque_len);
7061
7062         /* Send the HSM request */
7063         if (realpath(some_file, fullpath) == NULL) {
7064                 fprintf(stderr, "Could not find path '%s': %s\n",
7065                         some_file, strerror(errno));
7066         }
7067         rc = llapi_hsm_request(fullpath, hur);
7068         if (rc) {
7069                 fprintf(stderr, "Cannot send HSM request (use of %s): %s\n",
7070                         some_file, strerror(-rc));
7071                 goto out_free;
7072         }
7073
7074 out_free:
7075         free(some_file);
7076         free(hur);
7077         return rc;
7078 }
7079
7080 static int lfs_hsm_archive(int argc, char **argv)
7081 {
7082         return lfs_hsm_request(argc, argv, HUA_ARCHIVE);
7083 }
7084
7085 static int lfs_hsm_restore(int argc, char **argv)
7086 {
7087         return lfs_hsm_request(argc, argv, HUA_RESTORE);
7088 }
7089
7090 static int lfs_hsm_release(int argc, char **argv)
7091 {
7092         return lfs_hsm_request(argc, argv, HUA_RELEASE);
7093 }
7094
7095 static int lfs_hsm_remove(int argc, char **argv)
7096 {
7097         return lfs_hsm_request(argc, argv, HUA_REMOVE);
7098 }
7099
7100 static int lfs_hsm_cancel(int argc, char **argv)
7101 {
7102         return lfs_hsm_request(argc, argv, HUA_CANCEL);
7103 }
7104
7105 static int lfs_swap_layouts(int argc, char **argv)
7106 {
7107         if (argc != 3)
7108                 return CMD_HELP;
7109
7110         return llapi_swap_layouts(argv[1], argv[2], 0, 0,
7111                                   SWAP_LAYOUTS_KEEP_MTIME |
7112                                   SWAP_LAYOUTS_KEEP_ATIME);
7113 }
7114
7115 static const char *const ladvise_names[] = LU_LADVISE_NAMES;
7116
7117 static const char *const lock_mode_names[] = LOCK_MODE_NAMES;
7118
7119 int lfs_get_mode(const char *string)
7120 {
7121         enum lock_mode_user mode;
7122
7123         for (mode = 0; mode < ARRAY_SIZE(lock_mode_names); mode++) {
7124                 if (lock_mode_names[mode] == NULL)
7125                         continue;
7126                 if (strcmp(string, lock_mode_names[mode]) == 0)
7127                         return mode;
7128         }
7129
7130         return -EINVAL;
7131 }
7132
7133 static enum lu_ladvise_type lfs_get_ladvice(const char *string)
7134 {
7135         enum lu_ladvise_type advice;
7136
7137         for (advice = 0;
7138              advice < ARRAY_SIZE(ladvise_names); advice++) {
7139                 if (ladvise_names[advice] == NULL)
7140                         continue;
7141                 if (strcmp(string, ladvise_names[advice]) == 0)
7142                         return advice;
7143         }
7144
7145         return LU_LADVISE_INVALID;
7146 }
7147
7148 static int lfs_ladvise(int argc, char **argv)
7149 {
7150         struct option long_opts[] = {
7151         { .val = 'a',   .name = "advice",       .has_arg = required_argument },
7152         { .val = 'b',   .name = "background",   .has_arg = no_argument },
7153         { .val = 'e',   .name = "end",          .has_arg = required_argument },
7154         { .val = 'l',   .name = "length",       .has_arg = required_argument },
7155         { .val = 'm',   .name = "mode",         .has_arg = required_argument },
7156         { .val = 's',   .name = "start",        .has_arg = required_argument },
7157         { .val = 'u',   .name = "unset",        .has_arg = no_argument },
7158         { .name = NULL } };
7159         char                     short_opts[] = "a:be:l:m:s:u";
7160         int                      c;
7161         int                      rc = 0;
7162         const char              *path;
7163         int                      fd;
7164         struct llapi_lu_ladvise  advice;
7165         enum lu_ladvise_type     advice_type = LU_LADVISE_INVALID;
7166         unsigned long long       start = 0;
7167         unsigned long long       end = LUSTRE_EOF;
7168         unsigned long long       length = 0;
7169         unsigned long long       size_units;
7170         unsigned long long       flags = 0;
7171         int                      mode = 0;
7172
7173         optind = 0;
7174         while ((c = getopt_long(argc, argv, short_opts,
7175                                 long_opts, NULL)) != -1) {
7176                 switch (c) {
7177                 case 'a':
7178                         advice_type = lfs_get_ladvice(optarg);
7179                         if (advice_type == LU_LADVISE_INVALID) {
7180                                 fprintf(stderr, "%s: invalid advice type "
7181                                         "'%s'\n", argv[0], optarg);
7182                                 fprintf(stderr, "Valid types:");
7183
7184                                 for (advice_type = 0;
7185                                      advice_type < ARRAY_SIZE(ladvise_names);
7186                                      advice_type++) {
7187                                         if (ladvise_names[advice_type] == NULL)
7188                                                 continue;
7189                                         fprintf(stderr, " %s",
7190                                                 ladvise_names[advice_type]);
7191                                 }
7192                                 fprintf(stderr, "\n");
7193
7194                                 return CMD_HELP;
7195                         }
7196                         break;
7197                 case 'b':
7198                         flags |= LF_ASYNC;
7199                         break;
7200                 case 'u':
7201                         flags |= LF_UNSET;
7202                         break;
7203                 case 'e':
7204                         size_units = 1;
7205                         rc = llapi_parse_size(optarg, &end,
7206                                               &size_units, 0);
7207                         if (rc) {
7208                                 fprintf(stderr, "%s: bad end offset '%s'\n",
7209                                         argv[0], optarg);
7210                                 return CMD_HELP;
7211                         }
7212                         break;
7213                 case 's':
7214                         size_units = 1;
7215                         rc = llapi_parse_size(optarg, &start,
7216                                               &size_units, 0);
7217                         if (rc) {
7218                                 fprintf(stderr, "%s: bad start offset "
7219                                         "'%s'\n", argv[0], optarg);
7220                                 return CMD_HELP;
7221                         }
7222                         break;
7223                 case 'l':
7224                         size_units = 1;
7225                         rc = llapi_parse_size(optarg, &length,
7226                                               &size_units, 0);
7227                         if (rc) {
7228                                 fprintf(stderr, "%s: bad length '%s'\n",
7229                                         argv[0], optarg);
7230                                 return CMD_HELP;
7231                         }
7232                         break;
7233                 case 'm':
7234                         mode = lfs_get_mode(optarg);
7235                         if (mode < 0) {
7236                                 fprintf(stderr, "%s: bad mode '%s', valid "
7237                                                  "modes are READ or WRITE\n",
7238                                         argv[0], optarg);
7239                                 return CMD_HELP;
7240                         }
7241                         break;
7242                 case '?':
7243                         return CMD_HELP;
7244                 default:
7245                         fprintf(stderr, "%s: option '%s' unrecognized\n",
7246                                 argv[0], argv[optind - 1]);
7247                         return CMD_HELP;
7248                 }
7249         }
7250
7251         if (advice_type == LU_LADVISE_INVALID) {
7252                 fprintf(stderr, "%s: please give an advice type\n", argv[0]);
7253                 fprintf(stderr, "Valid types:");
7254                 for (advice_type = 0; advice_type < ARRAY_SIZE(ladvise_names);
7255                      advice_type++) {
7256                         if (ladvise_names[advice_type] == NULL)
7257                                 continue;
7258                         fprintf(stderr, " %s", ladvise_names[advice_type]);
7259                 }
7260                 fprintf(stderr, "\n");
7261                 return CMD_HELP;
7262         }
7263
7264         if (advice_type == LU_LADVISE_LOCKNOEXPAND) {
7265                 fprintf(stderr, "%s: Lock no expand advice is a per file "
7266                                  "descriptor advice, so when called from lfs, "
7267                                  "it does nothing.\n", argv[0]);
7268                 return CMD_HELP;
7269         }
7270
7271         if (argc <= optind) {
7272                 fprintf(stderr, "%s: please give one or more file names\n",
7273                         argv[0]);
7274                 return CMD_HELP;
7275         }
7276
7277         if (end != LUSTRE_EOF && length != 0 && end != start + length) {
7278                 fprintf(stderr, "%s: conflicting arguments of -l and -e\n",
7279                         argv[0]);
7280                 return CMD_HELP;
7281         }
7282
7283         if (end == LUSTRE_EOF && length != 0)
7284                 end = start + length;
7285
7286         if (end <= start) {
7287                 fprintf(stderr, "%s: range [%llu, %llu] is invalid\n",
7288                         argv[0], start, end);
7289                 return CMD_HELP;
7290         }
7291
7292         if (advice_type != LU_LADVISE_LOCKAHEAD && mode != 0) {
7293                 fprintf(stderr, "%s: mode is only valid with lockahead\n",
7294                         argv[0]);
7295                 return CMD_HELP;
7296         }
7297
7298         if (advice_type == LU_LADVISE_LOCKAHEAD && mode == 0) {
7299                 fprintf(stderr, "%s: mode is required with lockahead\n",
7300                         argv[0]);
7301                 return CMD_HELP;
7302         }
7303
7304         while (optind < argc) {
7305                 int rc2;
7306
7307                 path = argv[optind++];
7308
7309                 fd = open(path, O_RDONLY);
7310                 if (fd < 0) {
7311                         fprintf(stderr, "%s: cannot open file '%s': %s\n",
7312                                 argv[0], path, strerror(errno));
7313                         rc2 = -errno;
7314                         goto next;
7315                 }
7316
7317                 advice.lla_start = start;
7318                 advice.lla_end = end;
7319                 advice.lla_advice = advice_type;
7320                 advice.lla_value1 = 0;
7321                 advice.lla_value2 = 0;
7322                 advice.lla_value3 = 0;
7323                 advice.lla_value4 = 0;
7324                 if (advice_type == LU_LADVISE_LOCKAHEAD) {
7325                         advice.lla_lockahead_mode = mode;
7326                         advice.lla_peradvice_flags = flags;
7327                 }
7328
7329                 rc2 = llapi_ladvise(fd, flags, 1, &advice);
7330                 close(fd);
7331                 if (rc2 < 0) {
7332                         fprintf(stderr, "%s: cannot give advice '%s' to file "
7333                                 "'%s': %s\n", argv[0],
7334                                 ladvise_names[advice_type],
7335                                 path, strerror(errno));
7336
7337                         goto next;
7338                 }
7339
7340 next:
7341                 if (rc == 0 && rc2 < 0)
7342                         rc = rc2;
7343         }
7344         return rc;
7345 }
7346
7347 /** The input string contains a comma delimited list of component ids and
7348  * ranges, for example "1,2-4,7".
7349  */
7350 static int parse_mirror_ids(__u16 *ids, int size, char *arg)
7351 {
7352         bool end_of_loop = false;
7353         char *ptr = NULL;
7354         int nr = 0;
7355         int rc;
7356
7357         if (arg == NULL)
7358                 return -EINVAL;
7359
7360         while (!end_of_loop) {
7361                 int start_index;
7362                 int end_index;
7363                 int i;
7364                 char *endptr = NULL;
7365
7366                 rc = -EINVAL;
7367                 ptr = strchrnul(arg, ',');
7368                 end_of_loop = *ptr == '\0';
7369                 *ptr = '\0';
7370
7371                 start_index = strtol(arg, &endptr, 0);
7372                 if (endptr == arg) /* no data at all */
7373                         break;
7374                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
7375                         break;
7376                 if (start_index < 0)
7377                         break;
7378
7379                 end_index = start_index;
7380                 if (*endptr == '-') {
7381                         end_index = strtol(endptr + 1, &endptr, 0);
7382                         if (*endptr != '\0')
7383                                 break;
7384                         if (end_index < start_index)
7385                                 break;
7386                 }
7387
7388                 for (i = start_index; i <= end_index && size > 0; i++) {
7389                         int j;
7390
7391                         /* remove duplicate */
7392                         for (j = 0; j < nr; j++) {
7393                                 if (ids[j] == i)
7394                                         break;
7395                         }
7396                         if (j == nr) { /* no duplicate */
7397                                 ids[nr++] = i;
7398                                 --size;
7399                         }
7400                 }
7401
7402                 if (size == 0 && i < end_index)
7403                         break;
7404
7405                 *ptr = ',';
7406                 arg = ++ptr;
7407                 rc = 0;
7408         }
7409         if (!end_of_loop && ptr != NULL)
7410                 *ptr = ',';
7411
7412         return rc < 0 ? rc : nr;
7413 }
7414
7415 /**
7416  * struct verify_mirror_id - Mirror id to be verified.
7417  * @mirror_id:   A specified mirror id.
7418  * @is_valid_id: @mirror_id is valid or not in the mirrored file.
7419  */
7420 struct verify_mirror_id {
7421         __u16 mirror_id;
7422         bool is_valid_id;
7423 };
7424
7425 /**
7426  * compare_mirror_ids() - Compare mirror ids.
7427  * @layout: Mirror component list.
7428  * @cbdata: Callback data in verify_mirror_id structure.
7429  *
7430  * This is a callback function called by llapi_layout_comp_iterate()
7431  * to compare the specified mirror id with the one in the current
7432  * component of @layout. If they are the same, then the specified
7433  * mirror id is valid.
7434  *
7435  * Return: a negative error code on failure or
7436  *         LLAPI_LAYOUT_ITER_CONT: Proceed iteration
7437  *         LLAPI_LAYOUT_ITER_STOP: Stop iteration
7438  */
7439 static inline
7440 int compare_mirror_ids(struct llapi_layout *layout, void *cbdata)
7441 {
7442         struct verify_mirror_id *mirror_id_cbdata =
7443                                  (struct verify_mirror_id *)cbdata;
7444         uint32_t mirror_id;
7445         int rc = 0;
7446
7447         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
7448         if (rc < 0) {
7449                 rc = -errno;
7450                 fprintf(stderr,
7451                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
7452                         progname, strerror(errno));
7453                 return rc;
7454         }
7455
7456         if (mirror_id_cbdata->mirror_id == mirror_id) {
7457                 mirror_id_cbdata->is_valid_id = true;
7458                 return LLAPI_LAYOUT_ITER_STOP;
7459         }
7460
7461         return LLAPI_LAYOUT_ITER_CONT;
7462 }
7463
7464 /**
7465  * verify_mirror_ids() - Verify specified mirror ids.
7466  * @fname:      Mirrored file name.
7467  * @mirror_ids: Specified mirror ids to be verified.
7468  * @ids_nr:     Number of specified mirror ids.
7469  *
7470  * This function verifies that specified @mirror_ids are valid
7471  * in the mirrored file @fname.
7472  *
7473  * Return: 0 on success or a negative error code on failure.
7474  */
7475 static inline
7476 int verify_mirror_ids(const char *fname, __u16 *mirror_ids, int ids_nr)
7477 {
7478         struct llapi_layout *layout = NULL;
7479         struct verify_mirror_id mirror_id_cbdata = { 0 };
7480         struct stat stbuf;
7481         uint32_t flr_state;
7482         int i;
7483         int fd;
7484         int rc = 0;
7485         int rc2 = 0;
7486
7487         if (ids_nr <= 0)
7488                 return -EINVAL;
7489
7490         if (stat(fname, &stbuf) < 0) {
7491                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
7492                         progname, fname, strerror(errno));
7493                 rc = -errno;
7494                 goto error;
7495         }
7496
7497         if (!S_ISREG(stbuf.st_mode)) {
7498                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
7499                         progname, fname);
7500                 rc = -EINVAL;
7501                 goto error;
7502         }
7503
7504         fd = open(fname, O_DIRECT | O_RDONLY);
7505         if (fd < 0) {
7506                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
7507                         progname, fname, strerror(errno));
7508                 rc = -errno;
7509                 goto error;
7510         }
7511
7512         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
7513         if (rc < 0) {
7514                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
7515                         progname, fname, strerror(errno));
7516                 goto close_fd;
7517         }
7518
7519         layout = llapi_layout_get_by_fd(fd, 0);
7520         if (layout == NULL) {
7521                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
7522                         progname, fname, strerror(errno));
7523                 rc = -errno;
7524                 llapi_lease_release(fd);
7525                 goto close_fd;
7526         }
7527
7528         rc = llapi_layout_flags_get(layout, &flr_state);
7529         if (rc < 0) {
7530                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
7531                         progname, fname, strerror(errno));
7532                 rc = -errno;
7533                 goto free_layout;
7534         }
7535
7536         flr_state &= LCM_FL_FLR_MASK;
7537         switch (flr_state) {
7538         case LCM_FL_NONE:
7539                 rc = -EINVAL;
7540                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
7541                         progname, fname, llapi_layout_flags_string(flr_state));
7542                 goto free_layout;
7543         default:
7544                 break;
7545         }
7546
7547         rc2 = 0;
7548         for (i = 0; i < ids_nr; i++) {
7549                 mirror_id_cbdata.mirror_id = mirror_ids[i];
7550                 mirror_id_cbdata.is_valid_id = false;
7551
7552                 rc = llapi_layout_comp_iterate(layout, compare_mirror_ids,
7553                                                &mirror_id_cbdata);
7554                 if (rc < 0) {
7555                         rc = -errno;
7556                         fprintf(stderr,
7557                                 "%s: '%s' failed to verify mirror id: %u.\n",
7558                                 progname, fname, mirror_ids[i]);
7559                         goto free_layout;
7560                 }
7561
7562                 if (!mirror_id_cbdata.is_valid_id) {
7563                         rc2 = -EINVAL;
7564                         fprintf(stderr,
7565                                 "%s: '%s' invalid specified mirror id: %u.\n",
7566                                 progname, fname, mirror_ids[i]);
7567                 }
7568         }
7569         rc = rc2;
7570
7571 free_layout:
7572         llapi_layout_free(layout);
7573         llapi_lease_release(fd);
7574 close_fd:
7575         close(fd);
7576 error:
7577         return rc;
7578 }
7579
7580 static inline
7581 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
7582                            __u16 *mirror_ids, int ids_nr)
7583 {
7584         struct llapi_resync_comp comp_array[1024] = { { 0 } };
7585         struct llapi_layout *layout;
7586         struct stat stbuf;
7587         uint32_t flr_state;
7588         int comp_size = 0;
7589         int idx;
7590         int fd;
7591         int rc;
7592
7593         if (stat(fname, &stbuf) < 0) {
7594                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
7595                         progname, fname, strerror(errno));
7596                 rc = -errno;
7597                 goto error;
7598         }
7599         if (!S_ISREG(stbuf.st_mode)) {
7600                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
7601                         progname, fname);
7602                 rc = -EINVAL;
7603                 goto error;
7604         }
7605
7606         fd = open(fname, O_DIRECT | O_RDWR);
7607         if (fd < 0) {
7608                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
7609                         progname, fname, strerror(errno));
7610                 rc = -errno;
7611                 goto error;
7612         }
7613
7614         layout = llapi_layout_get_by_fd(fd, 0);
7615         if (layout == NULL) {
7616                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
7617                         progname, fname, strerror(errno));
7618                 rc = -errno;
7619                 goto close_fd;
7620         }
7621
7622         rc = llapi_layout_flags_get(layout, &flr_state);
7623         if (rc) {
7624                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
7625                         progname, fname, strerror(errno));
7626                 rc = -errno;
7627                 goto free_layout;
7628         }
7629
7630         flr_state &= LCM_FL_FLR_MASK;
7631         if (flr_state == LCM_FL_NONE) {
7632                 rc = -EINVAL;
7633                 fprintf(stderr, "%s: '%s' is not a FLR file.\n",
7634                         progname, fname);
7635                 goto free_layout;
7636         }
7637
7638         /* get stale component info */
7639         comp_size = llapi_mirror_find_stale(layout, comp_array,
7640                                             ARRAY_SIZE(comp_array),
7641                                             mirror_ids, ids_nr);
7642         if (comp_size <= 0) {
7643                 rc = comp_size;
7644                 goto free_layout;
7645         }
7646
7647         ioc->lil_mode = LL_LEASE_WRLCK;
7648         ioc->lil_flags = LL_LEASE_RESYNC;
7649         rc = llapi_lease_set(fd, ioc);
7650         if (rc < 0) {
7651                 if (rc == -EALREADY)
7652                         rc = 0;
7653                 else
7654                         fprintf(stderr,
7655                             "%s: '%s' llapi_lease_get_ext resync failed: %s.\n",
7656                                 progname, fname, strerror(errno));
7657                 goto free_layout;
7658         }
7659
7660         idx = 0;
7661         while (idx < comp_size) {
7662                 ssize_t result;
7663                 uint64_t end;
7664                 __u16 mirror_id;
7665                 int i;
7666
7667                 rc = llapi_lease_check(fd);
7668                 if (rc != LL_LEASE_WRLCK) {
7669                         fprintf(stderr, "%s: '%s' lost lease lock.\n",
7670                                 progname, fname);
7671                         goto free_layout;
7672                 }
7673
7674                 mirror_id = comp_array[idx].lrc_mirror_id;
7675                 end = comp_array[idx].lrc_end;
7676
7677                 /* try to combine adjacent component */
7678                 for (i = idx + 1; i < comp_size; i++) {
7679                         if (mirror_id != comp_array[i].lrc_mirror_id ||
7680                             end != comp_array[i].lrc_start)
7681                                 break;
7682                         end = comp_array[i].lrc_end;
7683                 }
7684
7685                 result = llapi_mirror_resync_one(fd, layout, mirror_id,
7686                                                  comp_array[idx].lrc_start,
7687                                                  end);
7688                 if (result < 0) {
7689                         fprintf(stderr, "%s: '%s' llapi_mirror_resync_one: "
7690                                 "%ld.\n", progname, fname, result);
7691                         rc = result;
7692                         goto unlock;
7693                 } else if (result > 0) {
7694                         int j;
7695
7696                         /* mark synced components */
7697                         for (j = idx; j < i; j++)
7698                                 comp_array[j].lrc_synced = true;
7699                 }
7700
7701                 idx = i;
7702         }
7703
7704 unlock:
7705         /* prepare ioc for lease put */
7706         ioc->lil_mode = LL_LEASE_UNLCK;
7707         ioc->lil_flags = LL_LEASE_RESYNC_DONE;
7708         ioc->lil_count = 0;
7709         for (idx = 0; idx < comp_size; idx++) {
7710                 if (comp_array[idx].lrc_synced) {
7711                         ioc->lil_ids[ioc->lil_count] = comp_array[idx].lrc_id;
7712                         ioc->lil_count++;
7713                 }
7714         }
7715
7716         rc = llapi_lease_set(fd, ioc);
7717         if (rc <= 0) {
7718                 if (rc == 0) /* lost lease lock */
7719                         rc = -EBUSY;
7720                 fprintf(stderr, "%s: resync file '%s' failed: %s.\n",
7721                         progname, fname, strerror(errno));
7722                 goto free_layout;
7723         }
7724         /**
7725          * llapi_lease_set returns lease mode when it request to unlock
7726          * the lease lock
7727          */
7728         rc = 0;
7729
7730 free_layout:
7731         llapi_layout_free(layout);
7732 close_fd:
7733         close(fd);
7734 error:
7735         return rc;
7736 }
7737
7738 static inline int lfs_mirror_resync(int argc, char **argv)
7739 {
7740         struct ll_ioc_lease *ioc = NULL;
7741         __u16 mirror_ids[128] = { 0 };
7742         int ids_nr = 0;
7743         int c;
7744         int rc = 0;
7745
7746         struct option long_opts[] = {
7747         { .val = 'o',   .name = "only",         .has_arg = required_argument },
7748         { .name = NULL } };
7749
7750         while ((c = getopt_long(argc, argv, "o:", long_opts, NULL)) >= 0) {
7751                 switch (c) {
7752                 case 'o':
7753                         rc = parse_mirror_ids(mirror_ids,
7754                                         sizeof(mirror_ids) / sizeof(__u16),
7755                                         optarg);
7756                         if (rc < 0) {
7757                                 fprintf(stderr,
7758                                         "%s: bad mirror ids '%s'.\n",
7759                                         argv[0], optarg);
7760                                 goto error;
7761                         }
7762                         ids_nr = rc;
7763                         break;
7764                 default:
7765                         fprintf(stderr, "%s: options '%s' unrecognized.\n",
7766                                 argv[0], argv[optind - 1]);
7767                         rc = -EINVAL;
7768                         goto error;
7769                 }
7770         }
7771
7772         if (argc == optind) {
7773                 fprintf(stderr, "%s: no file name given.\n", argv[0]);
7774                 rc = CMD_HELP;
7775                 goto error;
7776         }
7777
7778         if (ids_nr > 0 && argc > optind + 1) {
7779                 fprintf(stderr,
7780                     "%s: option '--only' cannot be used upon multiple files.\n",
7781                         argv[0]);
7782                 rc = CMD_HELP;
7783                 goto error;
7784
7785         }
7786
7787         if (ids_nr > 0) {
7788                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
7789                 if (rc < 0)
7790                         goto error;
7791         }
7792
7793         /* set the lease on the file */
7794         ioc = calloc(sizeof(*ioc) + sizeof(__u32) * 4096, 1);
7795         if (ioc == NULL) {
7796                 fprintf(stderr, "%s: cannot alloc id array for ioc: %s.\n",
7797                         argv[0], strerror(errno));
7798                 rc = -errno;
7799                 goto error;
7800         }
7801
7802         for (; optind < argc; optind++) {
7803                 rc = lfs_mirror_resync_file(argv[optind], ioc,
7804                                             mirror_ids, ids_nr);
7805                 /* ignore previous file's error, continue with next file */
7806
7807                 /* reset ioc */
7808                 memset(ioc, 0, sizeof(__u32) * 4096);
7809         }
7810
7811         free(ioc);
7812 error:
7813         return rc;
7814 }
7815
7816 /**
7817  * struct verify_chunk - Mirror chunk to be verified.
7818  * @chunk:        [start, end) of the chunk.
7819  * @mirror_count: Number of mirror ids in @mirror_id array.
7820  * @mirror_id:    Array of valid mirror ids that cover the chunk.
7821  */
7822 struct verify_chunk {
7823         struct lu_extent chunk;
7824         unsigned int mirror_count;
7825         __u16 mirror_id[LUSTRE_MIRROR_COUNT_MAX];
7826 };
7827
7828 /**
7829  * print_chunks() - Print chunk information.
7830  * @fname:       Mirrored file name.
7831  * @chunks:      Array of chunks.
7832  * @chunk_count: Number of chunks in @chunks array.
7833  *
7834  * This function prints [start, end) of each chunk in @chunks
7835  * for mirrored file @fname, and also prints the valid mirror ids
7836  * that cover the chunk.
7837  *
7838  * Return: void.
7839  */
7840 static inline
7841 void print_chunks(const char *fname, struct verify_chunk *chunks,
7842                   int chunk_count)
7843 {
7844         int i;
7845         int j;
7846
7847         fprintf(stdout, "Chunks to be verified in %s:\n", fname);
7848         for (i = 0; i < chunk_count; i++) {
7849                 fprintf(stdout, DEXT, PEXT(&chunks[i].chunk));
7850
7851                 if (chunks[i].mirror_count == 0)
7852                         fprintf(stdout, "\t[");
7853                 else {
7854                         fprintf(stdout, "\t[%u", chunks[i].mirror_id[0]);
7855                         for (j = 1; j < chunks[i].mirror_count; j++)
7856                                 fprintf(stdout, ", %u", chunks[i].mirror_id[j]);
7857                 }
7858                 fprintf(stdout, "]\t%u\n", chunks[i].mirror_count);
7859         }
7860         fprintf(stdout, "\n");
7861 }
7862
7863 /**
7864  * print_checksums() - Print CRC-32 checksum values.
7865  * @chunk: A chunk and its corresponding valid mirror ids.
7866  * @crc:   CRC-32 checksum values on the chunk for each valid mirror.
7867  *
7868  * This function prints CRC-32 checksum values on @chunk for
7869  * each valid mirror that covers it.
7870  *
7871  * Return: void.
7872  */
7873 static inline
7874 void print_checksums(struct verify_chunk *chunk, unsigned long *crc)
7875 {
7876         int i;
7877
7878         fprintf(stdout,
7879                 "CRC-32 checksum value for chunk "DEXT":\n",
7880                 PEXT(&chunk->chunk));
7881         for (i = 0; i < chunk->mirror_count; i++)
7882                 fprintf(stdout, "Mirror %u:\t%#lx\n",
7883                         chunk->mirror_id[i], crc[i]);
7884         fprintf(stdout, "\n");
7885 }
7886
7887 /**
7888  * filter_mirror_id() - Filter specified mirror ids.
7889  * @chunks:      Array of chunks.
7890  * @chunk_count: Number of chunks in @chunks array.
7891  * @mirror_ids:  Specified mirror ids to be verified.
7892  * @ids_nr:      Number of specified mirror ids.
7893  *
7894  * This function scans valid mirror ids that cover each chunk in @chunks
7895  * and filters specified mirror ids.
7896  *
7897  * Return: void.
7898  */
7899 static inline
7900 void filter_mirror_id(struct verify_chunk *chunks, int chunk_count,
7901                       __u16 *mirror_ids, int ids_nr)
7902 {
7903         int i;
7904         int j;
7905         int k;
7906         __u16 valid_id[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
7907         unsigned int valid_count = 0;
7908
7909         for (i = 0; i < chunk_count; i++) {
7910                 if (chunks[i].mirror_count == 0)
7911                         continue;
7912
7913                 valid_count = 0;
7914                 for (j = 0; j < ids_nr; j++) {
7915                         for (k = 0; k < chunks[i].mirror_count; k++) {
7916                                 if (chunks[i].mirror_id[k] == mirror_ids[j]) {
7917                                         valid_id[valid_count] = mirror_ids[j];
7918                                         valid_count++;
7919                                         break;
7920                                 }
7921                         }
7922                 }
7923
7924                 memcpy(chunks[i].mirror_id, valid_id,
7925                        sizeof(__u16) * valid_count);
7926                 chunks[i].mirror_count = valid_count;
7927         }
7928 }
7929
7930 /**
7931  * lfs_mirror_prepare_chunk() - Find mirror chunks to be verified.
7932  * @layout:      Mirror component list.
7933  * @chunks:      Array of chunks.
7934  * @chunks_size: Array size of @chunks.
7935  *
7936  * This function scans the components in @layout from offset 0 to LUSTRE_EOF
7937  * to find out chunk segments and store them in @chunks array.
7938  *
7939  * The @mirror_id array in each element of @chunks will store the valid
7940  * mirror ids that cover the chunk. If a mirror component covering the
7941  * chunk has LCME_FL_STALE or LCME_FL_OFFLINE flag, then the mirror id
7942  * will not be stored into the @mirror_id array, and the chunk for that
7943  * mirror will not be verified.
7944  *
7945  * The @mirror_count in each element of @chunks will store the number of
7946  * mirror ids in @mirror_id array. If @mirror_count is 0, it indicates the
7947  * chunk is invalid in all of the mirrors. And if @mirror_count is 1, it
7948  * indicates the chunk is valid in only one mirror. In both cases, the
7949  * chunk will not be verified.
7950  *
7951  * Here is an example:
7952  *
7953  *  0      1M     2M     3M     4M           EOF
7954  *  +------+-------------+--------------------+
7955  *  |      |             |      S             |       mirror1
7956  *  +------+------+------+------+-------------+
7957  *  |             |   S  |   S  |             |       mirror2
7958  *  +-------------+------+------+-------------+
7959  *
7960  * prepared @chunks array will contain 5 elements:
7961  * (([0, 1M), [1, 2], 2),
7962  *  ([1M, 2M), [1, 2], 2),
7963  *  ([2M, 3M), [1], 1),
7964  *  ([3M, 4M], [], 0),
7965  *  ([4M, EOF), [2], 1))
7966  *
7967  * Return: the actual array size of @chunks on success
7968  *         or a negative error code on failure.
7969  */
7970 static inline
7971 int lfs_mirror_prepare_chunk(struct llapi_layout *layout,
7972                              struct verify_chunk *chunks,
7973                              size_t chunks_size)
7974 {
7975         uint64_t start;
7976         uint64_t end;
7977         uint32_t mirror_id;
7978         uint32_t flags;
7979         int idx = 0;
7980         int i = 0;
7981         int rc = 0;
7982
7983         memset(chunks, 0, sizeof(*chunks) * chunks_size);
7984
7985         while (1) {
7986                 rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
7987                 if (rc < 0) {
7988                         fprintf(stderr,
7989                                 "%s: move to the first layout component: %s.\n",
7990                                 progname, strerror(errno));
7991                         goto error;
7992                 }
7993
7994                 i = 0;
7995                 rc = 0;
7996                 chunks[idx].chunk.e_end = LUSTRE_EOF;
7997                 while (rc == 0) {
7998                         rc = llapi_layout_comp_extent_get(layout, &start, &end);
7999                         if (rc < 0) {
8000                                 fprintf(stderr,
8001                                         "%s: llapi_layout_comp_extent_get failed: %s.\n",
8002                                         progname, strerror(errno));
8003                                 goto error;
8004                         }
8005
8006                         if (start > chunks[idx].chunk.e_start ||
8007                             end <= chunks[idx].chunk.e_start)
8008                                 goto next;
8009
8010                         if (end < chunks[idx].chunk.e_end)
8011                                 chunks[idx].chunk.e_end = end;
8012
8013                         rc = llapi_layout_comp_flags_get(layout, &flags);
8014                         if (rc < 0) {
8015                                 fprintf(stderr,
8016                                         "%s: llapi_layout_comp_flags_get failed: %s.\n",
8017                                         progname, strerror(errno));
8018                                 goto error;
8019                         }
8020
8021                         if (flags & LCME_FL_STALE || flags & LCME_FL_OFFLINE)
8022                                 goto next;
8023
8024                         rc = llapi_layout_mirror_id_get(layout, &mirror_id);
8025                         if (rc < 0) {
8026                                 fprintf(stderr,
8027                                         "%s: llapi_layout_mirror_id_get failed: %s.\n",
8028                                         progname, strerror(errno));
8029                                 goto error;
8030                         }
8031
8032                         chunks[idx].mirror_id[i] = mirror_id;
8033                         i++;
8034                         if (i >= ARRAY_SIZE(chunks[idx].mirror_id)) {
8035                                 fprintf(stderr,
8036                                         "%s: mirror_id array is too small.\n",
8037                                         progname);
8038                                 rc = -EINVAL;
8039                                 goto error;
8040                         }
8041
8042                 next:
8043                         rc = llapi_layout_comp_use(layout,
8044                                                    LLAPI_LAYOUT_COMP_USE_NEXT);
8045                         if (rc < 0) {
8046                                 fprintf(stderr,
8047                                         "%s: move to the next layout component: %s.\n",
8048                                         progname, strerror(errno));
8049                                 goto error;
8050                         }
8051                 } /* loop through all components */
8052
8053                 chunks[idx].mirror_count = i;
8054
8055                 if (chunks[idx].chunk.e_end == LUSTRE_EOF)
8056                         break;
8057
8058                 idx++;
8059                 if (idx >= chunks_size) {
8060                         fprintf(stderr, "%s: chunks array is too small.\n",
8061                                 progname);
8062                         rc = -EINVAL;
8063                         goto error;
8064                 }
8065
8066                 chunks[idx].chunk.e_start = chunks[idx - 1].chunk.e_end;
8067         }
8068
8069 error:
8070         return rc < 0 ? rc : idx + 1;
8071 }
8072
8073 /**
8074  * lfs_mirror_verify_chunk() - Verify a chunk.
8075  * @fd:        File descriptor of the mirrored file.
8076  * @file_size: Size of the mirrored file.
8077  * @chunk:     A chunk and its corresponding valid mirror ids.
8078  * @verbose:   Verbose mode.
8079  *
8080  * This function verifies a @chunk contains exactly the same data
8081  * ammong the mirrors that cover it.
8082  *
8083  * If @verbose is specified, then the function will print where the
8084  * differences are if the data do not match. Otherwise, it will
8085  * just return an error in that case.
8086  *
8087  * Return: 0 on success or a negative error code on failure.
8088  */
8089 static inline
8090 int lfs_mirror_verify_chunk(int fd, size_t file_size,
8091                             struct verify_chunk *chunk, int verbose)
8092 {
8093         const size_t buflen = 4 * 1024 * 1024; /* 4M */
8094         void *buf;
8095         size_t page_size = sysconf(_SC_PAGESIZE);
8096         ssize_t bytes_read;
8097         ssize_t bytes_done;
8098         size_t count;
8099         off_t pos;
8100         unsigned long crc;
8101         unsigned long crc_array[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
8102         int i;
8103         int rc = 0;
8104
8105         if (file_size == 0)
8106                 return 0;
8107
8108         rc = posix_memalign(&buf, page_size, buflen);
8109         if (rc) /* error code is returned directly */
8110                 return -rc;
8111
8112         if (verbose > 1) {
8113                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
8114                         PEXT(&chunk->chunk));
8115                 for (i = 0; i < chunk->mirror_count; i++)
8116                         fprintf(stdout, " %u", chunk->mirror_id[i]);
8117                 fprintf(stdout, "\n");
8118         }
8119
8120         bytes_done = 0;
8121         count = MIN(chunk->chunk.e_end, file_size) - chunk->chunk.e_start;
8122         pos = chunk->chunk.e_start;
8123         while (bytes_done < count) {
8124                 /* compute initial CRC-32 checksum */
8125                 crc = crc32(0L, Z_NULL, 0);
8126                 memset(crc_array, 0, sizeof(crc_array));
8127
8128                 bytes_read = 0;
8129                 for (i = 0; i < chunk->mirror_count; i++) {
8130                         bytes_read = llapi_mirror_read(fd, chunk->mirror_id[i],
8131                                                        buf, buflen, pos);
8132                         if (bytes_read < 0) {
8133                                 rc = bytes_read;
8134                                 fprintf(stderr,
8135                                         "%s: failed to read data from mirror %u: %s.\n",
8136                                         progname, chunk->mirror_id[i],
8137                                         strerror(-rc));
8138                                 goto error;
8139                         }
8140
8141                         /* compute new CRC-32 checksum */
8142                         crc_array[i] = crc32(crc, buf, bytes_read);
8143                 }
8144
8145                 if (verbose)
8146                         print_checksums(chunk, crc_array);
8147
8148                 /* compare CRC-32 checksum values */
8149                 for (i = 1; i < chunk->mirror_count; i++) {
8150                         if (crc_array[i] != crc_array[0]) {
8151                                 rc = -EINVAL;
8152                                 if (!verbose)
8153                                         goto error;
8154
8155                                 fprintf(stderr,
8156                                         "%s: chunk "DEXT" has different checksum value on mirror %u and mirror %u.\n",
8157                                         progname, PEXT(&chunk->chunk),
8158                                         chunk->mirror_id[0],
8159                                         chunk->mirror_id[i]);
8160                         }
8161                 }
8162
8163                 pos += bytes_read;
8164                 bytes_done += bytes_read;
8165         }
8166
8167         if (verbose > 1 && rc == 0) {
8168                 fprintf(stdout, "Verifying chunk "DEXT" on mirror:",
8169                         PEXT(&chunk->chunk));
8170                 for (i = 0; i < chunk->mirror_count; i++)
8171                         fprintf(stdout, " %u", chunk->mirror_id[i]);
8172                 fprintf(stdout, " PASS\n\n");
8173         }
8174
8175 error:
8176         free(buf);
8177         return rc;
8178 }
8179
8180 /**
8181  * lfs_mirror_verify_file() - Verify a mirrored file.
8182  * @fname:      Mirrored file name.
8183  * @mirror_ids: Specified mirror ids to be verified.
8184  * @ids_nr:     Number of specified mirror ids.
8185  * @verbose:    Verbose mode.
8186  *
8187  * This function verifies that each SYNC mirror of a mirrored file
8188  * specified by @fname contains exactly the same data.
8189  *
8190  * If @mirror_ids is specified, then the function will verify the
8191  * mirrors specified by @mirror_ids contain exactly the same data.
8192  *
8193  * If @verbose is specified, then the function will print where the
8194  * differences are if the data do not match. Otherwise, it will
8195  * just return an error in that case.
8196  *
8197  * Return: 0 on success or a negative error code on failure.
8198  */
8199 static inline
8200 int lfs_mirror_verify_file(const char *fname, __u16 *mirror_ids, int ids_nr,
8201                            int verbose)
8202 {
8203         struct verify_chunk chunks_array[1024] = { };
8204         struct llapi_layout *layout = NULL;
8205         struct stat stbuf;
8206         uint32_t flr_state;
8207         int fd;
8208         int chunk_count = 0;
8209         int idx = 0;
8210         int rc = 0;
8211         int rc1 = 0;
8212         int rc2 = 0;
8213
8214         if (stat(fname, &stbuf) < 0) {
8215                 fprintf(stderr, "%s: cannot stat file '%s': %s.\n",
8216                         progname, fname, strerror(errno));
8217                 rc = -errno;
8218                 goto error;
8219         }
8220
8221         if (!S_ISREG(stbuf.st_mode)) {
8222                 fprintf(stderr, "%s: '%s' is not a regular file.\n",
8223                         progname, fname);
8224                 rc = -EINVAL;
8225                 goto error;
8226         }
8227
8228         if (stbuf.st_size == 0) {
8229                 if (verbose)
8230                         fprintf(stdout, "%s: '%s' file size is 0.\n",
8231                                 progname, fname);
8232                 rc = 0;
8233                 goto error;
8234         }
8235
8236         fd = open(fname, O_DIRECT | O_RDONLY);
8237         if (fd < 0) {
8238                 fprintf(stderr, "%s: cannot open '%s': %s.\n",
8239                         progname, fname, strerror(errno));
8240                 rc = -errno;
8241                 goto error;
8242         }
8243
8244         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
8245         if (rc < 0) {
8246                 fprintf(stderr, "%s: '%s' llapi_lease_acquire failed: %s.\n",
8247                         progname, fname, strerror(errno));
8248                 goto close_fd;
8249         }
8250
8251         layout = llapi_layout_get_by_fd(fd, 0);
8252         if (layout == NULL) {
8253                 fprintf(stderr, "%s: '%s' llapi_layout_get_by_fd failed: %s.\n",
8254                         progname, fname, strerror(errno));
8255                 rc = -errno;
8256                 llapi_lease_release(fd);
8257                 goto close_fd;
8258         }
8259
8260         rc = llapi_layout_flags_get(layout, &flr_state);
8261         if (rc < 0) {
8262                 fprintf(stderr, "%s: '%s' llapi_layout_flags_get failed: %s.\n",
8263                         progname, fname, strerror(errno));
8264                 rc = -errno;
8265                 goto free_layout;
8266         }
8267
8268         flr_state &= LCM_FL_FLR_MASK;
8269         switch (flr_state) {
8270         case LCM_FL_NONE:
8271                 rc = -EINVAL;
8272                 fprintf(stderr, "%s: '%s' file state error: %s.\n",
8273                         progname, fname, llapi_layout_flags_string(flr_state));
8274                 goto free_layout;
8275         default:
8276                 break;
8277         }
8278
8279         /* find out mirror chunks to be verified */
8280         chunk_count = lfs_mirror_prepare_chunk(layout, chunks_array,
8281                                                ARRAY_SIZE(chunks_array));
8282         if (chunk_count < 0) {
8283                 rc = chunk_count;
8284                 goto free_layout;
8285         }
8286
8287         if (ids_nr > 0)
8288                 /* filter specified mirror ids */
8289                 filter_mirror_id(chunks_array, chunk_count, mirror_ids, ids_nr);
8290
8291         if (verbose > 2)
8292                 print_chunks(fname, chunks_array, chunk_count);
8293
8294         for (idx = 0; idx < chunk_count; idx++) {
8295                 if (chunks_array[idx].chunk.e_start >= stbuf.st_size) {
8296                         if (verbose)
8297                                 fprintf(stdout,
8298                                         "%s: '%s' chunk "DEXT" exceeds file size %#llx: skipped\n",
8299                                         progname, fname,
8300                                         PEXT(&chunks_array[idx].chunk),
8301                                         (unsigned long long)stbuf.st_size);
8302                         break;
8303                 }
8304
8305                 if (chunks_array[idx].mirror_count == 0) {
8306                         fprintf(stderr,
8307                                 "%s: '%s' chunk "DEXT" is invalid in all of the mirrors: ",
8308                                 progname, fname,
8309                                 PEXT(&chunks_array[idx].chunk));
8310                         if (verbose) {
8311                                 fprintf(stderr, "skipped\n");
8312                                 continue;
8313                         }
8314                         rc = -EINVAL;
8315                         fprintf(stderr, "failed\n");
8316                         goto free_layout;
8317                 }
8318
8319                 if (chunks_array[idx].mirror_count == 1) {
8320                         if (verbose)
8321                                 fprintf(stdout,
8322                                         "%s: '%s' chunk "DEXT" is only valid in mirror %u: skipped\n",
8323                                         progname, fname,
8324                                         PEXT(&chunks_array[idx].chunk),
8325                                         chunks_array[idx].mirror_id[0]);
8326                         continue;
8327                 }
8328
8329                 rc = llapi_lease_check(fd);
8330                 if (rc != LL_LEASE_RDLCK) {
8331                         fprintf(stderr, "%s: '%s' lost lease lock.\n",
8332                                 progname, fname);
8333                         goto free_layout;
8334                 }
8335
8336                 /* verify one chunk */
8337                 rc1 = lfs_mirror_verify_chunk(fd, stbuf.st_size,
8338                                               &chunks_array[idx], verbose);
8339                 if (rc1 < 0) {
8340                         rc2 = rc1;
8341                         if (!verbose) {
8342                                 rc = rc1;
8343                                 goto free_layout;
8344                         }
8345                 }
8346         }
8347
8348         if (rc2 < 0)
8349                 rc = rc2;
8350
8351 free_layout:
8352         llapi_layout_free(layout);
8353         llapi_lease_release(fd);
8354 close_fd:
8355         close(fd);
8356 error:
8357         return rc;
8358 }
8359
8360 /**
8361  * lfs_mirror_verify() - Parse and execute lfs mirror verify command.
8362  * @argc: The count of lfs mirror verify command line arguments.
8363  * @argv: Array of strings for lfs mirror verify command line arguments.
8364  *
8365  * This function parses lfs mirror verify command and verifies the
8366  * specified mirrored file(s).
8367  *
8368  * Return: 0 on success or a negative error code on failure.
8369  */
8370 static inline int lfs_mirror_verify(int argc, char **argv)
8371 {
8372         __u16 mirror_ids[LUSTRE_MIRROR_COUNT_MAX] = { 0 };
8373         int ids_nr = 0;
8374         int c;
8375         int verbose = 0;
8376         int rc = 0;
8377         int rc1 = 0;
8378         char cmd[PATH_MAX];
8379
8380         struct option long_opts[] = {
8381         { .val = 'o',   .name = "only",         .has_arg = required_argument },
8382         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
8383         { .name = NULL } };
8384
8385         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
8386         progname = cmd;
8387         while ((c = getopt_long(argc, argv, "o:v", long_opts, NULL)) >= 0) {
8388                 switch (c) {
8389                 case 'o':
8390                         rc = parse_mirror_ids(mirror_ids,
8391                                               ARRAY_SIZE(mirror_ids),
8392                                               optarg);
8393                         if (rc < 0) {
8394                                 fprintf(stderr,
8395                                         "%s: bad mirror ids '%s'.\n",
8396                                         progname, optarg);
8397                                 goto error;
8398                         }
8399                         ids_nr = rc;
8400                         if (ids_nr < 2) {
8401                                 fprintf(stderr,
8402                                         "%s: at least 2 mirror ids needed with '--only' option.\n",
8403                                         progname);
8404                                 rc = CMD_HELP;
8405                                 goto error;
8406                         }
8407                         break;
8408                 case 'v':
8409                         verbose++;
8410                         break;
8411                 default:
8412                         fprintf(stderr, "%s: options '%s' unrecognized.\n",
8413                                 progname, argv[optind - 1]);
8414                         rc = -EINVAL;
8415                         goto error;
8416                 }
8417         }
8418
8419         if (argc == optind) {
8420                 fprintf(stderr, "%s: no file name given.\n", progname);
8421                 rc = CMD_HELP;
8422                 goto error;
8423         }
8424
8425         if (ids_nr > 0 && argc > optind + 1) {
8426                 fprintf(stderr,
8427                         "%s: '--only' cannot be used upon multiple files.\n",
8428                         progname);
8429                 rc = CMD_HELP;
8430                 goto error;
8431
8432         }
8433
8434         if (ids_nr > 0) {
8435                 rc = verify_mirror_ids(argv[optind], mirror_ids, ids_nr);
8436                 if (rc < 0)
8437                         goto error;
8438         }
8439
8440         rc = 0;
8441         for (; optind < argc; optind++) {
8442                 rc1 = lfs_mirror_verify_file(argv[optind], mirror_ids, ids_nr,
8443                                              verbose);
8444                 if (rc1 < 0)
8445                         rc = rc1;
8446         }
8447 error:
8448         return rc;
8449 }
8450
8451 /**
8452  * lfs_mirror() - Parse and execute lfs mirror commands.
8453  * @argc: The count of lfs mirror command line arguments.
8454  * @argv: Array of strings for lfs mirror command line arguments.
8455  *
8456  * This function parses lfs mirror commands and performs the
8457  * corresponding functions specified in mirror_cmdlist[].
8458  *
8459  * Return: 0 on success or an error code on failure.
8460  */
8461 static int lfs_mirror(int argc, char **argv)
8462 {
8463         char cmd[PATH_MAX];
8464         int rc = 0;
8465
8466         setlinebuf(stdout);
8467
8468         Parser_init("lfs-mirror > ", mirror_cmdlist);
8469
8470         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
8471         progname = cmd;
8472         program_invocation_short_name = cmd;
8473         if (argc > 1)
8474                 rc = Parser_execarg(argc - 1, argv + 1, mirror_cmdlist);
8475         else
8476                 rc = Parser_commands();
8477
8478         return rc < 0 ? -rc : rc;
8479 }
8480
8481 /**
8482  * lfs_mirror_list_commands() - List lfs mirror commands.
8483  * @argc: The count of command line arguments.
8484  * @argv: Array of strings for command line arguments.
8485  *
8486  * This function lists lfs mirror commands defined in mirror_cmdlist[].
8487  *
8488  * Return: 0 on success.
8489  */
8490 static int lfs_mirror_list_commands(int argc, char **argv)
8491 {
8492         char buffer[81] = "";
8493
8494         Parser_list_commands(mirror_cmdlist, buffer, sizeof(buffer),
8495                              NULL, 0, 4);
8496
8497         return 0;
8498 }
8499
8500 static int lfs_list_commands(int argc, char **argv)
8501 {
8502         char buffer[81] = ""; /* 80 printable chars + terminating NUL */
8503
8504         Parser_list_commands(cmdlist, buffer, sizeof(buffer), NULL, 0, 4);
8505
8506         return 0;
8507 }
8508
8509 int main(int argc, char **argv)
8510 {
8511         int rc;
8512
8513         /* Ensure that liblustreapi constructor has run */
8514         if (!llapi_liblustreapi_initialized())
8515                 fprintf(stderr, "liblustreapi was not properly initialized\n");
8516
8517         setlinebuf(stdout);
8518         opterr = 0;
8519
8520         Parser_init("lfs > ", cmdlist);
8521
8522         progname = program_invocation_short_name; /* Used in error messages */
8523         if (argc > 1) {
8524                 llapi_set_command_name(argv[1]);
8525                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
8526                 llapi_clear_command_name();
8527         } else {
8528                 rc = Parser_commands();
8529         }
8530
8531         return rc < 0 ? -rc : rc;
8532 }
8533
8534 #ifdef _LUSTRE_IDL_H_
8535 /* Everything we need here should be included by lustreapi.h. */
8536 # error "lfs should not depend on lustre_idl.h"
8537 #endif /* _LUSTRE_IDL_H_ */