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