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