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