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