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