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