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