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