Whamcloud - gitweb
LU-5243 utils: use goto rather than GOTO()
[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.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 2013, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/utils/lfs.c
37  *
38  * Author: Peter J. Braam <braam@clusterfs.com>
39  * Author: Phil Schwan <phil@clusterfs.com>
40  * Author: Robert Read <rread@clusterfs.com>
41  */
42
43 /* for O_DIRECTORY */
44 #ifndef _GNU_SOURCE
45 #define _GNU_SOURCE
46 #endif
47
48 #include <stdlib.h>
49 #include <stdio.h>
50 #include <getopt.h>
51 #include <string.h>
52 #include <mntent.h>
53 #include <errno.h>
54 #include <err.h>
55 #include <pwd.h>
56 #include <grp.h>
57 #include <sys/quota.h>
58 #include <sys/types.h>
59 #include <sys/stat.h>
60 #include <fcntl.h>
61 #include <dirent.h>
62 #include <time.h>
63 #include <ctype.h>
64 #ifdef HAVE_SYS_QUOTA_H
65 # include <sys/quota.h>
66 #endif
67
68 #include <libcfs/libcfs.h>
69 #include <libcfs/libcfsutil.h>
70 #include <lustre/lustreapi.h>
71 #include <lustre_ver.h>
72
73 /* all functions */
74 static int lfs_setstripe(int argc, char **argv);
75 static int lfs_find(int argc, char **argv);
76 static int lfs_getstripe(int argc, char **argv);
77 static int lfs_getdirstripe(int argc, char **argv);
78 static int lfs_setdirstripe(int argc, char **argv);
79 static int lfs_rmentry(int argc, char **argv);
80 static int lfs_osts(int argc, char **argv);
81 static int lfs_mdts(int argc, char **argv);
82 static int lfs_df(int argc, char **argv);
83 static int lfs_getname(int argc, char **argv);
84 static int lfs_check(int argc, char **argv);
85 #ifdef HAVE_SYS_QUOTA_H
86 static int lfs_quotacheck(int argc, char **argv);
87 static int lfs_quotaon(int argc, char **argv);
88 static int lfs_quotaoff(int argc, char **argv);
89 static int lfs_setquota(int argc, char **argv);
90 static int lfs_quota(int argc, char **argv);
91 #endif
92 static int lfs_flushctx(int argc, char **argv);
93 static int lfs_join(int argc, char **argv);
94 static int lfs_lsetfacl(int argc, char **argv);
95 static int lfs_lgetfacl(int argc, char **argv);
96 static int lfs_rsetfacl(int argc, char **argv);
97 static int lfs_rgetfacl(int argc, char **argv);
98 static int lfs_cp(int argc, char **argv);
99 static int lfs_ls(int argc, char **argv);
100 static int lfs_poollist(int argc, char **argv);
101 static int lfs_changelog(int argc, char **argv);
102 static int lfs_changelog_clear(int argc, char **argv);
103 static int lfs_fid2path(int argc, char **argv);
104 static int lfs_path2fid(int argc, char **argv);
105 static int lfs_data_version(int argc, char **argv);
106 static int lfs_hsm_state(int argc, char **argv);
107 static int lfs_hsm_set(int argc, char **argv);
108 static int lfs_hsm_clear(int argc, char **argv);
109 static int lfs_hsm_action(int argc, char **argv);
110 static int lfs_hsm_archive(int argc, char **argv);
111 static int lfs_hsm_restore(int argc, char **argv);
112 static int lfs_hsm_release(int argc, char **argv);
113 static int lfs_hsm_remove(int argc, char **argv);
114 static int lfs_hsm_cancel(int argc, char **argv);
115 static int lfs_swap_layouts(int argc, char **argv);
116 static int lfs_mv(int argc, char **argv);
117
118 #define SETSTRIPE_USAGE(_cmd, _tgt) \
119         "usage: "_cmd" [--stripe-count|-c <stripe_count>]\n"\
120         "                 [--stripe-index|-i <start_ost_idx>]\n"\
121         "                 [--stripe-size|-S <stripe_size>]\n"\
122         "                 [--pool|-p <pool_name>]\n"\
123         "                 [--block|-b] "_tgt"\n"\
124         "\tstripe_size:  Number of bytes on each OST (0 filesystem default)\n"\
125         "\t              Can be specified with k, m or g (in KB, MB and GB\n"\
126         "\t              respectively)\n"\
127         "\tstart_ost_idx: OST index of first stripe (-1 default)\n"\
128         "\tstripe_count: Number of OSTs to stripe over (0 default, -1 all)\n"\
129         "\tpool_name:    Name of OST pool to use (default none)\n"\
130         "\tblock:        Block file access during data migration"
131
132 /* all avaialable commands */
133 command_t cmdlist[] = {
134         {"setstripe", lfs_setstripe, 0,
135          "Create a new file with a specific striping pattern or\n"
136          "set the default striping pattern on an existing directory or\n"
137          "delete the default striping pattern from an existing directory\n"
138          "usage: setstripe -d <directory>   (to delete default striping)\n"\
139          " or\n"
140          SETSTRIPE_USAGE("setstripe", "<directory|filename>")},
141         {"getstripe", lfs_getstripe, 0,
142          "To list the striping info for a given file or files in a\n"
143          "directory or recursively for all files in a directory tree.\n"
144          "usage: getstripe [--ost|-O <uuid>] [--quiet | -q] [--verbose | -v]\n"
145          "                 [--stripe-count|-c] [--stripe-index|-i]\n"
146          "                 [--pool|-p] [--stripe-size|-S] [--directory|-d]\n"
147          "                 [--mdt-index|-M] [--recursive|-r] [--raw|-R]\n"
148          "                 [--layout|-L]\n"
149          "                 <directory|filename> ..."},
150         {"setdirstripe", lfs_setdirstripe, 0,
151          "To create a striped directory on a specified MDT. This can only\n"
152          "be done on MDT0 with the right of administrator.\n"
153          "usage: setdirstripe <--count|-c stripe_count>\n"
154          "              [--index|-i mdt_index] [--hash-type|-t hash_type]\n"
155          "              [--default_stripe|-D ] [--mode|-m mode] <dir>\n"
156          "\tstripe_count: stripe count of the striped directory\n"
157          "\tmdt_index:  MDT index of first stripe\n"
158          "\thash_type:  hash type of the striped directory. Hash types:\n"
159          "      fnv_1a_64 FNV-1a hash algorithm (default)\n"
160          "      all_char  sum of characters % MDT_COUNT (not recommended)\n"
161          "\tdefault_stripe: set default dirstripe of the directory\n"
162          "\tmode: the mode of the directory\n"},
163         {"getdirstripe", lfs_getdirstripe, 0,
164          "To list the striping info for a given directory\n"
165          "or recursively for all directories in a directory tree.\n"
166          "usage: getdirstripe [--obd|-O <uuid>] [--quiet|-q] [--verbose|-v]\n"
167          "               [--count|-c ] [--index|-i ] [--raw|-R]\n"
168          "               [--recursive | -r] [ --default_stripe | -D ] <dir> "},
169         {"mkdir", lfs_setdirstripe, 0,
170          "To create a striped directory on a specified MDT. This can only\n"
171          "be done on MDT0 with the right of administrator.\n"
172          "usage: mkdir <--count|-c stripe_count>\n"
173          "              [--index|-i mdt_index] [--hash-type|-t hash_type]\n"
174          "              [--default_stripe|-D ] [--mode|-m mode] <dir>\n"
175          "\tstripe_count: stripe count of the striped directory\n"
176          "\tmdt_index:  MDT index of first stripe\n"
177          "\thash_type:  hash type of the striped directory. Hash types:\n"
178          "      fnv_1a_64 FNV-1a hash algorithm (default)\n"
179          "      all_char  sum of characters % MDT_COUNT (not recommended)\n"
180          "\tdefault_stripe: set default dirstripe of the directory\n"
181          "\tmode: the mode of the directory\n"},
182         {"rm_entry", lfs_rmentry, 0,
183          "To remove the name entry of the remote directory. Note: This\n"
184          "command will only delete the name entry, i.e. the remote directory\n"
185          "will become inaccessable after this command. This can only be done\n"
186          "by the administrator\n"
187          "usage: rm_entry <dir>\n"},
188         {"pool_list", lfs_poollist, 0,
189          "List pools or pool OSTs\n"
190          "usage: pool_list <fsname>[.<pool>] | <pathname>\n"},
191         {"find", lfs_find, 0,
192          "find files matching given attributes recursively in directory tree.\n"
193          "usage: find <directory|filename> ...\n"
194          "     [[!] --atime|-A [+-]N] [[!] --ctime|-C [+-]N]\n"
195          "     [[!] --mtime|-M [+-]N] [[!] --mdt|-m <uuid|index,...>]\n"
196          "     [--maxdepth|-D N] [[!] --name|-n <pattern>]\n"
197          "     [[!] --ost|-O <uuid|index,...>] [--print|-p] [--print0|-P]\n"
198          "     [[!] --size|-s [+-]N[bkMGTPE]]\n"
199          "     [[!] --stripe-count|-c [+-]<stripes>]\n"
200          "     [[!] --stripe-index|-i <index,...>]\n"
201          "     [[!] --stripe-size|-S [+-]N[kMGT]] [[!] --type|-t <filetype>]\n"
202          "     [[!] --gid|-g|--group|-G <gid>|<gname>]\n"
203          "     [[!] --uid|-u|--user|-U <uid>|<uname>] [[!] --pool <pool>]\n"
204          "     [[!] --layout|-L released,raid0]\n"
205          "\t !: used before an option indicates 'NOT' requested attribute\n"
206          "\t -: used before a value indicates 'AT MOST' requested value\n"
207          "\t +: used before a value indicates 'AT LEAST' requested value\n"},
208         {"check", lfs_check, 0,
209          "Display the status of MDS or OSTs (as specified in the command)\n"
210          "or all the servers (MDS and OSTs).\n"
211          "usage: check <osts|mds|servers>"},
212         {"join", lfs_join, 0,
213          "join two lustre files into one.\n"
214          "obsolete, HEAD does not support it anymore.\n"},
215         {"osts", lfs_osts, 0, "list OSTs connected to client "
216          "[for specified path only]\n" "usage: osts [path]"},
217         {"mdts", lfs_mdts, 0, "list MDTs connected to client "
218          "[for specified path only]\n" "usage: mdts [path]"},
219         {"df", lfs_df, 0,
220          "report filesystem disk space usage or inodes usage"
221          "of each MDS and all OSDs or a batch belonging to a specific pool .\n"
222          "Usage: df [-i] [-h] [--lazy|-l] [--pool|-p <fsname>[.<pool>] [path]"},
223         {"getname", lfs_getname, 0, "list instances and specified mount points "
224          "[for specified path only]\n"
225          "Usage: getname [-h]|[path ...] "},
226 #ifdef HAVE_SYS_QUOTA_H
227         {"quotacheck", lfs_quotacheck, 0,
228          "Scan the specified filesystem for disk usage, and create,\n"
229          "or update quota files. Deprecated as of 2.4.0.\n"
230          "usage: quotacheck [ -ug ] <filesystem>"},
231         {"quotaon", lfs_quotaon, 0, "Turn filesystem"
232          " quotas on. Deprecated as of 2.4.0.\n"
233          "usage: quotaon [ -ugf ] <filesystem>"},
234         {"quotaoff", lfs_quotaoff, 0, "Turn filesystem"
235          " quotas off. Deprecated as of 2.4.0.\n"
236          "usage: quotaoff [ -ug ] <filesystem>"},
237         {"setquota", lfs_setquota, 0, "Set filesystem quotas.\n"
238          "usage: setquota <-u|-g> <uname>|<uid>|<gname>|<gid>\n"
239          "                -b <block-softlimit> -B <block-hardlimit>\n"
240          "                -i <inode-softlimit> -I <inode-hardlimit> <filesystem>\n"
241          "       setquota <-u|--user|-g|--group> <uname>|<uid>|<gname>|<gid>\n"
242          "                [--block-softlimit <block-softlimit>]\n"
243          "                [--block-hardlimit <block-hardlimit>]\n"
244          "                [--inode-softlimit <inode-softlimit>]\n"
245          "                [--inode-hardlimit <inode-hardlimit>] <filesystem>\n"
246          "       setquota [-t] <-u|--user|-g|--group>\n"
247          "                [--block-grace <block-grace>]\n"
248          "                [--inode-grace <inode-grace>] <filesystem>\n"
249          "       -b can be used instead of --block-softlimit/--block-grace\n"
250          "       -B can be used instead of --block-hardlimit\n"
251          "       -i can be used instead of --inode-softlimit/--inode-grace\n"
252          "       -I can be used instead of --inode-hardlimit\n\n"
253          "Note: The total quota space will be split into many qunits and\n"
254          "      balanced over all server targets, the minimal qunit size is\n"
255          "      1M bytes for block space and 1K inodes for inode space.\n\n"
256          "      Quota space rebalancing process will stop when this mininum\n"
257          "      value is reached. As a result, quota exceeded can be returned\n"
258          "      while many targets still have 1MB or 1K inodes of spare\n"
259          "      quota space."},
260         {"quota", lfs_quota, 0, "Display disk usage and limits.\n"
261          "usage: quota [-q] [-v] [-h] [-o <obd_uuid>|-i <mdt_idx>|-I "
262                        "<ost_idx>]\n"
263          "             [<-u|-g> <uname>|<uid>|<gname>|<gid>] <filesystem>\n"
264          "       quota [-o <obd_uuid>|-i <mdt_idx>|-I <ost_idx>] -t <-u|-g> <filesystem>"},
265 #endif
266         {"flushctx", lfs_flushctx, 0, "Flush security context for current user.\n"
267          "usage: flushctx [-k] [mountpoint...]"},
268         {"lsetfacl", lfs_lsetfacl, 0,
269          "Remote user setfacl for user/group on the same remote client.\n"
270          "usage: lsetfacl [-bkndRLPvh] [{-m|-x} acl_spec] [{-M|-X} acl_file] file ..."},
271         {"lgetfacl", lfs_lgetfacl, 0,
272          "Remote user getfacl for user/group on the same remote client.\n"
273          "usage: lgetfacl [-dRLPvh] file ..."},
274         {"rsetfacl", lfs_rsetfacl, 0,
275          "Remote user setfacl for user/group on other clients.\n"
276          "usage: rsetfacl [-bkndRLPvh] [{-m|-x} acl_spec] [{-M|-X} acl_file] file ..."},
277         {"rgetfacl", lfs_rgetfacl, 0,
278          "Remote user getfacl for user/group on other clients.\n"
279          "usage: rgetfacl [-dRLPvh] file ..."},
280         {"cp", lfs_cp, 0,
281          "Remote user copy files and directories.\n"
282          "usage: cp [OPTION]... [-T] SOURCE DEST\n\tcp [OPTION]... SOURCE... DIRECTORY\n\tcp [OPTION]... -t DIRECTORY SOURCE..."},
283         {"ls", lfs_ls, 0,
284          "Remote user list directory contents.\n"
285          "usage: ls [OPTION]... [FILE]..."},
286         {"changelog", lfs_changelog, 0,
287          "Show the metadata changes on an MDT."
288          "\nusage: changelog <mdtname> [startrec [endrec]]"},
289         {"changelog_clear", lfs_changelog_clear, 0,
290          "Indicate that old changelog records up to <endrec> are no longer of "
291          "interest to consumer <id>, allowing the system to free up space.\n"
292          "An <endrec> of 0 means all records.\n"
293          "usage: changelog_clear <mdtname> <id> <endrec>"},
294         {"fid2path", lfs_fid2path, 0,
295          "Resolve the full path(s) for given FID(s). For a specific hardlink "
296          "specify link number <linkno>.\n"
297         /* "For a historical link name, specify changelog record <recno>.\n" */
298          "usage: fid2path [--link <linkno>] <fsname|rootpath> <fid> ..."
299                 /* [ --rec <recno> ] */ },
300         {"path2fid", lfs_path2fid, 0, "Display the fid(s) for a given path(s).\n"
301          "usage: path2fid <path> ..."},
302         {"data_version", lfs_data_version, 0, "Display file data version for "
303          "a given path.\n" "usage: data_version -[n|r|w] <path>"},
304         {"hsm_state", lfs_hsm_state, 0, "Display the HSM information (states, "
305          "undergoing actions) for given files.\n usage: hsm_state <file> ..."},
306         {"hsm_set", lfs_hsm_set, 0, "Set HSM user flag on specified files.\n"
307          "usage: hsm_set [--norelease] [--noarchive] [--dirty] [--exists] "
308          "[--archived] [--lost] <file> ..."},
309         {"hsm_clear", lfs_hsm_clear, 0, "Clear HSM user flag on specified "
310          "files.\n"
311          "usage: hsm_clear [--norelease] [--noarchive] [--dirty] [--exists] "
312          "[--archived] [--lost] <file> ..."},
313         {"hsm_action", lfs_hsm_action, 0, "Display current HSM request for "
314          "given files.\n" "usage: hsm_action <file> ..."},
315         {"hsm_archive", lfs_hsm_archive, 0,
316          "Archive file to external storage.\n"
317          "usage: hsm_archive [--filelist FILELIST] [--data DATA] [--archive NUM] "
318          "<file> ..."},
319         {"hsm_restore", lfs_hsm_restore, 0,
320          "Restore file from external storage.\n"
321          "usage: hsm_restore [--filelist FILELIST] [--data DATA] <file> ..."},
322         {"hsm_release", lfs_hsm_release, 0,
323          "Release files from Lustre.\n"
324          "usage: hsm_release [--filelist FILELIST] [--data DATA] <file> ..."},
325         {"hsm_remove", lfs_hsm_remove, 0,
326          "Remove file copy from external storage.\n"
327          "usage: hsm_remove [--filelist FILELIST] [--data DATA] <file> ..."},
328         {"hsm_cancel", lfs_hsm_cancel, 0,
329          "Cancel requests related to specified files.\n"
330          "usage: hsm_cancel [--filelist FILELIST] [--data DATA] <file> ..."},
331         {"swap_layouts", lfs_swap_layouts, 0, "Swap layouts between 2 files.\n"
332          "usage: swap_layouts <path1> <path2>"},
333         {"migrate", lfs_setstripe, 0, "migrate file from one OST layout to "
334          "another (may be not safe with concurent writes).\n"
335          SETSTRIPE_USAGE("migrate  ", "<filename>")},
336         {"mv", lfs_mv, 0,
337          "To move directories between MDTs.\n"
338          "usage: mv <directory|filename> [--mdt-index|-M] <mdt_index> "
339          "[--verbose|-v]\n"},
340         {"help", Parser_help, 0, "help"},
341         {"exit", Parser_quit, 0, "quit"},
342         {"quit", Parser_quit, 0, "quit"},
343         { 0, 0, 0, NULL }
344 };
345
346 #define MIGRATION_BLOCKS 1
347
348 static int lfs_migrate(char *name, unsigned long long stripe_size,
349                        int stripe_offset, int stripe_count,
350                        int stripe_pattern, char *pool_name,
351                        __u64 migration_flags)
352 {
353         int                      fd, fdv;
354         char                     volatile_file[PATH_MAX +
355                                                 LUSTRE_VOLATILE_HDR_LEN + 4];
356         char                     parent[PATH_MAX];
357         char                    *ptr;
358         int                      rc;
359         __u64                    dv1;
360         struct lov_user_md      *lum = NULL;
361         int                      lumsz;
362         int                      bufsz;
363         void                    *buf = NULL;
364         int                      rsize, wsize;
365         __u64                    rpos, wpos, bufoff;
366         int                      gid = 0, sz;
367         int                      have_gl = 0;
368         struct stat              st, stv;
369
370         /* find the right size for the IO and allocate the buffer */
371         lumsz = lov_user_md_size(LOV_MAX_STRIPE_COUNT, LOV_USER_MAGIC_V3);
372         lum = malloc(lumsz);
373         if (lum == NULL) {
374                 rc = -ENOMEM;
375                 goto free;
376         }
377
378         rc = llapi_file_get_stripe(name, lum);
379         /* failure can come from may case and some may be not real error
380          * (eg: no stripe)
381          * in case of a real error, a later call will failed with a better
382          * error management */
383         if (rc < 0)
384                 bufsz = 1024*1024;
385         else
386                 bufsz = lum->lmm_stripe_size;
387         rc = posix_memalign(&buf, getpagesize(), bufsz);
388         if (rc != 0) {
389                 rc = -rc;
390                 goto free;
391         }
392
393         if (migration_flags & MIGRATION_BLOCKS) {
394                 /* generate a random id for the grouplock */
395                 fd = open("/dev/urandom", O_RDONLY);
396                 if (fd == -1) {
397                         rc = -errno;
398                         fprintf(stderr, "cannot open /dev/urandom (%s)\n",
399                                 strerror(-rc));
400                         goto free;
401                 }
402                 sz = sizeof(gid);
403                 rc = read(fd, &gid, sz);
404                 close(fd);
405                 if (rc < sz) {
406                         rc = -errno;
407                         fprintf(stderr, "cannot read %d bytes from"
408                                 " /dev/urandom (%s)\n", sz, strerror(-rc));
409                         goto free;
410                 }
411         }
412
413         /* search for file directory pathname */
414         if (strlen(name) > sizeof(parent)-1) {
415                 rc = -E2BIG;
416                 goto free;
417         }
418         strncpy(parent, name, sizeof(parent));
419         ptr = strrchr(parent, '/');
420         if (ptr == NULL) {
421                 if (getcwd(parent, sizeof(parent)) == NULL) {
422                         rc = -errno;
423                         goto free;
424                 }
425         } else {
426                 if (ptr == parent)
427                         strcpy(parent, "/");
428                 else
429                         *ptr = '\0';
430         }
431         rc = snprintf(volatile_file, sizeof(volatile_file), "%s/%s::", parent,
432                       LUSTRE_VOLATILE_HDR);
433         if (rc >= sizeof(volatile_file)) {
434                 rc = -E2BIG;
435                 goto free;
436         }
437
438         /* create, open a volatile file, use caching (ie no directio) */
439         /* exclusive create is not needed because volatile files cannot
440          * conflict on name by construction */
441         fdv = llapi_file_open_pool(volatile_file, O_CREAT | O_WRONLY,
442                                    0644, stripe_size, stripe_offset,
443                                    stripe_count, stripe_pattern, pool_name);
444         if (fdv < 0) {
445                 rc = fdv;
446                 fprintf(stderr, "cannot create volatile file in %s (%s)\n",
447                         parent, strerror(-rc));
448                 goto free;
449         }
450
451         /* open file, direct io */
452         /* even if the file is only read, WR mode is nedeed to allow
453          * layout swap on fd */
454         fd = open(name, O_RDWR | O_DIRECT);
455         if (fd == -1) {
456                 rc = -errno;
457                 fprintf(stderr, "cannot open %s (%s)\n", name, strerror(-rc));
458                 close(fdv);
459                 goto free;
460         }
461
462         /* Not-owner (root?) special case.
463          * Need to set owner/group of volatile file like original.
464          * This will allow to pass related check during layout_swap.
465          */
466         rc = fstat(fd, &st);
467         if (rc != 0) {
468                 rc = -errno;
469                 fprintf(stderr, "cannot stat %s (%s)\n", name,
470                         strerror(errno));
471                 goto error;
472         }
473         rc = fstat(fdv, &stv);
474         if (rc != 0) {
475                 rc = -errno;
476                 fprintf(stderr, "cannot stat %s (%s)\n", volatile_file,
477                         strerror(errno));
478                 goto error;
479         }
480         if (st.st_uid != stv.st_uid || st.st_gid != stv.st_gid) {
481                 rc = fchown(fdv, st.st_uid, st.st_gid);
482                 if (rc != 0) {
483                         rc = -errno;
484                         fprintf(stderr, "cannot chown %s (%s)\n", name,
485                                 strerror(errno));
486                         goto error;
487                 }
488         }
489
490         /* get file data version */
491         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
492         if (rc != 0) {
493                 fprintf(stderr, "cannot get dataversion on %s (%s)\n",
494                         name, strerror(-rc));
495                 goto error;
496         }
497
498         if (migration_flags & MIGRATION_BLOCKS) {
499                 /* take group lock to limit concurent access
500                  * this will be no more needed when exclusive access will
501                  * be implemented (see LU-2919) */
502                 /* group lock is taken after data version read because it
503                  * blocks data version call */
504                 if (ioctl(fd, LL_IOC_GROUP_LOCK, gid) == -1) {
505                         rc = -errno;
506                         fprintf(stderr, "cannot get group lock on %s (%s)\n",
507                                 name, strerror(-rc));
508                         goto error;
509                 }
510                 have_gl = 1;
511         }
512
513         /* copy data */
514         rpos = 0;
515         wpos = 0;
516         bufoff = 0;
517         rsize = -1;
518         do {
519                 /* read new data only if we have written all
520                  * previously read data */
521                 if (wpos == rpos) {
522                         rsize = read(fd, buf, bufsz);
523                         if (rsize < 0) {
524                                 rc = -errno;
525                                 fprintf(stderr, "read failed on %s"
526                                         " (%s)\n", name,
527                                         strerror(-rc));
528                                 goto error;
529                         }
530                         rpos += rsize;
531                         bufoff = 0;
532                 }
533                 /* eof ? */
534                 if (rsize == 0)
535                         break;
536                 wsize = write(fdv, buf + bufoff, rpos - wpos);
537                 if (wsize < 0) {
538                         rc = -errno;
539                         fprintf(stderr, "write failed on volatile"
540                                 " for %s (%s)\n", name, strerror(-rc));
541                         goto error;
542                 }
543                 wpos += wsize;
544                 bufoff += wsize;
545         } while (1);
546
547         /* flush data */
548         fsync(fdv);
549
550         if (migration_flags & MIGRATION_BLOCKS) {
551                 /* give back group lock */
552                 if (ioctl(fd, LL_IOC_GROUP_UNLOCK, gid) == -1) {
553                         rc = -errno;
554                         fprintf(stderr, "cannot put group lock on %s (%s)\n",
555                                 name, strerror(-rc));
556                 }
557                 have_gl = 0;
558         }
559
560         /* swap layouts
561          * for a migration we need to:
562          * - check data version on file did not change
563          * - keep file mtime
564          * - keep file atime
565          */
566         rc = llapi_fswap_layouts(fd, fdv, dv1, 0,
567                                  SWAP_LAYOUTS_CHECK_DV1 |
568                                  SWAP_LAYOUTS_KEEP_MTIME |
569                                  SWAP_LAYOUTS_KEEP_ATIME);
570         if (rc == -EAGAIN) {
571                 fprintf(stderr, "%s: dataversion changed during copy, "
572                         "migration aborted\n", name);
573                 goto error;
574         }
575         if (rc != 0)
576                 fprintf(stderr, "%s: swap layout to new file failed: %s\n",
577                         name, strerror(-rc));
578
579 error:
580         /* give back group lock */
581         if ((migration_flags & MIGRATION_BLOCKS) && have_gl &&
582             (ioctl(fd, LL_IOC_GROUP_UNLOCK, gid) == -1)) {
583                 /* we keep in rc the original error */
584                 fprintf(stderr, "cannot put group lock on %s (%s)\n",
585                         name, strerror(-errno));
586         }
587
588         close(fdv);
589         close(fd);
590 free:
591         if (lum)
592                 free(lum);
593         if (buf)
594                 free(buf);
595         return rc;
596 }
597
598 /* functions */
599 static int lfs_setstripe(int argc, char **argv)
600 {
601         char                    *fname;
602         int                      result;
603         unsigned long long       st_size;
604         int                      st_offset, st_count;
605         char                    *end;
606         int                      c;
607         int                      delete = 0;
608         char                    *stripe_size_arg = NULL;
609         char                    *stripe_off_arg = NULL;
610         char                    *stripe_count_arg = NULL;
611         char                    *pool_name_arg = NULL;
612         unsigned long long       size_units = 1;
613         int                      migrate_mode = 0;
614         __u64                    migration_flags = 0;
615
616         struct option            long_opts[] = {
617                 /* valid only in migrate mode */
618                 {"block",        no_argument,       0, 'b'},
619 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
620                 /* This formerly implied "stripe-count", but was explicitly
621                  * made "stripe-count" for consistency with other options,
622                  * and to separate it from "mdt-count" when DNE arrives. */
623                 {"count",        required_argument, 0, 'c'},
624 #endif
625                 {"stripe-count", required_argument, 0, 'c'},
626                 {"stripe_count", required_argument, 0, 'c'},
627                 {"delete",       no_argument,       0, 'd'},
628 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
629                 /* This formerly implied "stripe-index", but was explicitly
630                  * made "stripe-index" for consistency with other options,
631                  * and to separate it from "mdt-index" when DNE arrives. */
632                 {"index",        required_argument, 0, 'i'},
633 #endif
634                 {"stripe-index", required_argument, 0, 'i'},
635                 {"stripe_index", required_argument, 0, 'i'},
636 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
637                 /* This formerly implied "stripe-index", but was confusing
638                  * with "file offset" (which will eventually be needed for
639                  * with different layouts by offset), so deprecate it. */
640                 {"offset",       required_argument, 0, 'o'},
641 #endif
642                 {"pool",         required_argument, 0, 'p'},
643 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
644                 /* This formerly implied "--stripe-size", but was confusing
645                  * with "lfs find --size|-s", which means "file size", so use
646                  * the consistent "--stripe-size|-S" for all commands. */
647                 {"size",         required_argument, 0, 's'},
648 #endif
649                 {"stripe-size",  required_argument, 0, 'S'},
650                 {"stripe_size",  required_argument, 0, 'S'},
651                 {0, 0, 0, 0}
652         };
653
654         st_size = 0;
655         st_offset = -1;
656         st_count = 0;
657
658         if (strcmp(argv[0], "migrate") == 0)
659                 migrate_mode = 1;
660
661         optind = 0;
662         while ((c = getopt_long(argc, argv, "c:di:o:p:s:S:",
663                                 long_opts, NULL)) >= 0) {
664                 switch (c) {
665                 case 0:
666                         /* Long options. */
667                         break;
668                 case 'b':
669                         if (migrate_mode == 0) {
670                                 fprintf(stderr, "--block is valid only for"
671                                                 " migrate mode");
672                                 return CMD_HELP;
673                         }
674                         migration_flags |= MIGRATION_BLOCKS;
675                         break;
676                 case 'c':
677 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 6, 53, 0)
678                         if (strcmp(argv[optind - 1], "--count") == 0)
679                                 fprintf(stderr, "warning: '--count' deprecated"
680                                         ", use '--stripe-count' instead\n");
681 #endif
682                         stripe_count_arg = optarg;
683                         break;
684                 case 'd':
685                         /* delete the default striping pattern */
686                         delete = 1;
687                         break;
688 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
689                 case 'o':
690                         fprintf(stderr, "warning: '--offset|-o' deprecated, "
691                                 "use '--stripe-index|-i' instead\n");
692 #endif
693                 case 'i':
694 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 6, 53, 0)
695                         if (strcmp(argv[optind - 1], "--index") == 0)
696                                 fprintf(stderr, "warning: '--index' deprecated"
697                                         ", use '--stripe-index' instead\n");
698 #endif
699                         stripe_off_arg = optarg;
700                         break;
701 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
702                 case 's':
703 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 6, 53, 0)
704                         fprintf(stderr, "warning: '--size|-s' deprecated, "
705                                 "use '--stripe-size|-S' instead\n");
706 #endif
707 #endif /* LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0) */
708                 case 'S':
709                         stripe_size_arg = optarg;
710                         break;
711                 case 'p':
712                         pool_name_arg = optarg;
713                         break;
714                 default:
715                         return CMD_HELP;
716                 }
717         }
718
719         fname = argv[optind];
720
721         if (delete &&
722             (stripe_size_arg != NULL || stripe_off_arg != NULL ||
723              stripe_count_arg != NULL || pool_name_arg != NULL)) {
724                 fprintf(stderr, "error: %s: cannot specify -d with "
725                         "-s, -c, -o, or -p options\n",
726                         argv[0]);
727                 return CMD_HELP;
728         }
729
730         if (optind == argc) {
731                 fprintf(stderr, "error: %s: missing filename|dirname\n",
732                         argv[0]);
733                 return CMD_HELP;
734         }
735
736         /* get the stripe size */
737         if (stripe_size_arg != NULL) {
738                 result = llapi_parse_size(stripe_size_arg, &st_size,
739                                           &size_units, 0);
740                 if (result) {
741                         fprintf(stderr, "error: %s: bad stripe size '%s'\n",
742                                 argv[0], stripe_size_arg);
743                         return result;
744                 }
745         }
746         /* get the stripe offset */
747         if (stripe_off_arg != NULL) {
748                 st_offset = strtol(stripe_off_arg, &end, 0);
749                 if (*end != '\0') {
750                         fprintf(stderr, "error: %s: bad stripe offset '%s'\n",
751                                 argv[0], stripe_off_arg);
752                         return CMD_HELP;
753                 }
754         }
755         /* get the stripe count */
756         if (stripe_count_arg != NULL) {
757                 st_count = strtoul(stripe_count_arg, &end, 0);
758                 if (*end != '\0') {
759                         fprintf(stderr, "error: %s: bad stripe count '%s'\n",
760                                 argv[0], stripe_count_arg);
761                         return CMD_HELP;
762                 }
763         }
764
765         do {
766                 if (migrate_mode)
767                         result = lfs_migrate(fname, st_size, st_offset,
768                                              st_count, 0, pool_name_arg,
769                                              migration_flags);
770                 else
771                         result = llapi_file_create_pool(fname, st_size,
772                                                         st_offset, st_count,
773                                                         0, pool_name_arg);
774                 if (result) {
775                         fprintf(stderr,
776                                 "error: %s: %s stripe file '%s' failed\n",
777                                 argv[0], migrate_mode ? "migrate" : "create",
778                                 fname);
779                         break;
780                 }
781                 fname = argv[++optind];
782         } while (fname != NULL);
783
784         return result;
785 }
786
787 static int lfs_poollist(int argc, char **argv)
788 {
789         if (argc != 2)
790                 return CMD_HELP;
791
792         return llapi_poollist(argv[1]);
793 }
794
795 static int set_time(time_t *time, time_t *set, char *str)
796 {
797         time_t t;
798         int res = 0;
799
800         if (str[0] == '+')
801                 res = 1;
802         else if (str[0] == '-')
803                 res = -1;
804
805         if (res)
806                 str++;
807
808         t = strtol(str, NULL, 0);
809         if (*time < t * 24 * 60 * 60) {
810                 if (res)
811                         str--;
812                 fprintf(stderr, "Wrong time '%s' is specified.\n", str);
813                 return INT_MAX;
814         }
815
816         *set = *time - t * 24 * 60 * 60;
817         return res;
818 }
819
820 #define USER 0
821 #define GROUP 1
822
823 static int name2id(unsigned int *id, char *name, int type)
824 {
825         if (type == USER) {
826                 struct passwd *entry;
827
828                 if (!(entry = getpwnam(name))) {
829                         if (!errno)
830                                 errno = ENOENT;
831                         return -1;
832                 }
833
834                 *id = entry->pw_uid;
835         } else {
836                 struct group *entry;
837
838                 if (!(entry = getgrnam(name))) {
839                         if (!errno)
840                                 errno = ENOENT;
841                         return -1;
842                 }
843
844                 *id = entry->gr_gid;
845         }
846
847         return 0;
848 }
849
850 static int id2name(char **name, unsigned int id, int type)
851 {
852         if (type == USER) {
853                 struct passwd *entry;
854
855                 if (!(entry = getpwuid(id))) {
856                         if (!errno)
857                                 errno = ENOENT;
858                         return -1;
859                 }
860
861                 *name = entry->pw_name;
862         } else {
863                 struct group *entry;
864
865                 if (!(entry = getgrgid(id))) {
866                         if (!errno)
867                                 errno = ENOENT;
868                         return -1;
869                 }
870
871                 *name = entry->gr_name;
872         }
873
874         return 0;
875 }
876
877 static int name2layout(__u32 *layout, char *name)
878 {
879         char *ptr, *lyt;
880
881         *layout = 0;
882         for (ptr = name; ; ptr = NULL) {
883                 lyt = strtok(ptr, ",");
884                 if (lyt == NULL)
885                         break;
886                 if (strcmp(lyt, "released") == 0)
887                         *layout |= LOV_PATTERN_F_RELEASED;
888                 else if (strcmp(lyt, "raid0") == 0)
889                         *layout |= LOV_PATTERN_RAID0;
890                 else
891                         return -1;
892         }
893         return 0;
894 }
895
896 #define FIND_POOL_OPT 3
897 static int lfs_find(int argc, char **argv)
898 {
899         int c, rc;
900         int ret = 0;
901         time_t t;
902         struct find_param param = {
903                 .fp_max_depth = -1,
904                 .quiet = 1,
905         };
906         struct option long_opts[] = {
907                 {"atime",        required_argument, 0, 'A'},
908                 {"stripe-count", required_argument, 0, 'c'},
909                 {"stripe_count", required_argument, 0, 'c'},
910                 {"ctime",        required_argument, 0, 'C'},
911                 {"maxdepth",     required_argument, 0, 'D'},
912                 {"gid",          required_argument, 0, 'g'},
913                 {"group",        required_argument, 0, 'G'},
914                 {"stripe-index", required_argument, 0, 'i'},
915                 {"stripe_index", required_argument, 0, 'i'},
916                 {"layout",       required_argument, 0, 'L'},
917                 {"mdt",          required_argument, 0, 'm'},
918                 {"mtime",        required_argument, 0, 'M'},
919                 {"name",         required_argument, 0, 'n'},
920      /* reserve {"or",           no_argument,     , 0, 'o'}, to match find(1) */
921                 {"obd",          required_argument, 0, 'O'},
922                 {"ost",          required_argument, 0, 'O'},
923                 /* no short option for pool, p/P already used */
924                 {"pool",         required_argument, 0, FIND_POOL_OPT},
925                 {"print0",       no_argument,       0, 'p'},
926                 {"print",        no_argument,       0, 'P'},
927                 {"size",         required_argument, 0, 's'},
928                 {"stripe-size",  required_argument, 0, 'S'},
929                 {"stripe_size",  required_argument, 0, 'S'},
930                 {"type",         required_argument, 0, 't'},
931                 {"uid",          required_argument, 0, 'u'},
932                 {"user",         required_argument, 0, 'U'},
933                 {0, 0, 0, 0}
934         };
935         int pathstart = -1;
936         int pathend = -1;
937         int neg_opt = 0;
938         time_t *xtime;
939         int *xsign;
940         int isoption;
941         char *endptr;
942
943         time(&t);
944
945         optind = 0;
946         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
947         while ((c = getopt_long_only(argc, argv,
948                                      "-A:c:C:D:g:G:i:L:m:M:n:O:Ppqrs:S:t:u:U:v",
949                                      long_opts, NULL)) >= 0) {
950                 xtime = NULL;
951                 xsign = NULL;
952                 if (neg_opt)
953                         --neg_opt;
954                 /* '!' is part of option */
955                 /* when getopt_long_only() finds a string which is not
956                  * an option nor a known option argument it returns 1
957                  * in that case if we already have found pathstart and pathend
958                  * (i.e. we have the list of pathnames),
959                  * the only supported value is "!"
960                  */
961                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
962                 if (!isoption && pathend != -1) {
963                         fprintf(stderr, "err: %s: filename|dirname must either "
964                                         "precede options or follow options\n",
965                                         argv[0]);
966                         ret = CMD_HELP;
967                         goto err;
968                 }
969                 if (!isoption && pathstart == -1)
970                         pathstart = optind - 1;
971                 if (isoption && pathstart != -1 && pathend == -1)
972                         pathend = optind - 2;
973                 switch (c) {
974                 case 0:
975                         /* Long options. */
976                         break;
977                 case 1:
978                         /* unknown; opt is "!" or path component,
979                          * checking done above.
980                          */
981                         if (strcmp(optarg, "!") == 0)
982                                 neg_opt = 2;
983                         break;
984                 case 'A':
985                         xtime = &param.fp_atime;
986                         xsign = &param.fp_asign;
987                         param.fp_exclude_atime = !!neg_opt;
988                         /* no break, this falls through to 'C' for ctime */
989                 case 'C':
990                         if (c == 'C') {
991                                 xtime = &param.fp_ctime;
992                                 xsign = &param.fp_csign;
993                                 param.fp_exclude_ctime = !!neg_opt;
994                         }
995                         /* no break, this falls through to 'M' for mtime */
996                 case 'M':
997                         if (c == 'M') {
998                                 xtime = &param.fp_mtime;
999                                 xsign = &param.fp_msign;
1000                                 param.fp_exclude_mtime = !!neg_opt;
1001                         }
1002                         rc = set_time(&t, xtime, optarg);
1003                         if (rc == INT_MAX) {
1004                                 ret = -1;
1005                                 goto err;
1006                         }
1007                         if (rc)
1008                                 *xsign = rc;
1009                         break;
1010                 case 'c':
1011                         if (optarg[0] == '+') {
1012                                 param.stripecount_sign = -1;
1013                                 optarg++;
1014                         } else if (optarg[0] == '-') {
1015                                 param.stripecount_sign =  1;
1016                                 optarg++;
1017                         }
1018
1019                         param.stripecount = strtoul(optarg, &endptr, 0);
1020                         if (*endptr != '\0') {
1021                                 fprintf(stderr,"error: bad stripe_count '%s'\n",
1022                                         optarg);
1023                                 ret = -1;
1024                                 goto err;
1025                         }
1026                         param.check_stripecount = 1;
1027                         param.exclude_stripecount = !!neg_opt;
1028                         break;
1029                 case 'D':
1030                         param.fp_max_depth = strtol(optarg, 0, 0);
1031                         break;
1032                 case 'g':
1033                 case 'G':
1034                         rc = name2id(&param.fp_gid, optarg, GROUP);
1035                         if (rc) {
1036                                 param.fp_gid = strtoul(optarg, &endptr, 10);
1037                                 if (*endptr != '\0') {
1038                                         fprintf(stderr, "Group/GID: %s cannot "
1039                                                 "be found.\n", optarg);
1040                                         ret = -1;
1041                                         goto err;
1042                                 }
1043                         }
1044                         param.fp_exclude_gid = !!neg_opt;
1045                         param.fp_check_gid = 1;
1046                         break;
1047                 case 'L':
1048                         ret = name2layout(&param.layout, optarg);
1049                         if (ret)
1050                                 goto err;
1051                         param.exclude_layout = !!neg_opt;
1052                         param.check_layout = 1;
1053                         break;
1054                 case 'u':
1055                 case 'U':
1056                         rc = name2id(&param.fp_uid, optarg, USER);
1057                         if (rc) {
1058                                 param.fp_uid = strtoul(optarg, &endptr, 10);
1059                                 if (*endptr != '\0') {
1060                                         fprintf(stderr, "User/UID: %s cannot "
1061                                                 "be found.\n", optarg);
1062                                         ret = -1;
1063                                         goto err;
1064                                 }
1065                         }
1066                         param.fp_exclude_uid = !!neg_opt;
1067                         param.fp_check_uid = 1;
1068                         break;
1069                 case FIND_POOL_OPT:
1070                         if (strlen(optarg) > LOV_MAXPOOLNAME) {
1071                                 fprintf(stderr,
1072                                         "Pool name %s is too long"
1073                                         " (max is %d)\n", optarg,
1074                                         LOV_MAXPOOLNAME);
1075                                 ret = -1;
1076                                 goto err;
1077                         }
1078                         /* we do check for empty pool because empty pool
1079                          * is used to find V1 lov attributes */
1080                         strncpy(param.poolname, optarg, LOV_MAXPOOLNAME);
1081                         param.poolname[LOV_MAXPOOLNAME] = '\0';
1082                         param.exclude_pool = !!neg_opt;
1083                         param.check_pool = 1;
1084                         break;
1085                 case 'n':
1086                         param.pattern = (char *)optarg;
1087                         param.exclude_pattern = !!neg_opt;
1088                         break;
1089                 case 'm':
1090                 case 'i':
1091                 case 'O': {
1092                         char *buf, *token, *next, *p;
1093                         int len = 1;
1094                         void *tmp;
1095
1096                         buf = strdup(optarg);
1097                         if (buf == NULL) {
1098                                 ret = -ENOMEM;
1099                                 goto err;
1100                         }
1101
1102                         param.exclude_obd = !!neg_opt;
1103
1104                         token = buf;
1105                         while (token && *token) {
1106                                 token = strchr(token, ',');
1107                                 if (token) {
1108                                         len++;
1109                                         token++;
1110                                 }
1111                         }
1112                         if (c == 'm') {
1113                                 param.exclude_mdt = !!neg_opt;
1114                                 param.num_alloc_mdts += len;
1115                                 tmp = realloc(param.mdtuuid,
1116                                               param.num_alloc_mdts *
1117                                               sizeof(*param.mdtuuid));
1118                                 if (tmp == NULL) {
1119                                         ret = -ENOMEM;
1120                                         goto err_free;
1121                                 }
1122
1123                                 param.mdtuuid = tmp;
1124                         } else {
1125                                 param.exclude_obd = !!neg_opt;
1126                                 param.num_alloc_obds += len;
1127                                 tmp = realloc(param.obduuid,
1128                                               param.num_alloc_obds *
1129                                               sizeof(*param.obduuid));
1130                                 if (tmp == NULL) {
1131                                         ret = -ENOMEM;
1132                                         goto err_free;
1133                                 }
1134
1135                                 param.obduuid = tmp;
1136                         }
1137                         for (token = buf; token && *token; token = next) {
1138                                 struct obd_uuid *puuid;
1139                                 if (c == 'm') {
1140                                         puuid =
1141                                           &param.mdtuuid[param.num_mdts++];
1142                                 } else {
1143                                         puuid =
1144                                           &param.obduuid[param.num_obds++];
1145                                 }
1146                                 p = strchr(token, ',');
1147                                 next = 0;
1148                                 if (p) {
1149                                         *p = 0;
1150                                         next = p+1;
1151                                 }
1152
1153                                 if (strlen(token) > sizeof(puuid->uuid) - 1) {
1154                                         ret = -E2BIG;
1155                                         goto err_free;
1156                                 }
1157
1158                                 strncpy(puuid->uuid, token,
1159                                         sizeof(puuid->uuid));
1160                         }
1161 err_free:
1162                         if (buf)
1163                                 free(buf);
1164                         break;
1165                 }
1166                 case 'p':
1167                         param.zeroend = 1;
1168                         break;
1169                 case 'P':
1170                         break;
1171                 case 's':
1172                         if (optarg[0] == '+') {
1173                                 param.size_sign = -1;
1174                                 optarg++;
1175                         } else if (optarg[0] == '-') {
1176                                 param.size_sign =  1;
1177                                 optarg++;
1178                         }
1179
1180                         ret = llapi_parse_size(optarg, &param.size,
1181                                                &param.size_units, 0);
1182                         if (ret) {
1183                                 fprintf(stderr, "error: bad file size '%s'\n",
1184                                         optarg);
1185                                 goto err;
1186                         }
1187                         param.check_size = 1;
1188                         param.exclude_size = !!neg_opt;
1189                         break;
1190                 case 'S':
1191                         if (optarg[0] == '+') {
1192                                 param.stripesize_sign = -1;
1193                                 optarg++;
1194                         } else if (optarg[0] == '-') {
1195                                 param.stripesize_sign =  1;
1196                                 optarg++;
1197                         }
1198
1199                         ret = llapi_parse_size(optarg, &param.stripesize,
1200                                                &param.stripesize_units, 0);
1201                         if (ret) {
1202                                 fprintf(stderr, "error: bad stripe_size '%s'\n",
1203                                         optarg);
1204                                 goto err;
1205                         }
1206                         param.check_stripesize = 1;
1207                         param.exclude_stripesize = !!neg_opt;
1208                         break;
1209                 case 't':
1210                         param.fp_exclude_type = !!neg_opt;
1211                         switch (optarg[0]) {
1212                         case 'b':
1213                                 param.fp_type = S_IFBLK;
1214                                 break;
1215                         case 'c':
1216                                 param.fp_type = S_IFCHR;
1217                                 break;
1218                         case 'd':
1219                                 param.fp_type = S_IFDIR;
1220                                 break;
1221                         case 'f':
1222                                 param.fp_type = S_IFREG;
1223                                 break;
1224                         case 'l':
1225                                 param.fp_type = S_IFLNK;
1226                                 break;
1227                         case 'p':
1228                                 param.fp_type = S_IFIFO;
1229                                 break;
1230                         case 's':
1231                                 param.fp_type = S_IFSOCK;
1232                                 break;
1233                         default:
1234                                 fprintf(stderr, "error: %s: bad type '%s'\n",
1235                                         argv[0], optarg);
1236                                 ret = CMD_HELP;
1237                                 goto err;
1238                         };
1239                         break;
1240                 default:
1241                         ret = CMD_HELP;
1242                         goto err;
1243                 };
1244         }
1245
1246         if (pathstart == -1) {
1247                 fprintf(stderr, "error: %s: no filename|pathname\n",
1248                         argv[0]);
1249                 ret = CMD_HELP;
1250                 goto err;
1251         } else if (pathend == -1) {
1252                 /* no options */
1253                 pathend = argc;
1254         }
1255
1256         do {
1257                 rc = llapi_find(argv[pathstart], &param);
1258                 if (rc != 0 && ret == 0)
1259                         ret = rc;
1260         } while (++pathstart < pathend);
1261
1262         if (ret)
1263                 fprintf(stderr, "error: %s failed for %s.\n",
1264                         argv[0], argv[optind - 1]);
1265 err:
1266         if (param.obduuid && param.num_alloc_obds)
1267                 free(param.obduuid);
1268
1269         if (param.mdtuuid && param.num_alloc_mdts)
1270                 free(param.mdtuuid);
1271
1272         return ret;
1273 }
1274
1275 static int lfs_getstripe_internal(int argc, char **argv,
1276                                   struct find_param *param)
1277 {
1278         struct option long_opts[] = {
1279 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1280                 /* This formerly implied "stripe-count", but was explicitly
1281                  * made "stripe-count" for consistency with other options,
1282                  * and to separate it from "mdt-count" when DNE arrives. */
1283                 {"count",               no_argument,            0, 'c'},
1284 #endif
1285                 {"stripe-count",        no_argument,            0, 'c'},
1286                 {"stripe_count",        no_argument,            0, 'c'},
1287                 {"directory",           no_argument,            0, 'd'},
1288                 {"default",             no_argument,            0, 'D'},
1289                 {"generation",          no_argument,            0, 'g'},
1290 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1291                 /* This formerly implied "stripe-index", but was explicitly
1292                  * made "stripe-index" for consistency with other options,
1293                  * and to separate it from "mdt-index" when DNE arrives. */
1294                 {"index",               no_argument,            0, 'i'},
1295 #endif
1296                 {"stripe-index",        no_argument,            0, 'i'},
1297                 {"stripe_index",        no_argument,            0, 'i'},
1298                 {"layout",              no_argument,            0, 'L'},
1299                 {"mdt-index",           no_argument,            0, 'M'},
1300                 {"mdt_index",           no_argument,            0, 'M'},
1301 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1302                 /* This formerly implied "stripe-index", but was confusing
1303                  * with "file offset" (which will eventually be needed for
1304                  * with different layouts by offset), so deprecate it. */
1305                 {"offset",              no_argument,            0, 'o'},
1306 #endif
1307                 {"obd",                 required_argument,      0, 'O'},
1308                 {"ost",                 required_argument,      0, 'O'},
1309                 {"pool",                no_argument,            0, 'p'},
1310                 {"quiet",               no_argument,            0, 'q'},
1311                 {"recursive",           no_argument,            0, 'r'},
1312                 {"raw",                 no_argument,            0, 'R'},
1313 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1314                 /* This formerly implied "--stripe-size", but was confusing
1315                  * with "lfs find --size|-s", which means "file size", so use
1316                  * the consistent "--stripe-size|-S" for all commands. */
1317                 {"size",                no_argument,            0, 's'},
1318 #endif
1319                 {"stripe-size",         no_argument,            0, 'S'},
1320                 {"stripe_size",         no_argument,            0, 'S'},
1321                 {"verbose",             no_argument,            0, 'v'},
1322                 {0, 0, 0, 0}
1323         };
1324         int c, rc;
1325
1326         param->fp_max_depth = 1;
1327         optind = 0;
1328         while ((c = getopt_long(argc, argv, "cdDghiLMoO:pqrRsSv",
1329                                 long_opts, NULL)) != -1) {
1330                 switch (c) {
1331                 case 'O':
1332                         if (param->obduuid) {
1333                                 fprintf(stderr,
1334                                         "error: %s: only one obduuid allowed",
1335                                         argv[0]);
1336                                 return CMD_HELP;
1337                         }
1338                         param->obduuid = (struct obd_uuid *)optarg;
1339                         break;
1340                 case 'q':
1341                         param->quiet++;
1342                         break;
1343                 case 'd':
1344                         param->fp_max_depth = 0;
1345                         break;
1346                 case 'D':
1347                         param->get_default_lmv = 1;
1348                         break;
1349                 case 'r':
1350                         param->recursive = 1;
1351                         break;
1352                 case 'v':
1353                         param->verbose = VERBOSE_ALL | VERBOSE_DETAIL;
1354                         break;
1355                 case 'c':
1356 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 6, 53, 0)
1357                         if (strcmp(argv[optind - 1], "--count") == 0)
1358                                 fprintf(stderr, "warning: '--count' deprecated,"
1359                                         " use '--stripe-count' instead\n");
1360 #endif
1361                         if (!(param->verbose & VERBOSE_DETAIL)) {
1362                                 param->verbose |= VERBOSE_COUNT;
1363                                 param->fp_max_depth = 0;
1364                         }
1365                         break;
1366 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1367                 case 's':
1368 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 6, 53, 0)
1369                         fprintf(stderr, "warning: '--size|-s' deprecated, "
1370                                 "use '--stripe-size|-S' instead\n");
1371 #endif
1372 #endif /* LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0) */
1373                 case 'S':
1374                         if (!(param->verbose & VERBOSE_DETAIL)) {
1375                                 param->verbose |= VERBOSE_SIZE;
1376                                 param->fp_max_depth = 0;
1377                         }
1378                         break;
1379 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1380                 case 'o':
1381                         fprintf(stderr, "warning: '--offset|-o' deprecated, "
1382                                 "use '--stripe-index|-i' instead\n");
1383 #endif
1384                 case 'i':
1385 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 6, 53, 0)
1386                         if (strcmp(argv[optind - 1], "--index") == 0)
1387                                 fprintf(stderr, "warning: '--index' deprecated"
1388                                         ", use '--stripe-index' instead\n");
1389 #endif
1390                         if (!(param->verbose & VERBOSE_DETAIL)) {
1391                                 param->verbose |= VERBOSE_OFFSET;
1392                                 param->fp_max_depth = 0;
1393                         }
1394                         break;
1395                 case 'p':
1396                         if (!(param->verbose & VERBOSE_DETAIL)) {
1397                                 param->verbose |= VERBOSE_POOL;
1398                                 param->fp_max_depth = 0;
1399                         }
1400                         break;
1401                 case 'g':
1402                         if (!(param->verbose & VERBOSE_DETAIL)) {
1403                                 param->verbose |= VERBOSE_GENERATION;
1404                                 param->fp_max_depth = 0;
1405                         }
1406                         break;
1407                 case 'L':
1408                         if (!(param->verbose & VERBOSE_DETAIL)) {
1409                                 param->verbose |= VERBOSE_LAYOUT;
1410                                 param->fp_max_depth = 0;
1411                         }
1412                         break;
1413                 case 'M':
1414                         if (!(param->verbose & VERBOSE_DETAIL))
1415                                 param->fp_max_depth = 0;
1416                         param->verbose |= VERBOSE_MDTINDEX;
1417                         break;
1418                 case 'R':
1419                         param->raw = 1;
1420                         break;
1421                 default:
1422                         return CMD_HELP;
1423                 }
1424         }
1425
1426         if (optind >= argc)
1427                 return CMD_HELP;
1428
1429         if (param->recursive)
1430                 param->fp_max_depth = -1;
1431
1432         if (!param->verbose)
1433                 param->verbose = VERBOSE_ALL;
1434         if (param->quiet)
1435                 param->verbose = VERBOSE_OBJID;
1436
1437         do {
1438                 rc = llapi_getstripe(argv[optind], param);
1439         } while (++optind < argc && !rc);
1440
1441         if (rc)
1442                 fprintf(stderr, "error: %s failed for %s.\n",
1443                         argv[0], argv[optind - 1]);
1444         return rc;
1445 }
1446
1447 static int lfs_tgts(int argc, char **argv)
1448 {
1449         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
1450         struct find_param param;
1451         int index = 0, rc=0;
1452
1453         if (argc > 2)
1454                 return CMD_HELP;
1455
1456         if (argc == 2 && !realpath(argv[1], path)) {
1457                 rc = -errno;
1458                 fprintf(stderr, "error: invalid path '%s': %s\n",
1459                         argv[1], strerror(-rc));
1460                 return rc;
1461         }
1462
1463         while (!llapi_search_mounts(path, index++, mntdir, NULL)) {
1464                 /* Check if we have a mount point */
1465                 if (mntdir[0] == '\0')
1466                         continue;
1467
1468                 memset(&param, 0, sizeof(param));
1469                 if (!strcmp(argv[0], "mdts"))
1470                         param.get_lmv = 1;
1471
1472                 rc = llapi_ostlist(mntdir, &param);
1473                 if (rc) {
1474                         fprintf(stderr, "error: %s: failed on %s\n",
1475                                 argv[0], mntdir);
1476                 }
1477                 if (path[0] != '\0')
1478                         break;
1479                 memset(mntdir, 0, PATH_MAX);
1480         }
1481
1482         return rc;
1483 }
1484
1485 static int lfs_getstripe(int argc, char **argv)
1486 {
1487         struct find_param param = { 0 };
1488         return lfs_getstripe_internal(argc, argv, &param);
1489 }
1490
1491 /* functions */
1492 static int lfs_getdirstripe(int argc, char **argv)
1493 {
1494         struct find_param param = { 0 };
1495
1496         param.get_lmv = 1;
1497         return lfs_getstripe_internal(argc, argv, &param);
1498 }
1499
1500 /* functions */
1501 static int lfs_setdirstripe(int argc, char **argv)
1502 {
1503         char                    *dname;
1504         int                     result;
1505         unsigned int            stripe_offset = -1;
1506         unsigned int            stripe_count = 1;
1507         enum lmv_hash_type      hash_type;
1508         char                    *end;
1509         int                     c;
1510         char                    *stripe_offset_opt = NULL;
1511         char                    *stripe_count_opt = NULL;
1512         char                    *stripe_hash_opt = NULL;
1513         char                    *mode_opt = NULL;
1514         int                     default_stripe = 0;
1515         mode_t                  mode = S_IRWXU | S_IRWXG | S_IRWXO;
1516         mode_t                  previous_mode = 0;
1517
1518         struct option long_opts[] = {
1519                 {"count",       required_argument, 0, 'c'},
1520                 {"index",       required_argument, 0, 'i'},
1521                 {"mode",        required_argument, 0, 'm'},
1522                 {"hash-type",   required_argument, 0, 't'},
1523                 {"default_stripe", no_argument, 0, 'D'},
1524                 {0, 0, 0, 0}
1525         };
1526
1527         optind = 0;
1528
1529         while ((c = getopt_long(argc, argv, "c:Di:m:t:", long_opts,
1530                                 NULL)) >= 0) {
1531                 switch (c) {
1532                 case 0:
1533                         /* Long options. */
1534                         break;
1535                 case 'c':
1536                         stripe_count_opt = optarg;
1537                         break;
1538                 case 'D':
1539                         default_stripe = 1;
1540                         break;
1541                 case 'i':
1542                         stripe_offset_opt = optarg;
1543                         break;
1544                 case 'm':
1545                         mode_opt = optarg;
1546                         break;
1547                 case 't':
1548                         stripe_hash_opt = optarg;
1549                         break;
1550                 default:
1551                         fprintf(stderr, "error: %s: option '%s' "
1552                                         "unrecognized\n",
1553                                         argv[0], argv[optind - 1]);
1554                         return CMD_HELP;
1555                 }
1556         }
1557
1558         if (optind == argc) {
1559                 fprintf(stderr, "error: %s: missing dirname\n",
1560                         argv[0]);
1561                 return CMD_HELP;
1562         }
1563
1564         if (stripe_offset_opt == NULL && stripe_count_opt == NULL) {
1565                 fprintf(stderr, "error: %s: missing stripe offset and count.\n",
1566                         argv[0]);
1567                 return CMD_HELP;
1568         }
1569
1570         if (stripe_offset_opt != NULL) {
1571                 /* get the stripe offset */
1572                 stripe_offset = strtoul(stripe_offset_opt, &end, 0);
1573                 if (*end != '\0') {
1574                         fprintf(stderr, "error: %s: bad stripe offset '%s'\n",
1575                                 argv[0], stripe_offset_opt);
1576                         return CMD_HELP;
1577                 }
1578         }
1579
1580         if (mode_opt != NULL) {
1581                 mode = strtoul(mode_opt, &end, 8);
1582                 if (*end != '\0') {
1583                         fprintf(stderr, "error: %s: bad mode '%s'\n",
1584                                 argv[0], mode_opt);
1585                         return CMD_HELP;
1586                 }
1587                 previous_mode = umask(0);
1588         }
1589
1590         if (stripe_hash_opt == NULL ||
1591             strcmp(stripe_hash_opt, LMV_HASH_NAME_FNV_1A_64) == 0) {
1592                 hash_type = LMV_HASH_TYPE_FNV_1A_64;
1593         } else if (strcmp(stripe_hash_opt, LMV_HASH_NAME_ALL_CHARS) == 0) {
1594                 hash_type = LMV_HASH_TYPE_ALL_CHARS;
1595         } else {
1596                 fprintf(stderr, "error: %s: bad stripe hash type '%s'\n",
1597                         argv[0], stripe_hash_opt);
1598                 return CMD_HELP;
1599         }
1600
1601         /* get the stripe count */
1602         if (stripe_count_opt != NULL) {
1603                 stripe_count = strtoul(stripe_count_opt, &end, 0);
1604                 if (*end != '\0') {
1605                         fprintf(stderr, "error: %s: bad stripe count '%s'\n",
1606                                 argv[0], stripe_count_opt);
1607                         return CMD_HELP;
1608                 }
1609         }
1610
1611         dname = argv[optind];
1612         do {
1613                 if (default_stripe == 1) {
1614                         result = llapi_dir_set_default_lmv_stripe(dname,
1615                                                     stripe_offset, stripe_count,
1616                                                     hash_type, NULL);
1617                 } else {
1618                         result = llapi_dir_create_pool(dname, mode,
1619                                                        stripe_offset,
1620                                                        stripe_count, hash_type,
1621                                                        NULL);
1622                 }
1623
1624                 if (result) {
1625                         fprintf(stderr, "error: %s: create stripe dir '%s' "
1626                                 "failed\n", argv[0], dname);
1627                         break;
1628                 }
1629                 dname = argv[++optind];
1630         } while (dname != NULL);
1631
1632         if (mode_opt != NULL)
1633                 umask(previous_mode);
1634
1635         return result;
1636 }
1637
1638 /* functions */
1639 static int lfs_rmentry(int argc, char **argv)
1640 {
1641         char *dname;
1642         int   index;
1643         int   result = 0;
1644
1645         if (argc <= 1) {
1646                 fprintf(stderr, "error: %s: missing dirname\n",
1647                         argv[0]);
1648                 return CMD_HELP;
1649         }
1650
1651         index = 1;
1652         dname = argv[index];
1653         while (dname != NULL) {
1654                 result = llapi_direntry_remove(dname);
1655                 if (result) {
1656                         fprintf(stderr, "error: %s: remove dir entry '%s' "
1657                                 "failed\n", argv[0], dname);
1658                         break;
1659                 }
1660                 dname = argv[++index];
1661         }
1662         return result;
1663 }
1664
1665 static int lfs_mv(int argc, char **argv)
1666 {
1667         struct  find_param param = {
1668                 .fp_max_depth = -1,
1669                 .mdtindex = -1,
1670         };
1671         char   *end;
1672         int     c;
1673         int     rc = 0;
1674         struct option long_opts[] = {
1675                 {"--mdt-index", required_argument, 0, 'M'},
1676                 {"verbose",     no_argument,       0, 'v'},
1677                 {0, 0, 0, 0}
1678         };
1679
1680         while ((c = getopt_long(argc, argv, "M:v", long_opts, NULL)) != -1) {
1681                 switch (c) {
1682                 case 'M': {
1683                         param.mdtindex = strtoul(optarg, &end, 0);
1684                         if (*end != '\0') {
1685                                 fprintf(stderr, "%s: invalid MDT index'%s'\n",
1686                                         argv[0], optarg);
1687                                 return CMD_HELP;
1688                         }
1689                         break;
1690                 }
1691                 case 'v': {
1692                         param.verbose = VERBOSE_DETAIL;
1693                         break;
1694                 }
1695                 default:
1696                         fprintf(stderr, "error: %s: unrecognized option '%s'\n",
1697                                 argv[0], argv[optind - 1]);
1698                         return CMD_HELP;
1699                 }
1700         }
1701
1702         if (param.mdtindex == -1) {
1703                 fprintf(stderr, "%s MDT index must be indicated\n", argv[0]);
1704                 return CMD_HELP;
1705         }
1706
1707         if (optind >= argc) {
1708                 fprintf(stderr, "%s missing operand path\n", argv[0]);
1709                 return CMD_HELP;
1710         }
1711
1712         param.migrate = 1;
1713         rc = llapi_mv(argv[optind], &param);
1714         if (rc != 0)
1715                 fprintf(stderr, "cannot migrate '%s' to MDT%04x: %s\n",
1716                         argv[optind], param.mdtindex, strerror(-rc));
1717         return rc;
1718 }
1719
1720 static int lfs_osts(int argc, char **argv)
1721 {
1722         return lfs_tgts(argc, argv);
1723 }
1724
1725 static int lfs_mdts(int argc, char **argv)
1726 {
1727         return lfs_tgts(argc, argv);
1728 }
1729
1730 #define COOK(value)                                                     \
1731 ({                                                                      \
1732         int radix = 0;                                                  \
1733         while (value > 1024) {                                          \
1734                 value /= 1024;                                          \
1735                 radix++;                                                \
1736         }                                                               \
1737         radix;                                                          \
1738 })
1739 #define UUF     "%-20s"
1740 #define CSF     "%11s"
1741 #define CDF     "%11llu"
1742 #define HDF     "%8.1f%c"
1743 #define RSF     "%4s"
1744 #define RDF     "%3d%%"
1745
1746 static int showdf(char *mntdir, struct obd_statfs *stat,
1747                   char *uuid, int ishow, int cooked,
1748                   char *type, int index, int rc)
1749 {
1750         long long avail, used, total;
1751         double ratio = 0;
1752         char *suffix = "KMGTPEZY";
1753         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
1754         char tbuf[3 * sizeof(__u64)];
1755         char ubuf[3 * sizeof(__u64)];
1756         char abuf[3 * sizeof(__u64)];
1757         char rbuf[3 * sizeof(__u64)];
1758
1759         if (!uuid || !stat)
1760                 return -EINVAL;
1761
1762         switch (rc) {
1763         case 0:
1764                 if (ishow) {
1765                         avail = stat->os_ffree;
1766                         used = stat->os_files - stat->os_ffree;
1767                         total = stat->os_files;
1768                 } else {
1769                         int shift = cooked ? 0 : 10;
1770
1771                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
1772                         used  = ((stat->os_blocks - stat->os_bfree) *
1773                                  stat->os_bsize) >> shift;
1774                         total = (stat->os_blocks * stat->os_bsize) >> shift;
1775                 }
1776
1777                 if ((used + avail) > 0)
1778                         ratio = (double)used / (double)(used + avail);
1779
1780                 if (cooked) {
1781                         int i;
1782                         double cook_val;
1783
1784                         cook_val = (double)total;
1785                         i = COOK(cook_val);
1786                         if (i > 0)
1787                                 sprintf(tbuf, HDF, cook_val, suffix[i - 1]);
1788                         else
1789                                 sprintf(tbuf, CDF, total);
1790
1791                         cook_val = (double)used;
1792                         i = COOK(cook_val);
1793                         if (i > 0)
1794                                 sprintf(ubuf, HDF, cook_val, suffix[i - 1]);
1795                         else
1796                                 sprintf(ubuf, CDF, used);
1797
1798                         cook_val = (double)avail;
1799                         i = COOK(cook_val);
1800                         if (i > 0)
1801                                 sprintf(abuf, HDF, cook_val, suffix[i - 1]);
1802                         else
1803                                 sprintf(abuf, CDF, avail);
1804                 } else {
1805                         sprintf(tbuf, CDF, total);
1806                         sprintf(ubuf, CDF, used);
1807                         sprintf(abuf, CDF, avail);
1808                 }
1809
1810                 sprintf(rbuf, RDF, (int)(ratio * 100 + 0.5));
1811                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
1812                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
1813                 if (type)
1814                         printf("[%s:%d]\n", type, index);
1815                 else
1816                         printf("\n");
1817
1818                 break;
1819         case -ENODATA:
1820                 printf(UUF": inactive device\n", uuid);
1821                 break;
1822         default:
1823                 printf(UUF": %s\n", uuid, strerror(-rc));
1824                 break;
1825         }
1826
1827         return 0;
1828 }
1829
1830 struct ll_stat_type {
1831         int   st_op;
1832         char *st_name;
1833 };
1834
1835 static int mntdf(char *mntdir, char *fsname, char *pool, int ishow,
1836                 int cooked, int lazy)
1837 {
1838         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
1839         struct obd_uuid uuid_buf;
1840         char *poolname = NULL;
1841         struct ll_stat_type types[] = { { LL_STATFS_LMV, "MDT" },
1842                                         { LL_STATFS_LOV, "OST" },
1843                                         { 0, NULL } };
1844         struct ll_stat_type *tp;
1845         __u64 ost_ffree = 0;
1846         __u32 index;
1847         __u32 type;
1848         int rc;
1849
1850         if (pool) {
1851                 poolname = strchr(pool, '.');
1852                 if (poolname != NULL) {
1853                         if (strncmp(fsname, pool, strlen(fsname))) {
1854                                 fprintf(stderr, "filesystem name incorrect\n");
1855                                 return -ENODEV;
1856                         }
1857                         poolname++;
1858                 } else
1859                         poolname = pool;
1860         }
1861
1862         if (ishow)
1863                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
1864                        "UUID", "Inodes", "IUsed", "IFree",
1865                        "IUse%", "Mounted on");
1866         else
1867                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
1868                        "UUID", cooked ? "bytes" : "1K-blocks",
1869                        "Used", "Available", "Use%", "Mounted on");
1870
1871         for (tp = types; tp->st_name != NULL; tp++) {
1872                 for (index = 0; ; index++) {
1873                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
1874                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
1875                         type = lazy ? tp->st_op | LL_STATFS_NODELAY : tp->st_op;
1876                         rc = llapi_obd_statfs(mntdir, type, index,
1877                                               &stat_buf, &uuid_buf);
1878                         if (rc == -ENODEV)
1879                                 break;
1880
1881                         if (poolname && tp->st_op == LL_STATFS_LOV &&
1882                             llapi_search_ost(fsname, poolname,
1883                                              obd_uuid2str(&uuid_buf)) != 1)
1884                                 continue;
1885
1886                         /* the llapi_obd_statfs() call may have returned with
1887                          * an error, but if it filled in uuid_buf we will at
1888                          * lease use that to print out a message for that OBD.
1889                          * If we didn't get anything in the uuid_buf, then fill
1890                          * it in so that we can print an error message. */
1891                         if (uuid_buf.uuid[0] == '\0')
1892                                 sprintf(uuid_buf.uuid, "%s%04x",
1893                                         tp->st_name, index);
1894                         showdf(mntdir, &stat_buf, obd_uuid2str(&uuid_buf),
1895                                ishow, cooked, tp->st_name, index, rc);
1896
1897                         if (rc == 0) {
1898                                 if (tp->st_op == LL_STATFS_LMV) {
1899                                         sum.os_ffree += stat_buf.os_ffree;
1900                                         sum.os_files += stat_buf.os_files;
1901                                 } else /* if (tp->st_op == LL_STATFS_LOV) */ {
1902                                         sum.os_blocks += stat_buf.os_blocks *
1903                                                 stat_buf.os_bsize;
1904                                         sum.os_bfree  += stat_buf.os_bfree *
1905                                                 stat_buf.os_bsize;
1906                                         sum.os_bavail += stat_buf.os_bavail *
1907                                                 stat_buf.os_bsize;
1908                                         ost_ffree += stat_buf.os_ffree;
1909                                 }
1910                         } else if (rc == -EINVAL || rc == -EFAULT) {
1911                                 break;
1912                         }
1913                 }
1914         }
1915
1916         /* If we don't have as many objects free on the OST as inodes
1917          * on the MDS, we reduce the total number of inodes to
1918          * compensate, so that the "inodes in use" number is correct.
1919          * Matches ll_statfs_internal() so the results are consistent. */
1920         if (ost_ffree < sum.os_ffree) {
1921                 sum.os_files = (sum.os_files - sum.os_ffree) + ost_ffree;
1922                 sum.os_ffree = ost_ffree;
1923         }
1924         printf("\n");
1925         showdf(mntdir, &sum, "filesystem summary:", ishow, cooked, NULL, 0, 0);
1926         printf("\n");
1927         return 0;
1928 }
1929
1930 static int lfs_df(int argc, char **argv)
1931 {
1932         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
1933         int ishow = 0, cooked = 0;
1934         int lazy = 0;
1935         int c, rc = 0, index = 0;
1936         char fsname[PATH_MAX] = "", *pool_name = NULL;
1937         struct option long_opts[] = {
1938                 {"pool", required_argument, 0, 'p'},
1939                 {"lazy", 0, 0, 'l'},
1940                 {0, 0, 0, 0}
1941         };
1942
1943         optind = 0;
1944         while ((c = getopt_long(argc, argv, "hilp:", long_opts, NULL)) != -1) {
1945                 switch (c) {
1946                 case 'i':
1947                         ishow = 1;
1948                         break;
1949                 case 'h':
1950                         cooked = 1;
1951                         break;
1952                 case 'l':
1953                         lazy = 1;
1954                         break;
1955                 case 'p':
1956                         pool_name = optarg;
1957                         break;
1958                 default:
1959                         return CMD_HELP;
1960                 }
1961         }
1962         if (optind < argc && !realpath(argv[optind], path)) {
1963                 rc = -errno;
1964                 fprintf(stderr, "error: invalid path '%s': %s\n",
1965                         argv[optind], strerror(-rc));
1966                 return rc;
1967         }
1968
1969         while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
1970                 /* Check if we have a mount point */
1971                 if (mntdir[0] == '\0')
1972                         continue;
1973
1974                 rc = mntdf(mntdir, fsname, pool_name, ishow, cooked, lazy);
1975                 if (rc || path[0] != '\0')
1976                         break;
1977                 fsname[0] = '\0'; /* avoid matching in next loop */
1978                 mntdir[0] = '\0'; /* avoid matching in next loop */
1979         }
1980
1981         return rc;
1982 }
1983
1984 static int lfs_getname(int argc, char **argv)
1985 {
1986         char mntdir[PATH_MAX] = "", path[PATH_MAX] = "", fsname[PATH_MAX] = "";
1987         int rc = 0, index = 0, c;
1988         char buf[sizeof(struct obd_uuid)];
1989
1990         optind = 0;
1991         while ((c = getopt(argc, argv, "h")) != -1)
1992                 return CMD_HELP;
1993
1994         if (optind == argc) { /* no paths specified, get all paths. */
1995                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
1996                         rc = llapi_getname(mntdir, buf, sizeof(buf));
1997                         if (rc < 0) {
1998                                 fprintf(stderr,
1999                                         "cannot get name for `%s': %s\n",
2000                                         mntdir, strerror(-rc));
2001                                 break;
2002                         }
2003
2004                         printf("%s %s\n", buf, mntdir);
2005
2006                         path[0] = fsname[0] = mntdir[0] = 0;
2007                 }
2008         } else { /* paths specified, only attempt to search these. */
2009                 for (; optind < argc; optind++) {
2010                         rc = llapi_getname(argv[optind], buf, sizeof(buf));
2011                         if (rc < 0) {
2012                                 fprintf(stderr,
2013                                         "cannot get name for `%s': %s\n",
2014                                         argv[optind], strerror(-rc));
2015                                 break;
2016                         }
2017
2018                         printf("%s %s\n", buf, argv[optind]);
2019                 }
2020         }
2021         return rc;
2022 }
2023
2024 static int lfs_check(int argc, char **argv)
2025 {
2026         int rc;
2027         char mntdir[PATH_MAX] = {'\0'};
2028         int num_types = 1;
2029         char *obd_types[2];
2030         char obd_type1[4];
2031         char obd_type2[4];
2032
2033         if (argc != 2)
2034                 return CMD_HELP;
2035
2036         obd_types[0] = obd_type1;
2037         obd_types[1] = obd_type2;
2038
2039         if (strcmp(argv[1], "osts") == 0) {
2040                 strcpy(obd_types[0], "osc");
2041         } else if (strcmp(argv[1], "mds") == 0) {
2042                 strcpy(obd_types[0], "mdc");
2043         } else if (strcmp(argv[1], "servers") == 0) {
2044                 num_types = 2;
2045                 strcpy(obd_types[0], "osc");
2046                 strcpy(obd_types[1], "mdc");
2047         } else {
2048                 fprintf(stderr, "error: %s: option '%s' unrecognized\n",
2049                                 argv[0], argv[1]);
2050                         return CMD_HELP;
2051         }
2052
2053         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
2054         if (rc < 0 || mntdir[0] == '\0') {
2055                 fprintf(stderr, "No suitable Lustre mount found\n");
2056                 return rc;
2057         }
2058
2059         rc = llapi_target_check(num_types, obd_types, mntdir);
2060         if (rc)
2061                 fprintf(stderr, "error: %s: %s status failed\n",
2062                                 argv[0],argv[1]);
2063
2064         return rc;
2065
2066 }
2067
2068 static int lfs_join(int argc, char **argv)
2069 {
2070         fprintf(stderr, "join two lustre files into one.\n"
2071                         "obsolete, HEAD does not support it anymore.\n");
2072         return 0;
2073 }
2074
2075 #ifdef HAVE_SYS_QUOTA_H
2076 static int lfs_quotacheck(int argc, char **argv)
2077 {
2078         int c, check_type = 0;
2079         char *mnt;
2080         struct if_quotacheck qchk;
2081         struct if_quotactl qctl;
2082         char *obd_type = (char *)qchk.obd_type;
2083         int rc;
2084
2085         memset(&qchk, 0, sizeof(qchk));
2086
2087         optind = 0;
2088         while ((c = getopt(argc, argv, "gu")) != -1) {
2089                 switch (c) {
2090                 case 'u':
2091                         check_type |= 0x01;
2092                         break;
2093                 case 'g':
2094                         check_type |= 0x02;
2095                         break;
2096                 default:
2097                         fprintf(stderr, "error: %s: option '-%c' "
2098                                         "unrecognized\n", argv[0], c);
2099                         return CMD_HELP;
2100                 }
2101         }
2102
2103         if (check_type)
2104                 check_type--;
2105         else    /* do quotacheck for both user & group quota by default */
2106                 check_type = 0x02;
2107
2108         if (argc == optind)
2109                 return CMD_HELP;
2110
2111         mnt = argv[optind];
2112
2113         rc = llapi_quotacheck(mnt, check_type);
2114         if (rc == -EOPNOTSUPP) {
2115                 fprintf(stderr, "error: quotacheck not supported by the quota "
2116                         "master.\nPlease note that quotacheck is deprecated as "
2117                         "of lustre 2.4.0 since space accounting is always "
2118                         "enabled.\nFilesystems not formatted with 2.4 utils or "
2119                         "beyond can be upgraded with tunefs.lustre --quota.\n");
2120                 return rc;
2121         } else if (rc) {
2122                 fprintf(stderr, "quotacheck failed: %s\n", strerror(-rc));
2123                 return rc;
2124         }
2125
2126         rc = llapi_poll_quotacheck(mnt, &qchk);
2127         if (rc) {
2128                 if (*obd_type)
2129                         fprintf(stderr, "%s %s ", obd_type,
2130                                 obd_uuid2str(&qchk.obd_uuid));
2131                 fprintf(stderr, "quota check failed: %s\n", strerror(-rc));
2132                 return rc;
2133         }
2134
2135         memset(&qctl, 0, sizeof(qctl));
2136         qctl.qc_cmd = LUSTRE_Q_QUOTAON;
2137         qctl.qc_type = check_type;
2138         rc = llapi_quotactl(mnt, &qctl);
2139         if (rc && rc != -EALREADY) {
2140                 if (*obd_type)
2141                         fprintf(stderr, "%s %s ", (char *)qctl.obd_type,
2142                                 obd_uuid2str(&qctl.obd_uuid));
2143                 fprintf(stderr, "%s turn on quota failed: %s\n",
2144                         argv[0], strerror(-rc));
2145                 return rc;
2146         }
2147
2148         return 0;
2149 }
2150
2151 static int lfs_quotaon(int argc, char **argv)
2152 {
2153         int c;
2154         char *mnt;
2155         struct if_quotactl qctl;
2156         char *obd_type = (char *)qctl.obd_type;
2157         int rc;
2158
2159         memset(&qctl, 0, sizeof(qctl));
2160         qctl.qc_cmd = LUSTRE_Q_QUOTAON;
2161
2162         optind = 0;
2163         while ((c = getopt(argc, argv, "fgu")) != -1) {
2164                 switch (c) {
2165                 case 'u':
2166                         qctl.qc_type |= 0x01;
2167                         break;
2168                 case 'g':
2169                         qctl.qc_type |= 0x02;
2170                         break;
2171                 case 'f':
2172                         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
2173                         break;
2174                 default:
2175                         fprintf(stderr, "error: %s: option '-%c' "
2176                                         "unrecognized\n", argv[0], c);
2177                         return CMD_HELP;
2178                 }
2179         }
2180
2181         if (qctl.qc_type)
2182                 qctl.qc_type--;
2183         else /* by default, enable quota for both user & group */
2184                 qctl.qc_type = 0x02;
2185
2186         if (argc == optind)
2187                 return CMD_HELP;
2188
2189         mnt = argv[optind];
2190
2191         rc = llapi_quotactl(mnt, &qctl);
2192         if (rc) {
2193                 if (rc == -EOPNOTSUPP) {
2194                         fprintf(stderr, "error: quotaon not supported by the "
2195                                 "quota master.\nPlease note that quotaon/off is"
2196                                 " deprecated as of lustre 2.4.0.\nQuota "
2197                                 "enforcement should now be enabled on the MGS "
2198                                 "via:\nmgs# lctl conf_param ${FSNAME}.quota."
2199                                 "<ost|mdt>=<u|g|ug>\n(ost for block quota, mdt "
2200                                 "for inode quota, u for user and g for group"
2201                                 "\n");
2202                 } else if (rc == -EALREADY) {
2203                         rc = 0;
2204                 } else if (rc == -ENOENT) {
2205                         fprintf(stderr, "error: cannot find quota database, "
2206                                         "make sure you have run quotacheck\n");
2207                 } else {
2208                         if (*obd_type)
2209                                 fprintf(stderr, "%s %s ", obd_type,
2210                                         obd_uuid2str(&qctl.obd_uuid));
2211                         fprintf(stderr, "%s failed: %s\n", argv[0],
2212                                 strerror(-rc));
2213                 }
2214         }
2215
2216         return rc;
2217 }
2218
2219 static int lfs_quotaoff(int argc, char **argv)
2220 {
2221         int c;
2222         char *mnt;
2223         struct if_quotactl qctl;
2224         char *obd_type = (char *)qctl.obd_type;
2225         int rc;
2226
2227         memset(&qctl, 0, sizeof(qctl));
2228         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
2229
2230         optind = 0;
2231         while ((c = getopt(argc, argv, "gu")) != -1) {
2232                 switch (c) {
2233                 case 'u':
2234                         qctl.qc_type |= 0x01;
2235                         break;
2236                 case 'g':
2237                         qctl.qc_type |= 0x02;
2238                         break;
2239                 default:
2240                         fprintf(stderr, "error: %s: option '-%c' "
2241                                         "unrecognized\n", argv[0], c);
2242                         return CMD_HELP;
2243                 }
2244         }
2245
2246         if (qctl.qc_type)
2247                 qctl.qc_type--;
2248         else /* by default, disable quota for both user & group */
2249                 qctl.qc_type = 0x02;
2250
2251         if (argc == optind)
2252                 return CMD_HELP;
2253
2254         mnt = argv[optind];
2255
2256         rc = llapi_quotactl(mnt, &qctl);
2257         if (rc) {
2258                 if (rc == -EOPNOTSUPP) {
2259                         fprintf(stderr, "error: quotaoff not supported by the "
2260                                 "quota master.\nPlease note that quotaon/off is"
2261                                 " deprecated as of lustre 2.4.0.\nQuota "
2262                                 "enforcement can be disabled on the MGS via:\n"
2263                                 "mgs# lctl conf_param ${FSNAME}.quota.<ost|mdt>"
2264                                 "=\"\"\n");
2265                 } else if (rc == -EALREADY) {
2266                         rc = 0;
2267                 } else {
2268                         if (*obd_type)
2269                                 fprintf(stderr, "%s %s ", obd_type,
2270                                         obd_uuid2str(&qctl.obd_uuid));
2271                         fprintf(stderr, "quotaoff failed: %s\n",
2272                                 strerror(-rc));
2273                 }
2274         }
2275
2276         return rc;
2277 }
2278
2279 #define ARG2INT(nr, str, msg)                                           \
2280 do {                                                                    \
2281         char *endp;                                                     \
2282         nr = strtol(str, &endp, 0);                                     \
2283         if (*endp) {                                                    \
2284                 fprintf(stderr, "error: bad %s: %s\n", msg, str);       \
2285                 return CMD_HELP;                                        \
2286         }                                                               \
2287 } while (0)
2288
2289 #define ADD_OVERFLOW(a,b) ((a + b) < a) ? (a = ULONG_MAX) : (a = a + b)
2290
2291 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
2292  * returns the value or ULONG_MAX on integer overflow or incorrect format
2293  * Notes:
2294  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
2295  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
2296  *        3. empty integer value is interpreted as 0
2297  */
2298 static unsigned long str2sec(const char* timestr)
2299 {
2300         const char spec[] = "smhdw";
2301         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
2302         unsigned long val = 0;
2303         char *tail;
2304
2305         if (strpbrk(timestr, spec) == NULL) {
2306                 /* no specifiers inside the time string,
2307                    should treat it as an integer value */
2308                 val = strtoul(timestr, &tail, 10);
2309                 return *tail ? ULONG_MAX : val;
2310         }
2311
2312         /* format string is XXwXXdXXhXXmXXs */
2313         while (*timestr) {
2314                 unsigned long v;
2315                 int ind;
2316                 char* ptr;
2317
2318                 v = strtoul(timestr, &tail, 10);
2319                 if (v == ULONG_MAX || *tail == '\0')
2320                         /* value too large (ULONG_MAX or more)
2321                            or missing specifier */
2322                         goto error;
2323
2324                 ptr = strchr(spec, *tail);
2325                 if (ptr == NULL)
2326                         /* unknown specifier */
2327                         goto error;
2328
2329                 ind = ptr - spec;
2330
2331                 /* check if product will overflow the type */
2332                 if (!(v < ULONG_MAX / mult[ind]))
2333                         goto error;
2334
2335                 ADD_OVERFLOW(val, mult[ind] * v);
2336                 if (val == ULONG_MAX)
2337                         goto error;
2338
2339                 timestr = tail + 1;
2340         }
2341
2342         return val;
2343
2344 error:
2345         return ULONG_MAX;
2346 }
2347
2348 #define ARG2ULL(nr, str, def_units)                                     \
2349 do {                                                                    \
2350         unsigned long long limit, units = def_units;                    \
2351         int rc;                                                         \
2352                                                                         \
2353         rc = llapi_parse_size(str, &limit, &units, 1);                  \
2354         if (rc < 0) {                                                   \
2355                 fprintf(stderr, "error: bad limit value %s\n", str);    \
2356                 return CMD_HELP;                                        \
2357         }                                                               \
2358         nr = limit;                                                     \
2359 } while (0)
2360
2361 static inline int has_times_option(int argc, char **argv)
2362 {
2363         int i;
2364
2365         for (i = 1; i < argc; i++)
2366                 if (!strcmp(argv[i], "-t"))
2367                         return 1;
2368
2369         return 0;
2370 }
2371
2372 int lfs_setquota_times(int argc, char **argv)
2373 {
2374         int c, rc;
2375         struct if_quotactl qctl;
2376         char *mnt, *obd_type = (char *)qctl.obd_type;
2377         struct obd_dqblk *dqb = &qctl.qc_dqblk;
2378         struct obd_dqinfo *dqi = &qctl.qc_dqinfo;
2379         struct option long_opts[] = {
2380                 {"block-grace",     required_argument, 0, 'b'},
2381                 {"group",           no_argument,       0, 'g'},
2382                 {"inode-grace",     required_argument, 0, 'i'},
2383                 {"times",           no_argument,       0, 't'},
2384                 {"user",            no_argument,       0, 'u'},
2385                 {0, 0, 0, 0}
2386         };
2387
2388         memset(&qctl, 0, sizeof(qctl));
2389         qctl.qc_cmd  = LUSTRE_Q_SETINFO;
2390         qctl.qc_type = UGQUOTA;
2391
2392         optind = 0;
2393         while ((c = getopt_long(argc, argv, "b:gi:tu", long_opts, NULL)) != -1) {
2394                 switch (c) {
2395                 case 'u':
2396                 case 'g':
2397                         if (qctl.qc_type != UGQUOTA) {
2398                                 fprintf(stderr, "error: -u and -g can't be used "
2399                                                 "more than once\n");
2400                                 return CMD_HELP;
2401                         }
2402                         qctl.qc_type = (c == 'u') ? USRQUOTA : GRPQUOTA;
2403                         break;
2404                 case 'b':
2405                         if ((dqi->dqi_bgrace = str2sec(optarg)) == ULONG_MAX) {
2406                                 fprintf(stderr, "error: bad block-grace: %s\n",
2407                                         optarg);
2408                                 return CMD_HELP;
2409                         }
2410                         dqb->dqb_valid |= QIF_BTIME;
2411                         break;
2412                 case 'i':
2413                         if ((dqi->dqi_igrace = str2sec(optarg)) == ULONG_MAX) {
2414                                 fprintf(stderr, "error: bad inode-grace: %s\n",
2415                                         optarg);
2416                                 return CMD_HELP;
2417                         }
2418                         dqb->dqb_valid |= QIF_ITIME;
2419                         break;
2420                 case 't': /* Yes, of course! */
2421                         break;
2422                 default: /* getopt prints error message for us when opterr != 0 */
2423                         return CMD_HELP;
2424                 }
2425         }
2426
2427         if (qctl.qc_type == UGQUOTA) {
2428                 fprintf(stderr, "error: neither -u nor -g specified\n");
2429                 return CMD_HELP;
2430         }
2431
2432         if (optind != argc - 1) {
2433                 fprintf(stderr, "error: unexpected parameters encountered\n");
2434                 return CMD_HELP;
2435         }
2436
2437         mnt = argv[optind];
2438         rc = llapi_quotactl(mnt, &qctl);
2439         if (rc) {
2440                 if (*obd_type)
2441                         fprintf(stderr, "%s %s ", obd_type,
2442                                 obd_uuid2str(&qctl.obd_uuid));
2443                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
2444                 return rc;
2445         }
2446
2447         return 0;
2448 }
2449
2450 #define BSLIMIT (1 << 0)
2451 #define BHLIMIT (1 << 1)
2452 #define ISLIMIT (1 << 2)
2453 #define IHLIMIT (1 << 3)
2454
2455 int lfs_setquota(int argc, char **argv)
2456 {
2457         int c, rc;
2458         struct if_quotactl qctl;
2459         char *mnt, *obd_type = (char *)qctl.obd_type;
2460         struct obd_dqblk *dqb = &qctl.qc_dqblk;
2461         struct option long_opts[] = {
2462                 {"block-softlimit", required_argument, 0, 'b'},
2463                 {"block-hardlimit", required_argument, 0, 'B'},
2464                 {"group",           required_argument, 0, 'g'},
2465                 {"inode-softlimit", required_argument, 0, 'i'},
2466                 {"inode-hardlimit", required_argument, 0, 'I'},
2467                 {"user",            required_argument, 0, 'u'},
2468                 {0, 0, 0, 0}
2469         };
2470         unsigned limit_mask = 0;
2471         char *endptr;
2472
2473         if (has_times_option(argc, argv))
2474                 return lfs_setquota_times(argc, argv);
2475
2476         memset(&qctl, 0, sizeof(qctl));
2477         qctl.qc_cmd  = LUSTRE_Q_SETQUOTA;
2478         qctl.qc_type = UGQUOTA; /* UGQUOTA makes no sense for setquota,
2479                                  * so it can be used as a marker that qc_type
2480                                  * isn't reinitialized from command line */
2481
2482         optind = 0;
2483         while ((c = getopt_long(argc, argv, "b:B:g:i:I:u:", long_opts, NULL)) != -1) {
2484                 switch (c) {
2485                 case 'u':
2486                 case 'g':
2487                         if (qctl.qc_type != UGQUOTA) {
2488                                 fprintf(stderr, "error: -u and -g can't be used"
2489                                                 " more than once\n");
2490                                 return CMD_HELP;
2491                         }
2492                         qctl.qc_type = (c == 'u') ? USRQUOTA : GRPQUOTA;
2493                         rc = name2id(&qctl.qc_id, optarg,
2494                                      (qctl.qc_type == USRQUOTA) ? USER : GROUP);
2495                         if (rc) {
2496                                 qctl.qc_id = strtoul(optarg, &endptr, 10);
2497                                 if (*endptr != '\0') {
2498                                         fprintf(stderr, "error: can't find id "
2499                                                 "for name %s\n", optarg);
2500                                         return CMD_HELP;
2501                                 }
2502                         }
2503                         break;
2504                 case 'b':
2505                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
2506                         dqb->dqb_bsoftlimit >>= 10;
2507                         limit_mask |= BSLIMIT;
2508                         if (dqb->dqb_bsoftlimit &&
2509                             dqb->dqb_bsoftlimit <= 1024) /* <= 1M? */
2510                                 fprintf(stderr, "warning: block softlimit is "
2511                                         "smaller than the miminal qunit size, "
2512                                         "please see the help of setquota or "
2513                                         "Lustre manual for details.\n");
2514                         break;
2515                 case 'B':
2516                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
2517                         dqb->dqb_bhardlimit >>= 10;
2518                         limit_mask |= BHLIMIT;
2519                         if (dqb->dqb_bhardlimit &&
2520                             dqb->dqb_bhardlimit <= 1024) /* <= 1M? */
2521                                 fprintf(stderr, "warning: block hardlimit is "
2522                                         "smaller than the miminal qunit size, "
2523                                         "please see the help of setquota or "
2524                                         "Lustre manual for details.\n");
2525                         break;
2526                 case 'i':
2527                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
2528                         limit_mask |= ISLIMIT;
2529                         if (dqb->dqb_isoftlimit &&
2530                             dqb->dqb_isoftlimit <= 1024) /* <= 1K inodes? */
2531                                 fprintf(stderr, "warning: inode softlimit is "
2532                                         "smaller than the miminal qunit size, "
2533                                         "please see the help of setquota or "
2534                                         "Lustre manual for details.\n");
2535                         break;
2536                 case 'I':
2537                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
2538                         limit_mask |= IHLIMIT;
2539                         if (dqb->dqb_ihardlimit &&
2540                             dqb->dqb_ihardlimit <= 1024) /* <= 1K inodes? */
2541                                 fprintf(stderr, "warning: inode hardlimit is "
2542                                         "smaller than the miminal qunit size, "
2543                                         "please see the help of setquota or "
2544                                         "Lustre manual for details.\n");
2545                         break;
2546                 default: /* getopt prints error message for us when opterr != 0 */
2547                         return CMD_HELP;
2548                 }
2549         }
2550
2551         if (qctl.qc_type == UGQUOTA) {
2552                 fprintf(stderr, "error: neither -u nor -g was specified\n");
2553                 return CMD_HELP;
2554         }
2555
2556         if (limit_mask == 0) {
2557                 fprintf(stderr, "error: at least one limit must be specified\n");
2558                 return CMD_HELP;
2559         }
2560
2561         if (optind != argc - 1) {
2562                 fprintf(stderr, "error: unexpected parameters encountered\n");
2563                 return CMD_HELP;
2564         }
2565
2566         mnt = argv[optind];
2567
2568         if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
2569             (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
2570                 /* sigh, we can't just set blimits/ilimits */
2571                 struct if_quotactl tmp_qctl = {.qc_cmd  = LUSTRE_Q_GETQUOTA,
2572                                                .qc_type = qctl.qc_type,
2573                                                .qc_id   = qctl.qc_id};
2574
2575                 rc = llapi_quotactl(mnt, &tmp_qctl);
2576                 if (rc < 0) {
2577                         fprintf(stderr, "error: setquota failed while retrieving"
2578                                         " current quota settings (%s)\n",
2579                                         strerror(-rc));
2580                         return rc;
2581                 }
2582
2583                 if (!(limit_mask & BHLIMIT))
2584                         dqb->dqb_bhardlimit = tmp_qctl.qc_dqblk.dqb_bhardlimit;
2585                 if (!(limit_mask & BSLIMIT))
2586                         dqb->dqb_bsoftlimit = tmp_qctl.qc_dqblk.dqb_bsoftlimit;
2587                 if (!(limit_mask & IHLIMIT))
2588                         dqb->dqb_ihardlimit = tmp_qctl.qc_dqblk.dqb_ihardlimit;
2589                 if (!(limit_mask & ISLIMIT))
2590                         dqb->dqb_isoftlimit = tmp_qctl.qc_dqblk.dqb_isoftlimit;
2591
2592                 /* Keep grace times if we have got no softlimit arguments */
2593                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
2594                         dqb->dqb_valid |= QIF_BTIME;
2595                         dqb->dqb_btime = tmp_qctl.qc_dqblk.dqb_btime;
2596                 }
2597
2598                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
2599                         dqb->dqb_valid |= QIF_ITIME;
2600                         dqb->dqb_itime = tmp_qctl.qc_dqblk.dqb_itime;
2601                 }
2602         }
2603
2604         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
2605         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
2606
2607         rc = llapi_quotactl(mnt, &qctl);
2608         if (rc) {
2609                 if (*obd_type)
2610                         fprintf(stderr, "%s %s ", obd_type,
2611                                 obd_uuid2str(&qctl.obd_uuid));
2612                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
2613                 return rc;
2614         }
2615
2616         return 0;
2617 }
2618
2619 static inline char *type2name(int check_type)
2620 {
2621         if (check_type == USRQUOTA)
2622                 return "user";
2623         else if (check_type == GRPQUOTA)
2624                 return "group";
2625         else
2626                 return "unknown";
2627 }
2628
2629 /* Converts seconds value into format string
2630  * result is returned in buf
2631  * Notes:
2632  *        1. result is in descenting order: 1w2d3h4m5s
2633  *        2. zero fields are not filled (except for p. 3): 5d1s
2634  *        3. zero seconds value is presented as "0s"
2635  */
2636 static char * __sec2str(time_t seconds, char *buf)
2637 {
2638         const char spec[] = "smhdw";
2639         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
2640         unsigned long c;
2641         char *tail = buf;
2642         int i;
2643
2644         for (i = sizeof(mult) / sizeof(mult[0]) - 1 ; i >= 0; i--) {
2645                 c = seconds / mult[i];
2646
2647                 if (c > 0 || (i == 0 && buf == tail))
2648                         tail += snprintf(tail, 40-(tail-buf), "%lu%c", c, spec[i]);
2649
2650                 seconds %= mult[i];
2651         }
2652
2653         return tail;
2654 }
2655
2656 static void sec2str(time_t seconds, char *buf, int rc)
2657 {
2658         char *tail = buf;
2659
2660         if (rc)
2661                 *tail++ = '[';
2662
2663         tail = __sec2str(seconds, tail);
2664
2665         if (rc && tail - buf < 39) {
2666                 *tail++ = ']';
2667                 *tail++ = 0;
2668         }
2669 }
2670
2671 static void diff2str(time_t seconds, char *buf, time_t now)
2672 {
2673
2674         buf[0] = 0;
2675         if (!seconds)
2676                 return;
2677         if (seconds <= now) {
2678                 strcpy(buf, "none");
2679                 return;
2680         }
2681         __sec2str(seconds - now, buf);
2682 }
2683
2684 static void print_quota_title(char *name, struct if_quotactl *qctl,
2685                               bool human_readable)
2686 {
2687         printf("Disk quotas for %s %s (%cid %u):\n",
2688                type2name(qctl->qc_type), name,
2689                *type2name(qctl->qc_type), qctl->qc_id);
2690         printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
2691                "Filesystem", human_readable ? "used" : "kbytes",
2692                "quota", "limit", "grace",
2693                "files", "quota", "limit", "grace");
2694 }
2695
2696 static void kbytes2str(__u64 num, char *buf, bool h)
2697 {
2698         if (!h) {
2699                 sprintf(buf, LPU64, num);
2700         } else {
2701                 if (num >> 30)
2702                         sprintf(buf, "%5.4gT", (double)num / (1 << 30));
2703                 else if (num >> 20)
2704                         sprintf(buf, "%5.4gG", (double)num / (1 << 20));
2705                 else if (num >> 10)
2706                         sprintf(buf, "%5.4gM", (double)num / (1 << 10));
2707                 else
2708                         sprintf(buf, LPU64"%s", num, "k");
2709         }
2710 }
2711
2712 static void print_quota(char *mnt, struct if_quotactl *qctl, int type,
2713                         int rc, bool h)
2714 {
2715         time_t now;
2716
2717         time(&now);
2718
2719         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA) {
2720                 int bover = 0, iover = 0;
2721                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
2722                 char numbuf[3][32];
2723                 char timebuf[40];
2724                 char strbuf[32];
2725
2726                 if (dqb->dqb_bhardlimit &&
2727                     lustre_stoqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
2728                         bover = 1;
2729                 } else if (dqb->dqb_bsoftlimit && dqb->dqb_btime) {
2730                         if (dqb->dqb_btime > now) {
2731                                 bover = 2;
2732                         } else {
2733                                 bover = 3;
2734                         }
2735                 }
2736
2737                 if (dqb->dqb_ihardlimit &&
2738                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
2739                         iover = 1;
2740                 } else if (dqb->dqb_isoftlimit && dqb->dqb_itime) {
2741                         if (dqb->dqb_itime > now) {
2742                                 iover = 2;
2743                         } else {
2744                                 iover = 3;
2745                         }
2746                 }
2747
2748
2749                 if (strlen(mnt) > 15)
2750                         printf("%s\n%15s", mnt, "");
2751                 else
2752                         printf("%15s", mnt);
2753
2754                 if (bover)
2755                         diff2str(dqb->dqb_btime, timebuf, now);
2756
2757                 kbytes2str(lustre_stoqb(dqb->dqb_curspace), strbuf, h);
2758                 if (rc == -EREMOTEIO)
2759                         sprintf(numbuf[0], "%s*", strbuf);
2760                 else
2761                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
2762                                 "%s" : "[%s]", strbuf);
2763
2764                 kbytes2str(dqb->dqb_bsoftlimit, strbuf, h);
2765                 if (type == QC_GENERAL)
2766                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS) ?
2767                                 "%s" : "[%s]", strbuf);
2768                 else
2769                         sprintf(numbuf[1], "%s", "-");
2770
2771                 kbytes2str(dqb->dqb_bhardlimit, strbuf, h);
2772                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS) ?
2773                         "%s" : "[%s]", strbuf);
2774
2775                 printf(" %7s%c %6s %7s %7s",
2776                        numbuf[0], bover ? '*' : ' ', numbuf[1],
2777                        numbuf[2], bover > 1 ? timebuf : "-");
2778
2779                 if (iover)
2780                         diff2str(dqb->dqb_itime, timebuf, now);
2781
2782                 sprintf(numbuf[0], (dqb->dqb_valid & QIF_INODES) ?
2783                         LPU64 : "["LPU64"]", dqb->dqb_curinodes);
2784
2785                 if (type == QC_GENERAL)
2786                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS) ?
2787                                 LPU64 : "["LPU64"]", dqb->dqb_isoftlimit);
2788                 else
2789                         sprintf(numbuf[1], "%s", "-");
2790
2791                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
2792                         LPU64 : "["LPU64"]", dqb->dqb_ihardlimit);
2793
2794                 if (type != QC_OSTIDX)
2795                         printf(" %7s%c %6s %7s %7s",
2796                                numbuf[0], iover ? '*' : ' ', numbuf[1],
2797                                numbuf[2], iover > 1 ? timebuf : "-");
2798                 else
2799                         printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
2800                 printf("\n");
2801
2802         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO ||
2803                    qctl->qc_cmd == Q_GETOINFO) {
2804                 char bgtimebuf[40];
2805                 char igtimebuf[40];
2806
2807                 sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
2808                 sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
2809                 printf("Block grace time: %s; Inode grace time: %s\n",
2810                        bgtimebuf, igtimebuf);
2811         }
2812 }
2813
2814 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt,
2815                            bool h, __u64 *total)
2816 {
2817         int rc = 0, rc1 = 0, count = 0;
2818         __u32 valid = qctl->qc_valid;
2819
2820         rc = llapi_get_obd_count(mnt, &count, is_mdt);
2821         if (rc) {
2822                 fprintf(stderr, "can not get %s count: %s\n",
2823                         is_mdt ? "mdt": "ost", strerror(-rc));
2824                 return rc;
2825         }
2826
2827         for (qctl->qc_idx = 0; qctl->qc_idx < count; qctl->qc_idx++) {
2828                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
2829                 rc = llapi_quotactl(mnt, qctl);
2830                 if (rc) {
2831                         /* It is remote client case. */
2832                         if (-rc == EOPNOTSUPP) {
2833                                 rc = 0;
2834                                 goto out;
2835                         }
2836
2837                         if (!rc1)
2838                                 rc1 = rc;
2839                         fprintf(stderr, "quotactl %s%d failed.\n",
2840                                 is_mdt ? "mdt": "ost", qctl->qc_idx);
2841                         continue;
2842                 }
2843
2844                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl,
2845                             qctl->qc_valid, 0, h);
2846                 *total += is_mdt ? qctl->qc_dqblk.dqb_ihardlimit :
2847                                    qctl->qc_dqblk.dqb_bhardlimit;
2848         }
2849 out:
2850         qctl->qc_valid = valid;
2851         return rc ? : rc1;
2852 }
2853
2854 static int lfs_quota(int argc, char **argv)
2855 {
2856         int c;
2857         char *mnt, *name = NULL;
2858         struct if_quotactl qctl = { .qc_cmd = LUSTRE_Q_GETQUOTA,
2859                                     .qc_type = UGQUOTA };
2860         char *obd_type = (char *)qctl.obd_type;
2861         char *obd_uuid = (char *)qctl.obd_uuid.uuid;
2862         int rc, rc1 = 0, rc2 = 0, rc3 = 0,
2863             verbose = 0, pass = 0, quiet = 0, inacc;
2864         char *endptr;
2865         __u32 valid = QC_GENERAL, idx = 0;
2866         __u64 total_ialloc = 0, total_balloc = 0;
2867         bool human_readable = false;
2868
2869         optind = 0;
2870         while ((c = getopt(argc, argv, "gi:I:o:qtuvh")) != -1) {
2871                 switch (c) {
2872                 case 'u':
2873                         if (qctl.qc_type != UGQUOTA) {
2874                                 fprintf(stderr, "error: use either -u or -g\n");
2875                                 return CMD_HELP;
2876                         }
2877                         qctl.qc_type = USRQUOTA;
2878                         break;
2879                 case 'g':
2880                         if (qctl.qc_type != UGQUOTA) {
2881                                 fprintf(stderr, "error: use either -u or -g\n");
2882                                 return CMD_HELP;
2883                         }
2884                         qctl.qc_type = GRPQUOTA;
2885                         break;
2886                 case 't':
2887                         qctl.qc_cmd = LUSTRE_Q_GETINFO;
2888                         break;
2889                 case 'o':
2890                         valid = qctl.qc_valid = QC_UUID;
2891                         strlcpy(obd_uuid, optarg, sizeof(qctl.obd_uuid));
2892                         break;
2893                 case 'i':
2894                         valid = qctl.qc_valid = QC_MDTIDX;
2895                         idx = qctl.qc_idx = atoi(optarg);
2896                         break;
2897                 case 'I':
2898                         valid = qctl.qc_valid = QC_OSTIDX;
2899                         idx = qctl.qc_idx = atoi(optarg);
2900                         break;
2901                 case 'v':
2902                         verbose = 1;
2903                         break;
2904                 case 'q':
2905                         quiet = 1;
2906                         break;
2907                 case 'h':
2908                         human_readable = true;
2909                         break;
2910                 default:
2911                         fprintf(stderr, "error: %s: option '-%c' "
2912                                         "unrecognized\n", argv[0], c);
2913                         return CMD_HELP;
2914                 }
2915         }
2916
2917         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
2918         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA && qctl.qc_type == UGQUOTA &&
2919             optind == argc - 1) {
2920 ug_output:
2921                 memset(&qctl, 0, sizeof(qctl)); /* spoiled by print_*_quota */
2922                 qctl.qc_cmd = LUSTRE_Q_GETQUOTA;
2923                 qctl.qc_valid = valid;
2924                 qctl.qc_idx = idx;
2925                 if (pass++ == 0) {
2926                         qctl.qc_type = USRQUOTA;
2927                         qctl.qc_id = geteuid();
2928                 } else {
2929                         qctl.qc_type = GRPQUOTA;
2930                         qctl.qc_id = getegid();
2931                 }
2932                 rc = id2name(&name, qctl.qc_id,
2933                              (qctl.qc_type == USRQUOTA) ? USER : GROUP);
2934                 if (rc)
2935                         name = "<unknown>";
2936         /* lfs quota -u username /path/to/lustre/mount */
2937         } else if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) {
2938                 /* options should be followed by u/g-name and mntpoint */
2939                 if (optind + 2 != argc || qctl.qc_type == UGQUOTA) {
2940                         fprintf(stderr, "error: missing quota argument(s)\n");
2941                         return CMD_HELP;
2942                 }
2943
2944                 name = argv[optind++];
2945                 rc = name2id(&qctl.qc_id, name,
2946                              (qctl.qc_type == USRQUOTA) ? USER : GROUP);
2947                 if (rc) {
2948                         qctl.qc_id = strtoul(name, &endptr, 10);
2949                         if (*endptr != '\0') {
2950                                 fprintf(stderr, "error: can't find id for name "
2951                                         "%s\n", name);
2952                                 return CMD_HELP;
2953                         }
2954                 }
2955         } else if (optind + 1 != argc || qctl.qc_type == UGQUOTA) {
2956                 fprintf(stderr, "error: missing quota info argument(s)\n");
2957                 return CMD_HELP;
2958         }
2959
2960         mnt = argv[optind];
2961
2962         rc1 = llapi_quotactl(mnt, &qctl);
2963         if (rc1 < 0) {
2964                 switch (rc1) {
2965                 case -ESRCH:
2966                         fprintf(stderr, "%s quotas are not enabled.\n",
2967                                 qctl.qc_type == USRQUOTA ? "user" : "group");
2968                         goto out;
2969                 case -EPERM:
2970                         fprintf(stderr, "Permission denied.\n");
2971                 case -ENOENT:
2972                         /* We already got a "No such file..." message. */
2973                         goto out;
2974                 default:
2975                         fprintf(stderr, "Unexpected quotactl error: %s\n",
2976                                 strerror(-rc1));
2977                 }
2978         }
2979
2980         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA && !quiet)
2981                 print_quota_title(name, &qctl, human_readable);
2982
2983         if (rc1 && *obd_type)
2984                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
2985
2986         if (qctl.qc_valid != QC_GENERAL)
2987                 mnt = "";
2988
2989         inacc = (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) &&
2990                 ((qctl.qc_dqblk.dqb_valid & (QIF_LIMITS|QIF_USAGE)) !=
2991                  (QIF_LIMITS|QIF_USAGE));
2992
2993         print_quota(mnt, &qctl, QC_GENERAL, rc1, human_readable);
2994
2995         if (qctl.qc_valid == QC_GENERAL && qctl.qc_cmd != LUSTRE_Q_GETINFO &&
2996             verbose) {
2997                 char strbuf[32];
2998
2999                 rc2 = print_obd_quota(mnt, &qctl, 1, human_readable,
3000                                       &total_ialloc);
3001                 rc3 = print_obd_quota(mnt, &qctl, 0, human_readable,
3002                                       &total_balloc);
3003                 kbytes2str(total_balloc, strbuf, human_readable);
3004                 printf("Total allocated inode limit: "LPU64", total "
3005                        "allocated block limit: %s\n", total_ialloc, strbuf);
3006         }
3007
3008         if (rc1 || rc2 || rc3 || inacc)
3009                 printf("Some errors happened when getting quota info. "
3010                        "Some devices may be not working or deactivated. "
3011                        "The data in \"[]\" is inaccurate.\n");
3012
3013 out:
3014         if (pass == 1)
3015                 goto ug_output;
3016
3017         return rc1;
3018 }
3019 #endif /* HAVE_SYS_QUOTA_H! */
3020
3021 static int flushctx_ioctl(char *mp)
3022 {
3023         int fd, rc;
3024
3025         fd = open(mp, O_RDONLY);
3026         if (fd == -1) {
3027                 fprintf(stderr, "flushctx: error open %s: %s\n",
3028                         mp, strerror(errno));
3029                 return -1;
3030         }
3031
3032         rc = ioctl(fd, LL_IOC_FLUSHCTX);
3033         if (rc == -1)
3034                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
3035                         mp, strerror(errno));
3036
3037         close(fd);
3038         return rc;
3039 }
3040
3041 static int lfs_flushctx(int argc, char **argv)
3042 {
3043         int     kdestroy = 0, c;
3044         char    mntdir[PATH_MAX] = {'\0'};
3045         int     index = 0;
3046         int     rc = 0;
3047
3048         optind = 0;
3049         while ((c = getopt(argc, argv, "k")) != -1) {
3050                 switch (c) {
3051                 case 'k':
3052                         kdestroy = 1;
3053                         break;
3054                 default:
3055                         fprintf(stderr, "error: %s: option '-%c' "
3056                                         "unrecognized\n", argv[0], c);
3057                         return CMD_HELP;
3058                 }
3059         }
3060
3061         if (kdestroy) {
3062             if ((rc = system("kdestroy > /dev/null")) != 0) {
3063                 rc = WEXITSTATUS(rc);
3064                 fprintf(stderr, "error destroying tickets: %d, continuing\n", rc);
3065             }
3066         }
3067
3068         if (optind >= argc) {
3069                 /* flush for all mounted lustre fs. */
3070                 while (!llapi_search_mounts(NULL, index++, mntdir, NULL)) {
3071                         /* Check if we have a mount point */
3072                         if (mntdir[0] == '\0')
3073                                 continue;
3074
3075                         if (flushctx_ioctl(mntdir))
3076                                 rc = -1;
3077
3078                         mntdir[0] = '\0'; /* avoid matching in next loop */
3079                 }
3080         } else {
3081                 /* flush fs as specified */
3082                 while (optind < argc) {
3083                         if (flushctx_ioctl(argv[optind++]))
3084                                 rc = -1;
3085                 }
3086         }
3087         return rc;
3088 }
3089
3090 static int lfs_lsetfacl(int argc, char **argv)
3091 {
3092         argv[0]++;
3093         return(llapi_lsetfacl(argc, argv));
3094 }
3095
3096 static int lfs_lgetfacl(int argc, char **argv)
3097 {
3098         argv[0]++;
3099         return(llapi_lgetfacl(argc, argv));
3100 }
3101
3102 static int lfs_rsetfacl(int argc, char **argv)
3103 {
3104         argv[0]++;
3105         return(llapi_rsetfacl(argc, argv));
3106 }
3107
3108 static int lfs_rgetfacl(int argc, char **argv)
3109 {
3110         argv[0]++;
3111         return(llapi_rgetfacl(argc, argv));
3112 }
3113
3114 static int lfs_cp(int argc, char **argv)
3115 {
3116         return(llapi_cp(argc, argv));
3117 }
3118
3119 static int lfs_ls(int argc, char **argv)
3120 {
3121         return(llapi_ls(argc, argv));
3122 }
3123
3124 static int lfs_changelog(int argc, char **argv)
3125 {
3126         void *changelog_priv;
3127         struct changelog_ext_rec *rec;
3128         long long startrec = 0, endrec = 0;
3129         char *mdd;
3130         struct option long_opts[] = {
3131                 {"follow", no_argument, 0, 'f'},
3132                 {0, 0, 0, 0}
3133         };
3134         char short_opts[] = "f";
3135         int rc, follow = 0;
3136
3137         optind = 0;
3138         while ((rc = getopt_long(argc, argv, short_opts,
3139                                 long_opts, NULL)) != -1) {
3140                 switch (rc) {
3141                 case 'f':
3142                         follow++;
3143                         break;
3144                 case '?':
3145                         return CMD_HELP;
3146                 default:
3147                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
3148                                 argv[0], argv[optind - 1]);
3149                         return CMD_HELP;
3150                 }
3151         }
3152         if (optind >= argc)
3153                 return CMD_HELP;
3154
3155         mdd = argv[optind++];
3156         if (argc > optind)
3157                 startrec = strtoll(argv[optind++], NULL, 10);
3158         if (argc > optind)
3159                 endrec = strtoll(argv[optind++], NULL, 10);
3160
3161         rc = llapi_changelog_start(&changelog_priv,
3162                                    CHANGELOG_FLAG_BLOCK |
3163                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
3164                                    mdd, startrec);
3165         if (rc < 0) {
3166                 fprintf(stderr, "Can't start changelog: %s\n",
3167                         strerror(errno = -rc));
3168                 return rc;
3169         }
3170
3171         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
3172                 time_t secs;
3173                 struct tm ts;
3174
3175                 if (endrec && rec->cr_index > endrec) {
3176                         llapi_changelog_free(&rec);
3177                         break;
3178                 }
3179                 if (rec->cr_index < startrec) {
3180                         llapi_changelog_free(&rec);
3181                         continue;
3182                 }
3183
3184                 secs = rec->cr_time >> 30;
3185                 gmtime_r(&secs, &ts);
3186                 printf(LPU64" %02d%-5s %02d:%02d:%02d.%06d %04d.%02d.%02d "
3187                        "0x%x t="DFID, rec->cr_index, rec->cr_type,
3188                        changelog_type2str(rec->cr_type),
3189                        ts.tm_hour, ts.tm_min, ts.tm_sec,
3190                        (int)(rec->cr_time & ((1<<30) - 1)),
3191                        ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday,
3192                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
3193                 if (rec->cr_namelen)
3194                         /* namespace rec includes parent and filename */
3195                         printf(" p="DFID" %.*s", PFID(&rec->cr_pfid),
3196                                 rec->cr_namelen, rec->cr_name);
3197
3198                 if (!fid_is_zero(&rec->cr_sfid))
3199                         printf(" s="DFID" sp="DFID" %.*s",
3200                                 PFID(&rec->cr_sfid), PFID(&rec->cr_spfid),
3201                                 changelog_rec_snamelen(rec),
3202                                 changelog_rec_sname(rec));
3203                 printf("\n");
3204
3205                 llapi_changelog_free(&rec);
3206         }
3207
3208         llapi_changelog_fini(&changelog_priv);
3209
3210         if (rc < 0)
3211                 fprintf(stderr, "Changelog: %s\n", strerror(errno = -rc));
3212
3213         return (rc == 1 ? 0 : rc);
3214 }
3215
3216 static int lfs_changelog_clear(int argc, char **argv)
3217 {
3218         long long endrec;
3219         int rc;
3220
3221         if (argc != 4)
3222                 return CMD_HELP;
3223
3224         endrec = strtoll(argv[3], NULL, 10);
3225
3226         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
3227         if (rc)
3228                 fprintf(stderr, "%s error: %s\n", argv[0],
3229                         strerror(errno = -rc));
3230         return rc;
3231 }
3232
3233 static int lfs_fid2path(int argc, char **argv)
3234 {
3235         struct option long_opts[] = {
3236                 {"cur", no_argument, 0, 'c'},
3237                 {"link", required_argument, 0, 'l'},
3238                 {"rec", required_argument, 0, 'r'},
3239                 {0, 0, 0, 0}
3240         };
3241         char  short_opts[] = "cl:r:";
3242         char *device, *fid, *path;
3243         long long recno = -1;
3244         int linkno = -1;
3245         int lnktmp;
3246         int printcur = 0;
3247         int rc = 0;
3248
3249         optind = 0;
3250
3251         while ((rc = getopt_long(argc, argv, short_opts,
3252                                 long_opts, NULL)) != -1) {
3253                 switch (rc) {
3254                 case 'c':
3255                         printcur++;
3256                         break;
3257                 case 'l':
3258                         linkno = strtol(optarg, NULL, 10);
3259                         break;
3260                 case 'r':
3261                         recno = strtoll(optarg, NULL, 10);
3262                         break;
3263                 case '?':
3264                         return CMD_HELP;
3265                 default:
3266                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
3267                                 argv[0], argv[optind - 1]);
3268                         return CMD_HELP;
3269                 }
3270         }
3271
3272         if (argc < 3)
3273                 return CMD_HELP;
3274
3275         device = argv[optind++];
3276         path = calloc(1, PATH_MAX);
3277         if (path == NULL) {
3278                 fprintf(stderr, "error: Not enough memory\n");
3279                 return -errno;
3280         }
3281
3282         rc = 0;
3283         while (optind < argc) {
3284                 fid = argv[optind++];
3285
3286                 lnktmp = (linkno >= 0) ? linkno : 0;
3287                 while (1) {
3288                         int oldtmp = lnktmp;
3289                         long long rectmp = recno;
3290                         int rc2;
3291                         rc2 = llapi_fid2path(device, fid, path, PATH_MAX,
3292                                              &rectmp, &lnktmp);
3293                         if (rc2 < 0) {
3294                                 fprintf(stderr, "%s: error on FID %s: %s\n",
3295                                         argv[0], fid, strerror(errno = -rc2));
3296                                 if (rc == 0)
3297                                         rc = rc2;
3298                                 break;
3299                         }
3300
3301                         if (printcur)
3302                                 fprintf(stdout, "%lld ", rectmp);
3303                         if (device[0] == '/') {
3304                                 fprintf(stdout, "%s", device);
3305                                 if (device[strlen(device) - 1] != '/')
3306                                         fprintf(stdout, "/");
3307                         } else if (path[0] == '\0') {
3308                                 fprintf(stdout, "/");
3309                         }
3310                         fprintf(stdout, "%s\n", path);
3311
3312                         if (linkno >= 0)
3313                                 /* specified linkno */
3314                                 break;
3315                         if (oldtmp == lnktmp)
3316                                 /* no more links */
3317                                 break;
3318                 }
3319         }
3320
3321         free(path);
3322         return rc;
3323 }
3324
3325 static int lfs_path2fid(int argc, char **argv)
3326 {
3327         char **path;
3328         const char *sep = "";
3329         lustre_fid fid;
3330         int rc = 0;
3331
3332         if (argc < 2)
3333                 return CMD_HELP;
3334         else if (argc > 2)
3335                 sep = ": ";
3336
3337         path = argv + 1;
3338         while (*path != NULL) {
3339                 int err = llapi_path2fid(*path, &fid);
3340
3341                 if (err) {
3342                         fprintf(stderr, "%s: can't get fid for %s: %s\n",
3343                                 argv[0], *path, strerror(-err));
3344                         if (rc == 0) {
3345                                 rc = err;
3346                                 errno = -err;
3347                         }
3348                         goto out;
3349                 }
3350                 printf("%s%s"DFID"\n", *sep != '\0' ? *path : "", sep,
3351                        PFID(&fid));
3352 out:
3353                 path++;
3354         }
3355
3356         return rc;
3357 }
3358
3359 static int lfs_data_version(int argc, char **argv)
3360 {
3361         char *path;
3362         __u64 data_version;
3363         int fd;
3364         int rc;
3365         int c;
3366         int data_version_flags = LL_DV_RD_FLUSH; /* Read by default */
3367
3368         if (argc < 2)
3369                 return CMD_HELP;
3370
3371         optind = 0;
3372         while ((c = getopt(argc, argv, "nrw")) != -1) {
3373                 switch (c) {
3374                 case 'n':
3375                         data_version_flags = 0;
3376                         break;
3377                 case 'r':
3378                         data_version_flags |= LL_DV_RD_FLUSH;
3379                         break;
3380                 case 'w':
3381                         data_version_flags |= LL_DV_WR_FLUSH;
3382                         break;
3383                 default:
3384                         return CMD_HELP;
3385                 }
3386         }
3387         if (optind == argc)
3388                 return CMD_HELP;
3389
3390         path = argv[optind];
3391         fd = open(path, O_RDONLY);
3392         if (fd < 0)
3393                 err(errno, "cannot open file %s", path);
3394
3395         rc = llapi_get_data_version(fd, &data_version, data_version_flags);
3396         if (rc < 0)
3397                 err(errno, "cannot get version for %s", path);
3398         else
3399                 printf(LPU64 "\n", data_version);
3400
3401         close(fd);
3402         return rc;
3403 }
3404
3405 static int lfs_hsm_state(int argc, char **argv)
3406 {
3407         int rc;
3408         int i = 1;
3409         char *path;
3410         struct hsm_user_state hus;
3411
3412         if (argc < 2)
3413                 return CMD_HELP;
3414
3415         do {
3416                 path = argv[i];
3417
3418                 rc = llapi_hsm_state_get(path, &hus);
3419                 if (rc) {
3420                         fprintf(stderr, "can't get hsm state for %s: %s\n",
3421                                 path, strerror(errno = -rc));
3422                         return rc;
3423                 }
3424
3425                 /* Display path name and status flags */
3426                 printf("%s: (0x%08x)", path, hus.hus_states);
3427
3428                 if (hus.hus_states & HS_RELEASED)
3429                         printf(" released");
3430                 if (hus.hus_states & HS_EXISTS)
3431                         printf(" exists");
3432                 if (hus.hus_states & HS_DIRTY)
3433                         printf(" dirty");
3434                 if (hus.hus_states & HS_ARCHIVED)
3435                         printf(" archived");
3436                 /* Display user-settable flags */
3437                 if (hus.hus_states & HS_NORELEASE)
3438                         printf(" never_release");
3439                 if (hus.hus_states & HS_NOARCHIVE)
3440                         printf(" never_archive");
3441                 if (hus.hus_states & HS_LOST)
3442                         printf(" lost_from_hsm");
3443
3444                 if (hus.hus_archive_id != 0)
3445                         printf(", archive_id:%d", hus.hus_archive_id);
3446                 printf("\n");
3447
3448         } while (++i < argc);
3449
3450         return 0;
3451 }
3452
3453 #define LFS_HSM_SET   0
3454 #define LFS_HSM_CLEAR 1
3455
3456 /**
3457  * Generic function to set or clear HSM flags.
3458  * Used by hsm_set and hsm_clear.
3459  *
3460  * @mode  if LFS_HSM_SET, set the flags, if LFS_HSM_CLEAR, clear the flags.
3461  */
3462 static int lfs_hsm_change_flags(int argc, char **argv, int mode)
3463 {
3464         struct option long_opts[] = {
3465                 {"lost", 0, 0, 'l'},
3466                 {"norelease", 0, 0, 'r'},
3467                 {"noarchive", 0, 0, 'a'},
3468                 {"archived", 0, 0, 'A'},
3469                 {"dirty", 0, 0, 'd'},
3470                 {"exists", 0, 0, 'e'},
3471                 {0, 0, 0, 0}
3472         };
3473         char short_opts[] = "lraAde";
3474         __u64 mask = 0;
3475         int c, rc;
3476         char *path;
3477
3478         if (argc < 3)
3479                 return CMD_HELP;
3480
3481         optind = 0;
3482         while ((c = getopt_long(argc, argv, short_opts,
3483                                 long_opts, NULL)) != -1) {
3484                 switch (c) {
3485                 case 'l':
3486                         mask |= HS_LOST;
3487                         break;
3488                 case 'a':
3489                         mask |= HS_NOARCHIVE;
3490                         break;
3491                 case 'A':
3492                         mask |= HS_ARCHIVED;
3493                         break;
3494                 case 'r':
3495                         mask |= HS_NORELEASE;
3496                         break;
3497                 case 'd':
3498                         mask |= HS_DIRTY;
3499                         break;
3500                 case 'e':
3501                         mask |= HS_EXISTS;
3502                         break;
3503                 case '?':
3504                         return CMD_HELP;
3505                 default:
3506                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
3507                                 argv[0], argv[optind - 1]);
3508                         return CMD_HELP;
3509                 }
3510         }
3511
3512         /* User should have specified a flag */
3513         if (mask == 0)
3514                 return CMD_HELP;
3515
3516         while (optind < argc) {
3517
3518                 path = argv[optind];
3519
3520                 /* If mode == 0, this means we apply the mask. */
3521                 if (mode == LFS_HSM_SET)
3522                         rc = llapi_hsm_state_set(path, mask, 0, 0);
3523                 else
3524                         rc = llapi_hsm_state_set(path, 0, mask, 0);
3525
3526                 if (rc != 0) {
3527                         fprintf(stderr, "Can't change hsm flags for %s: %s\n",
3528                                 path, strerror(errno = -rc));
3529                         return rc;
3530                 }
3531                 optind++;
3532         }
3533
3534         return 0;
3535 }
3536
3537 static int lfs_hsm_action(int argc, char **argv)
3538 {
3539         int                              rc;
3540         int                              i = 1;
3541         char                            *path;
3542         struct hsm_current_action        hca;
3543         struct hsm_extent                he;
3544         enum hsm_user_action             hua;
3545         enum hsm_progress_states         hps;
3546
3547         if (argc < 2)
3548                 return CMD_HELP;
3549
3550         do {
3551                 path = argv[i];
3552
3553                 rc = llapi_hsm_current_action(path, &hca);
3554                 if (rc) {
3555                         fprintf(stderr, "can't get hsm action for %s: %s\n",
3556                                 path, strerror(errno = -rc));
3557                         return rc;
3558                 }
3559                 he = hca.hca_location;
3560                 hua = hca.hca_action;
3561                 hps = hca.hca_state;
3562
3563                 printf("%s: %s", path, hsm_user_action2name(hua));
3564
3565                 /* Skip file without action */
3566                 if (hca.hca_action == HUA_NONE) {
3567                         printf("\n");
3568                         continue;
3569                 }
3570
3571                 printf(" %s ", hsm_progress_state2name(hps));
3572
3573                 if ((hps == HPS_RUNNING) &&
3574                     (hua == HUA_ARCHIVE || hua == HUA_RESTORE))
3575                         printf("("LPX64 " bytes moved)\n", he.length);
3576                 else if ((he.offset + he.length) == LUSTRE_EOF)
3577                         printf("(from "LPX64 " to EOF)\n", he.offset);
3578                 else
3579                         printf("(from "LPX64 " to "LPX64")\n",
3580                                he.offset, he.offset + he.length);
3581
3582         } while (++i < argc);
3583
3584         return 0;
3585 }
3586
3587 static int lfs_hsm_set(int argc, char **argv)
3588 {
3589         return lfs_hsm_change_flags(argc, argv, LFS_HSM_SET);
3590 }
3591
3592 static int lfs_hsm_clear(int argc, char **argv)
3593 {
3594         return lfs_hsm_change_flags(argc, argv, LFS_HSM_CLEAR);
3595 }
3596
3597 /**
3598  * Check file state and return its fid, to be used by lfs_hsm_request().
3599  *
3600  * \param[in]     file      Path to file to check
3601  * \param[in,out] fid       Pointer to allocated lu_fid struct.
3602  * \param[in,out] last_dev  Pointer to last device id used.
3603  *
3604  * \return 0 on success.
3605  */
3606 static int lfs_hsm_prepare_file(char *file, struct lu_fid *fid,
3607                                 dev_t *last_dev)
3608 {
3609         struct stat     st;
3610         int             rc;
3611
3612         rc = lstat(file, &st);
3613         if (rc) {
3614                 fprintf(stderr, "Cannot stat %s: %s\n", file, strerror(errno));
3615                 return -errno;
3616         }
3617         /* A request should be ... */
3618         if (*last_dev != st.st_dev && *last_dev != 0) {
3619                 fprintf(stderr, "All files should be "
3620                         "on the same filesystem: %s\n", file);
3621                 return -EINVAL;
3622         }
3623         *last_dev = st.st_dev;
3624
3625         rc = llapi_path2fid(file, fid);
3626         if (rc) {
3627                 fprintf(stderr, "Cannot read FID of %s: %s\n",
3628                         file, strerror(-rc));
3629                 return rc;
3630         }
3631         return 0;
3632 }
3633
3634 static int lfs_hsm_request(int argc, char **argv, int action)
3635 {
3636         struct option            long_opts[] = {
3637                 {"filelist", 1, 0, 'l'},
3638                 {"data", 1, 0, 'D'},
3639                 {"archive", 1, 0, 'a'},
3640                 {0, 0, 0, 0}
3641         };
3642         dev_t                    last_dev = 0;
3643         char                     short_opts[] = "l:D:a:";
3644         struct hsm_user_request *hur, *oldhur;
3645         int                      c, i;
3646         size_t                   len;
3647         int                      nbfile;
3648         char                    *line = NULL;
3649         char                    *filelist = NULL;
3650         char                     fullpath[PATH_MAX];
3651         char                    *opaque = NULL;
3652         int                      opaque_len = 0;
3653         int                      archive_id = 0;
3654         FILE                    *fp;
3655         int                      nbfile_alloc = 0;
3656         char                     some_file[PATH_MAX+1] = "";
3657         int                      rc;
3658
3659         if (argc < 2)
3660                 return CMD_HELP;
3661
3662         optind = 0;
3663         while ((c = getopt_long(argc, argv, short_opts,
3664                                 long_opts, NULL)) != -1) {
3665                 switch (c) {
3666                 case 'l':
3667                         filelist = optarg;
3668                         break;
3669                 case 'D':
3670                         opaque = optarg;
3671                         break;
3672                 case 'a':
3673                         if (action != HUA_ARCHIVE) {
3674                                 fprintf(stderr,
3675                                         "error: -a is supported only "
3676                                         "when archiving\n");
3677                                 return CMD_HELP;
3678                         }
3679                         archive_id = atoi(optarg);
3680                         break;
3681                 case '?':
3682                         return CMD_HELP;
3683                 default:
3684                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
3685                                 argv[0], argv[optind - 1]);
3686                         return CMD_HELP;
3687                 }
3688         }
3689
3690         /* All remaining args are files, so we have at least nbfile */
3691         nbfile = argc - optind;
3692
3693         if ((nbfile == 0) && (filelist == NULL))
3694                 return CMD_HELP;
3695
3696         if (opaque != NULL)
3697                 opaque_len = strlen(opaque);
3698
3699         /* Alloc the request structure with enough place to store all files
3700          * from command line. */
3701         hur = llapi_hsm_user_request_alloc(nbfile, opaque_len);
3702         if (hur == NULL) {
3703                 fprintf(stderr, "Cannot create the request: %s\n",
3704                         strerror(errno));
3705                 return errno;
3706         }
3707         nbfile_alloc = nbfile;
3708
3709         hur->hur_request.hr_action = action;
3710         hur->hur_request.hr_archive_id = archive_id;
3711         hur->hur_request.hr_flags = 0;
3712
3713         /* All remaining args are files, add them */
3714         if (nbfile != 0) {
3715                 if (strlen(argv[optind]) > sizeof(some_file)-1) {
3716                         free(hur);
3717                         return -E2BIG;
3718                 }
3719                 strncpy(some_file, argv[optind], sizeof(some_file));
3720         }
3721
3722         for (i = 0; i < nbfile; i++) {
3723                 hur->hur_user_item[i].hui_extent.length = -1;
3724                 rc = lfs_hsm_prepare_file(argv[optind + i],
3725                                           &hur->hur_user_item[i].hui_fid,
3726                                           &last_dev);
3727                 hur->hur_request.hr_itemcount++;
3728                 if (rc)
3729                         goto out_free;
3730         }
3731
3732         /* from here stop using nb_file, use hur->hur_request.hr_itemcount */
3733
3734         /* If a filelist was specified, read the filelist from it. */
3735         if (filelist != NULL) {
3736                 fp = fopen(filelist, "r");
3737                 if (fp == NULL) {
3738                         fprintf(stderr, "Cannot read the file list %s: %s\n",
3739                                 filelist, strerror(errno));
3740                         rc = -errno;
3741                         goto out_free;
3742                 }
3743
3744                 while ((rc = getline(&line, &len, fp)) != -1) {
3745                         struct hsm_user_item *hui;
3746
3747                         /* If allocated buffer was too small, gets something
3748                          * bigger */
3749                         if (nbfile_alloc <= hur->hur_request.hr_itemcount) {
3750                                 ssize_t size;
3751                                 nbfile_alloc = nbfile_alloc * 2 + 1;
3752                                 oldhur = hur;
3753                                 hur = llapi_hsm_user_request_alloc(nbfile_alloc,
3754                                                                    opaque_len);
3755                                 if (hur == NULL) {
3756                                         fprintf(stderr, "Cannot allocate "
3757                                                 "the request: %s\n",
3758                                                 strerror(errno));
3759                                         hur = oldhur;
3760                                         rc = -errno;
3761                                         fclose(fp);
3762                                         goto out_free;
3763                                 }
3764                                 size = hur_len(oldhur);
3765                                 if (size < 0) {
3766                                         fprintf(stderr, "Cannot allocate "
3767                                                 "the requested size\n");
3768                                         hur = oldhur;
3769                                         rc = -E2BIG;
3770                                         fclose(fp);
3771                                         goto out_free;
3772                                 }
3773                                 memcpy(hur, oldhur, size);
3774                                 free(oldhur);
3775                         }
3776
3777                         /* Chop CR */
3778                         if (line[strlen(line) - 1] == '\n')
3779                                 line[strlen(line) - 1] = '\0';
3780
3781                         hui =
3782                              &hur->hur_user_item[hur->hur_request.hr_itemcount];
3783                         hui->hui_extent.length = -1;
3784                         rc = lfs_hsm_prepare_file(line, &hui->hui_fid,
3785                                                   &last_dev);
3786                         hur->hur_request.hr_itemcount++;
3787                         if (rc) {
3788                                 fclose(fp);
3789                                 goto out_free;
3790                         }
3791
3792                         if ((some_file[0] == '\0') &&
3793                             (strlen(line) < sizeof(some_file)))
3794                                 strcpy(some_file, line);
3795                 }
3796
3797                 rc = fclose(fp);
3798                 if (line)
3799                         free(line);
3800         }
3801
3802         /* If a --data was used, add it to the request */
3803         hur->hur_request.hr_data_len = opaque_len;
3804         if (opaque != NULL)
3805                 memcpy(hur_data(hur), opaque, opaque_len);
3806
3807         /* Send the HSM request */
3808         if (realpath(some_file, fullpath) == NULL) {
3809                 fprintf(stderr, "Could not find path '%s': %s\n",
3810                         some_file, strerror(errno));
3811         }
3812         rc = llapi_hsm_request(fullpath, hur);
3813         if (rc) {
3814                 fprintf(stderr, "Cannot send HSM request (use of %s): %s\n",
3815                         some_file, strerror(-rc));
3816                 goto out_free;
3817         }
3818
3819 out_free:
3820         free(hur);
3821         return rc;
3822 }
3823
3824 static int lfs_hsm_archive(int argc, char **argv)
3825 {
3826         return lfs_hsm_request(argc, argv, HUA_ARCHIVE);
3827 }
3828
3829 static int lfs_hsm_restore(int argc, char **argv)
3830 {
3831         return lfs_hsm_request(argc, argv, HUA_RESTORE);
3832 }
3833
3834 static int lfs_hsm_release(int argc, char **argv)
3835 {
3836         return lfs_hsm_request(argc, argv, HUA_RELEASE);
3837 }
3838
3839 static int lfs_hsm_remove(int argc, char **argv)
3840 {
3841         return lfs_hsm_request(argc, argv, HUA_REMOVE);
3842 }
3843
3844 static int lfs_hsm_cancel(int argc, char **argv)
3845 {
3846         return lfs_hsm_request(argc, argv, HUA_CANCEL);
3847 }
3848
3849 static int lfs_swap_layouts(int argc, char **argv)
3850 {
3851         if (argc != 3)
3852                 return CMD_HELP;
3853
3854         return llapi_swap_layouts(argv[1], argv[2], 0, 0,
3855                                   SWAP_LAYOUTS_KEEP_MTIME |
3856                                   SWAP_LAYOUTS_KEEP_ATIME);
3857 }
3858
3859 int main(int argc, char **argv)
3860 {
3861         int rc;
3862
3863         setlinebuf(stdout);
3864
3865         Parser_init("lfs > ", cmdlist);
3866
3867         if (argc > 1) {
3868                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
3869         } else {
3870                 rc = Parser_commands();
3871         }
3872
3873         return rc < 0 ? -rc : rc;
3874 }
3875
3876 #ifdef _LUSTRE_IDL_H_
3877 /* Everything we need here should be included by lustreapi.h. */
3878 # error "lfs should not depend on lustre_idl.h"
3879 #endif /* _LUSTRE_IDL_H_ */