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