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