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