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