Whamcloud - gitweb
9694bac5a3f12bcc39fb808b1a91bc51d574f64b
[fs/lustre-release.git] / lustre / utils / lfs.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
30  * Use is subject to license terms.
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 <pwd.h>
55 #include <grp.h>
56 #include <sys/types.h>
57 #include <sys/stat.h>
58 #include <fcntl.h>
59 #include <dirent.h>
60 #include <time.h>
61 #include <ctype.h>
62 #ifdef HAVE_SYS_QUOTA_H
63 # include <sys/quota.h>
64 #endif
65
66 /* For dirname() */
67 #include <libgen.h>
68
69 #include <lnet/api-support.h>
70 #include <lnet/lnetctl.h>
71
72 #include <liblustre.h>
73 #include <lustre/lustre_idl.h>
74 #include <lustre/liblustreapi.h>
75 #include <lustre/lustre_user.h>
76 #include <lustre_quota.h>
77
78 #include <libcfs/libcfsutil.h>
79 #include "obdctl.h"
80
81 unsigned int libcfs_subsystem_debug = 0;
82
83 /* all functions */
84 static int lfs_setstripe(int argc, char **argv);
85 static int lfs_find(int argc, char **argv);
86 static int lfs_getstripe(int argc, char **argv);
87 static int lfs_osts(int argc, char **argv);
88 static int lfs_df(int argc, char **argv);
89 static int lfs_getname(int argc, char **argv);
90 static int lfs_check(int argc, char **argv);
91 static int lfs_catinfo(int argc, char **argv);
92 #ifdef HAVE_SYS_QUOTA_H
93 static int lfs_quotachown(int argc, char **argv);
94 static int lfs_quotacheck(int argc, char **argv);
95 static int lfs_quotaon(int argc, char **argv);
96 static int lfs_quotaoff(int argc, char **argv);
97 static int lfs_setquota(int argc, char **argv);
98 static int lfs_quota(int argc, char **argv);
99 static int lfs_quotainv(int argc, char **argv);
100 #endif
101 static int lfs_flushctx(int argc, char **argv);
102 static int lfs_join(int argc, char **argv);
103 static int lfs_lsetfacl(int argc, char **argv);
104 static int lfs_lgetfacl(int argc, char **argv);
105 static int lfs_rsetfacl(int argc, char **argv);
106 static int lfs_rgetfacl(int argc, char **argv);
107 static int lfs_cp(int argc, char **argv);
108 static int lfs_ls(int argc, char **argv);
109 static int lfs_poollist(int argc, char **argv);
110 static int lfs_changelog(int argc, char **argv);
111 static int lfs_changelog_clear(int argc, char **argv);
112 static int lfs_fid2path(int argc, char **argv);
113 static int lfs_path2fid(int argc, char **argv);
114
115 /* all avaialable commands */
116 command_t cmdlist[] = {
117         {"setstripe", lfs_setstripe, 0,
118          "Create a new file with a specific striping pattern or\n"
119          "set the default striping pattern on an existing directory or\n"
120          "delete the default striping pattern from an existing directory\n"
121          "usage: setstripe [--size|-s stripe_size] [--count|-c stripe_count]\n"
122          "                 [--index|-i|--offset|-o start_ost_index]\n"
123          "                 [--pool|-p <pool>] <directory|filename>\n"
124          "       or \n"
125          "       setstripe -d <directory>   (to delete default striping)\n"
126          "\tstripe_size:  Number of bytes on each OST (0 filesystem default)\n"
127          "\t              Can be specified with k, m or g (in KB, MB and GB\n"
128          "\t              respectively)\n"
129          "\tstart_ost_index: OST index of first stripe (-1 default)\n"
130          "\tstripe_count: Number of OSTs to stripe over (0 default, -1 all)\n"
131          "\tpool:         Name of OST pool to use (default none)"},
132         {"getstripe", lfs_getstripe, 0,
133          "To list the striping info for a given file or files in a\n"
134          "directory or recursively for all files in a directory tree.\n"
135          "usage: getstripe [--obd|-O <uuid>] [--quiet | -q] [--verbose | -v]\n"
136          "                 [--count | -c ] [--index | -i | --offset | -o]\n"
137          "                 [--size | -s ] [--pool | -p ] [--directory | -d]\n"
138          "                 [--mdt | -M] [--recursive | -r] [--raw | -R]\n"
139          "                 <directory|filename> ..."},
140         {"pool_list", lfs_poollist, 0,
141          "List pools or pool OSTs\n"
142          "usage: pool_list <fsname>[.<pool>] | <pathname>\n"},
143         {"find", lfs_find, 0,
144          "To find files that match given parameters recursively in a directory tree.\n"
145          "usage: find <directory|filename> ...\n"
146          "     [[!] --atime|-A [+-]N] [[!] --mtime|-M [+-]N] [[!] --ctime|-C [+-]N]\n"
147          "     [--maxdepth|-D N] [[!] --name|-n <pattern>] [--print0|-P]\n"
148          "     [--print|-p] [[!] --obd|-O <uuid[s]>] [[!] --size|-s [+-]N[bkMGTP]]\n"
149          "     [[!] --type|-t <filetype>] [[!] --gid|-g|--group|-G <gid>|<gname>]\n"
150          "     [[!] --uid|-u|--user|-U <uid>|<uname>]\n"
151          "     [[!] --pool <pool>]\n"
152          "\t !: used before an option indicates 'NOT' the requested attribute\n"
153          "\t -: used before an value indicates 'AT MOST' the requested value\n"
154          "\t +: used before an option indicates 'AT LEAST' the requested value\n"},
155         {"check", lfs_check, 0,
156          "Display the status of MDS or OSTs (as specified in the command)\n"
157          "or all the servers (MDS and OSTs).\n"
158          "usage: check <osts|mds|servers>"},
159         {"catinfo", lfs_catinfo, 0,
160          "Show information of specified type logs.\n"
161          "usage: catinfo {keyword} [node name]\n"
162          "\tkeywords are one of followings: config, deletions.\n"
163          "\tnode name must be provided when use keyword config."},
164         {"join", lfs_join, 0,
165          "join two lustre files into one.\n"
166          "obsolete, HEAD does not support it anymore.\n"},
167         {"osts", lfs_osts, 0, "list OSTs connected to client "
168          "[for specified path only]\n" "usage: osts [path]"},
169         {"df", lfs_df, 0,
170          "report filesystem disk space usage or inodes usage"
171          "of each MDS and all OSDs or a batch belonging to a specific pool .\n"
172          "Usage: df [-i] [-h] [--pool|-p <fsname>[.<pool>] [path]"},
173         {"getname", lfs_getname, 0, "list instances and specified mount points "
174          "[for specified path only]\n"
175          "Usage: getname [-h]|[path ...] "},
176 #ifdef HAVE_SYS_QUOTA_H
177         {"quotachown",lfs_quotachown, 0,
178          "Change files' owner or group on the specified filesystem.\n"
179          "usage: quotachown [-i] <filesystem>\n"
180          "\t-i: ignore error if file is not exist\n"},
181         {"quotacheck", lfs_quotacheck, 0,
182          "Scan the specified filesystem for disk usage, and create,\n"
183          "or update quota files.\n"
184          "usage: quotacheck [ -ug ] <filesystem>"},
185         {"quotaon", lfs_quotaon, 0, "Turn filesystem quotas on.\n"
186          "usage: quotaon [ -ugf ] <filesystem>"},
187         {"quotaoff", lfs_quotaoff, 0, "Turn filesystem quotas off.\n"
188          "usage: quotaoff [ -ug ] <filesystem>"},
189         {"setquota", lfs_setquota, 0, "Set filesystem quotas.\n"
190          "usage: setquota <-u|-g> <uname>|<uid>|<gname>|<gid>\n"
191          "                -b <block-softlimit> -B <block-hardlimit>\n"
192          "                -i <inode-softlimit> -I <inode-hardlimit> <filesystem>\n"
193          "       setquota -t <-u|-g> <block-grace> <inode-grace> <filesystem>\n"
194          "       setquota <-u|--user|-g|--group> <uname>|<uid>|<gname>|<gid>\n"
195          "                [--block-softlimit <block-softlimit>]\n"
196          "                [--block-hardlimit <block-hardlimit>]\n"
197          "                [--inode-softlimit <inode-softlimit>]\n"
198          "                [--inode-hardlimit <inode-hardlimit>] <filesystem>\n"
199          "       setquota [-t] <-u|--user|-g|--group>\n"
200          "                [--block-grace <block-grace>]\n"
201          "                [--inode-grace <inode-grace>] <filesystem>\n"
202          "       -b can be used instead of --block-softlimit/--block-grace\n"
203          "       -B can be used instead of --block-hardlimit\n"
204          "       -i can be used instead of --inode-softlimit/--inode-grace\n"
205          "       -I can be used instead of --inode-hardlimit"},
206         {"quota", lfs_quota, 0, "Display disk usage and limits.\n"
207          "usage: quota [-q] [-v] [-o <obd_uuid>|-i <mdt_idx>|-I <ost_idx>]\n"
208          "             [<-u|-g> <uname>|<uid>|<gname>|<gid>] <filesystem>\n"
209          "       quota [-o <obd_uuid>|-i <mdt_idx>|-I <ost_idx>] -t <-u|-g> <filesystem>"},
210         {"quotainv", lfs_quotainv, 0, "Invalidate quota data.\n"
211          "usage: quotainv [-u|-g] <filesystem>"},
212 #endif
213         {"flushctx", lfs_flushctx, 0, "Flush security context for current user.\n"
214          "usage: flushctx [-k] [mountpoint...]"},
215         {"lsetfacl", lfs_lsetfacl, 0,
216          "Remote user setfacl for user/group on the same remote client.\n"
217          "usage: lsetfacl [-bkndRLPvh] [{-m|-x} acl_spec] [{-M|-X} acl_file] file ..."},
218         {"lgetfacl", lfs_lgetfacl, 0,
219          "Remote user getfacl for user/group on the same remote client.\n"
220          "usage: lgetfacl [-dRLPvh] file ..."},
221         {"rsetfacl", lfs_rsetfacl, 0,
222          "Remote user setfacl for user/group on other clients.\n"
223          "usage: rsetfacl [-bkndRLPvh] [{-m|-x} acl_spec] [{-M|-X} acl_file] file ..."},
224         {"rgetfacl", lfs_rgetfacl, 0,
225          "Remote user getfacl for user/group on other clients.\n"
226          "usage: rgetfacl [-dRLPvh] file ..."},
227         {"cp", lfs_cp, 0,
228          "Remote user copy files and directories.\n"
229          "usage: cp [OPTION]... [-T] SOURCE DEST\n\tcp [OPTION]... SOURCE... DIRECTORY\n\tcp [OPTION]... -t DIRECTORY SOURCE..."},
230         {"ls", lfs_ls, 0,
231          "Remote user list directory contents.\n"
232          "usage: ls [OPTION]... [FILE]..."},
233         {"changelog", lfs_changelog, 0,
234          "Show the metadata changes on an MDT."
235          "\nusage: changelog <mdtname> [startrec [endrec]]"},
236         {"changelog_clear", lfs_changelog_clear, 0,
237          "Indicate that old changelog records up to <endrec> are no longer of "
238          "interest to consumer <id>, allowing the system to free up space.\n"
239          "An <endrec> of 0 means all records.\n"
240          "usage: changelog_clear <mdtname> <id> <endrec>"},
241         {"fid2path", lfs_fid2path, 0,
242          "Resolve the full path to a given FID. For a specific hardlink "
243          "specify link number <linkno>.\n"
244          /* "For a historical name, specify changelog record <recno>.\n" */
245          "usage: fid2path <fsname|rootpath> <fid> [--link <linkno>]"
246                 /*[--rec <recno>]*/},
247         {"path2fid", lfs_path2fid, 0, "Display the fid for a given path.\n"
248          "usage: path2fid <path>"},
249         {"help", Parser_help, 0, "help"},
250         {"exit", Parser_quit, 0, "quit"},
251         {"quit", Parser_quit, 0, "quit"},
252         { 0, 0, 0, NULL }
253 };
254
255 static int isnumber(const char *str)
256 {
257         const char *ptr;
258
259         if (str[0] != '-' && !isdigit(str[0]))
260                 return 0;
261
262         for (ptr = str + 1; *ptr != '\0'; ptr++) {
263                 if (!isdigit(*ptr))
264                         return 0;
265         }
266
267         return 1;
268 }
269
270 /* functions */
271 static int lfs_setstripe(int argc, char **argv)
272 {
273         char *fname;
274         int result;
275         unsigned long long st_size;
276         int  st_offset, st_count;
277         char *end;
278         int c;
279         int delete = 0;
280         char *stripe_size_arg = NULL;
281         char *stripe_off_arg = NULL;
282         char *stripe_count_arg = NULL;
283         char *pool_name_arg = NULL;
284         unsigned long long size_units = 1;
285
286         struct option long_opts[] = {
287                 {"count",       required_argument, 0, 'c'},
288                 {"delete",      no_argument,       0, 'd'},
289                 {"index",       required_argument, 0, 'i'},
290                 {"offset",      required_argument, 0, 'o'},
291                 {"pool",        required_argument, 0, 'p'},
292                 {"size",        required_argument, 0, 's'},
293                 {0, 0, 0, 0}
294         };
295
296         st_size = 0;
297         st_offset = -1;
298         st_count = 0;
299
300 #if LUSTRE_VERSION < OBD_OCD_VERSION(2,4,50,0)
301         if (argc == 5 && argv[1][0] != '-' &&
302             isnumber(argv[2]) && isnumber(argv[3]) && isnumber(argv[4])) {
303                 fprintf(stderr, "error: obsolete usage of setstripe "
304                         "positional parameters.  Use -c, -i, -s instead.\n");
305                 return CMD_HELP;
306         } else
307 #else
308 #warning "remove obsolete positional parameter code"
309 #endif
310         {
311                 optind = 0;
312                 while ((c = getopt_long(argc, argv, "c:di:o:p:s:",
313                                         long_opts, NULL)) >= 0) {
314                         switch (c) {
315                         case 0:
316                                 /* Long options. */
317                                 break;
318                         case 'c':
319                                 stripe_count_arg = optarg;
320                                 break;
321                         case 'd':
322                                 /* delete the default striping pattern */
323                                 delete = 1;
324                                 break;
325                         case 'i':
326                         case 'o':
327                                 stripe_off_arg = optarg;
328                                 break;
329                         case 's':
330                                 stripe_size_arg = optarg;
331                                 break;
332                         case 'p':
333                                 pool_name_arg = optarg;
334                                 break;
335                         case '?':
336                                 return CMD_HELP;
337                         default:
338                                 fprintf(stderr, "error: %s: option '%s' "
339                                                 "unrecognized\n",
340                                                 argv[0], argv[optind - 1]);
341                                 return CMD_HELP;
342                         }
343                 }
344
345                 fname = argv[optind];
346
347                 if (delete &&
348                     (stripe_size_arg != NULL || stripe_off_arg != NULL ||
349                      stripe_count_arg != NULL || pool_name_arg != NULL)) {
350                         fprintf(stderr, "error: %s: cannot specify -d with "
351                                         "-s, -c -o or -p options\n",
352                                         argv[0]);
353                         return CMD_HELP;
354                 }
355         }
356
357         if (optind == argc) {
358                 fprintf(stderr, "error: %s: missing filename|dirname\n",
359                         argv[0]);
360                 return CMD_HELP;
361         }
362
363         /* get the stripe size */
364         if (stripe_size_arg != NULL) {
365                 result = parse_size(stripe_size_arg, &st_size, &size_units, 0);
366                 if (result) {
367                         fprintf(stderr, "error: %s: bad size '%s'\n",
368                                 argv[0], stripe_size_arg);
369                         return result;
370                 }
371         }
372         /* get the stripe offset */
373         if (stripe_off_arg != NULL) {
374                 st_offset = strtol(stripe_off_arg, &end, 0);
375                 if (*end != '\0') {
376                         fprintf(stderr, "error: %s: bad stripe offset '%s'\n",
377                                 argv[0], stripe_off_arg);
378                         return CMD_HELP;
379                 }
380         }
381         /* get the stripe count */
382         if (stripe_count_arg != NULL) {
383                 st_count = strtoul(stripe_count_arg, &end, 0);
384                 if (*end != '\0') {
385                         fprintf(stderr, "error: %s: bad stripe count '%s'\n",
386                                 argv[0], stripe_count_arg);
387                         return CMD_HELP;
388                 }
389         }
390
391         do {
392                 result = llapi_file_create_pool(fname, st_size, st_offset,
393                                                 st_count, 0, pool_name_arg);
394                 if (result) {
395                         fprintf(stderr,"error: %s: create stripe file '%s' "
396                                 "failed\n", argv[0], fname);
397                         break;
398                 }
399                 fname = argv[++optind];
400         } while (fname != NULL);
401
402         return result;
403 }
404
405 static int lfs_poollist(int argc, char **argv)
406 {
407         if (argc != 2)
408                 return CMD_HELP;
409
410         return llapi_poollist(argv[1]);
411 }
412
413 static int set_time(time_t *time, time_t *set, char *str)
414 {
415         time_t t;
416         int res = 0;
417
418         if (str[0] == '+')
419                 res = 1;
420         else if (str[0] == '-')
421                 res = -1;
422
423         if (res)
424                 str++;
425
426         t = strtol(str, NULL, 0);
427         if (*time < t * 24 * 60 * 60) {
428                 if (res)
429                         str--;
430                 fprintf(stderr, "Wrong time '%s' is specified.\n", str);
431                 return INT_MAX;
432         }
433
434         *set = *time - t * 24 * 60 * 60;
435         return res;
436 }
437
438 #define USER 0
439 #define GROUP 1
440
441 static int name2id(unsigned int *id, char *name, int type)
442 {
443         if (type == USER) {
444                 struct passwd *entry;
445
446                 if (!(entry = getpwnam(name))) {
447                         if (!errno)
448                                 errno = ENOENT;
449                         return -1;
450                 }
451
452                 *id = entry->pw_uid;
453         } else {
454                 struct group *entry;
455
456                 if (!(entry = getgrnam(name))) {
457                         if (!errno)
458                                 errno = ENOENT;
459                         return -1;
460                 }
461
462                 *id = entry->gr_gid;
463         }
464
465         return 0;
466 }
467
468 static int id2name(char **name, unsigned int id, int type)
469 {
470         if (type == USER) {
471                 struct passwd *entry;
472
473                 if (!(entry = getpwuid(id))) {
474                         if (!errno)
475                                 errno = ENOENT;
476                         return -1;
477                 }
478
479                 *name = entry->pw_name;
480         } else {
481                 struct group *entry;
482
483                 if (!(entry = getgrgid(id))) {
484                         if (!errno)
485                                 errno = ENOENT;
486                         return -1;
487                 }
488
489                 *name = entry->gr_name;
490         }
491
492         return 0;
493 }
494
495 #define FIND_POOL_OPT 3
496 static int lfs_find(int argc, char **argv)
497 {
498         int new_fashion = 1;
499         int c, ret;
500         time_t t;
501         struct find_param param = { .maxdepth = -1, .size_units = 0 };
502         struct option long_opts[] = {
503                 {"atime",     required_argument, 0, 'A'},
504                 {"ctime",     required_argument, 0, 'C'},
505                 {"maxdepth",  required_argument, 0, 'D'},
506                 {"gid",       required_argument, 0, 'g'},
507                 {"group",     required_argument, 0, 'G'},
508                 {"mtime",     required_argument, 0, 'M'},
509                 {"name",      required_argument, 0, 'n'},
510                 /* --obd is considered as a new option. */
511                 {"obd",       required_argument, 0, 'O'},
512                 {"ost",       required_argument, 0, 'O'},
513                 /* no short option for pool, p/P already used */
514                 {"pool",      required_argument, 0, FIND_POOL_OPT},
515                 {"print0",    no_argument,       0, 'p'},
516                 {"print",     no_argument,       0, 'P'},
517                 {"quiet",     no_argument,       0, 'q'},
518                 {"recursive", no_argument,       0, 'r'},
519                 {"size",      required_argument, 0, 's'},
520                 {"type",      required_argument, 0, 't'},
521                 {"uid",       required_argument, 0, 'u'},
522                 {"user",      required_argument, 0, 'U'},
523                 {"verbose",   no_argument,       0, 'v'},
524                 {0, 0, 0, 0}
525         };
526         int pathstart = -1;
527         int pathend = -1;
528         int neg_opt = 0;
529         time_t *xtime;
530         int *xsign;
531         int isoption;
532         char *endptr;
533
534         time(&t);
535
536         optind = 0;
537         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
538         while ((c = getopt_long_only(argc,argv,"-A:C:D:g:G:M:n:O:Ppqrs:t:u:U:v",
539                                      long_opts, NULL)) >= 0) {
540                 xtime = NULL;
541                 xsign = NULL;
542                 if (neg_opt)
543                         --neg_opt;
544                 /* '!' is part of option */
545                 /* when getopt_long_only() finds a string which is not
546                  * an option nor a known option argument it returns 1
547                  * in that case if we already have found pathstart and pathend
548                  * (i.e. we have the list of pathnames),
549                  * the only supported value is "!"
550                  */
551                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
552                 if (!isoption && pathend != -1) {
553                         fprintf(stderr, "err: %s: filename|dirname must either "
554                                         "precede options or follow options\n",
555                                         argv[0]);
556                         return CMD_HELP;
557                 }
558                 if (!isoption && pathstart == -1)
559                         pathstart = optind - 1;
560                 if (isoption && pathstart != -1 && pathend == -1) {
561                         pathend = optind - 2;
562                         if ((c == 1 && strcmp(optarg, "!") == 0) ||
563                             c == 'P' || c == 'p' || c == 'O' ||
564                             c == 'q' || c == 'r' || c == 'v')
565                                 pathend = optind - 1;
566                 }
567                 switch (c) {
568                 case 0:
569                         /* Long options. */
570                         break;
571                 case 1:
572                         /* unknown; opt is "!" or path component,
573                          * checking done above.
574                          */
575                         if (strcmp(optarg, "!") == 0)
576                                 neg_opt = 2;
577                         break;
578                 case 'A':
579                         xtime = &param.atime;
580                         xsign = &param.asign;
581                         param.exclude_atime = !!neg_opt;
582                 case 'C':
583                         if (c == 'C') {
584                                 xtime = &param.ctime;
585                                 xsign = &param.csign;
586                                 param.exclude_ctime = !!neg_opt;
587                         }
588                 case 'M':
589                         if (c == 'M') {
590                                 xtime = &param.mtime;
591                                 xsign = &param.msign;
592                                 param.exclude_mtime = !!neg_opt;
593                         }
594                         new_fashion = 1;
595                         ret = set_time(&t, xtime, optarg);
596                         if (ret == INT_MAX)
597                                 return -1;
598                         if (ret)
599                                 *xsign = ret;
600                         break;
601                 case 'D':
602                         new_fashion = 1;
603                         param.maxdepth = strtol(optarg, 0, 0);
604                         break;
605                 case 'g':
606                 case 'G':
607                         new_fashion = 1;
608                         ret = name2id(&param.gid, optarg, GROUP);
609                         if (ret) {
610                                 param.gid = strtoul(optarg, &endptr, 10);
611                                 if (*endptr != '\0') {
612                                         fprintf(stderr, "Group/GID: %s cannot "
613                                                 "be found.\n", optarg);
614                                         return -1;
615                                 }
616                         }
617                         param.exclude_gid = !!neg_opt;
618                         param.check_gid = 1;
619                         break;
620                 case 'u':
621                 case 'U':
622                         new_fashion = 1;
623                         ret = name2id(&param.uid, optarg, USER);
624                         if (ret) {
625                                 param.uid = strtoul(optarg, &endptr, 10);
626                                 if (*endptr != '\0') {
627                                         fprintf(stderr, "User/UID: %s cannot "
628                                                 "be found.\n", optarg);
629                                         return -1;
630                                 }
631                         }
632                         param.exclude_uid = !!neg_opt;
633                         param.check_uid = 1;
634                         break;
635                 case FIND_POOL_OPT:
636                         new_fashion = 1;
637                         if (strlen(optarg) > LOV_MAXPOOLNAME) {
638                                 fprintf(stderr,
639                                         "Pool name %s is too long"
640                                         " (max is %d)\n", optarg,
641                                         LOV_MAXPOOLNAME);
642                                 return -1;
643                         }
644                         /* we do check for empty pool because empty pool
645                          * is used to find V1 lov attributes */
646                         strncpy(param.poolname, optarg, LOV_MAXPOOLNAME);
647                         param.poolname[LOV_MAXPOOLNAME] = '\0';
648                         param.exclude_pool = !!neg_opt;
649                         param.check_pool = 1;
650                         break;
651                 case 'n':
652                         new_fashion = 1;
653                         param.pattern = (char *)optarg;
654                         param.exclude_pattern = !!neg_opt;
655                         break;
656                 case 'O': {
657                         char *buf, *token, *next, *p;
658                         int len;
659
660                         len = strlen((char *)optarg);
661                         buf = malloc(len+1);
662                         if (buf == NULL)
663                                 return -ENOMEM;
664                         strcpy(buf, (char *)optarg);
665
666                         param.exclude_obd = !!neg_opt;
667
668                         if (param.num_alloc_obds == 0) {
669                                 param.obduuid = malloc(FIND_MAX_OSTS *
670                                                        sizeof(struct obd_uuid));
671                                 if (param.obduuid == NULL)
672                                         return -ENOMEM;
673                                 param.num_alloc_obds = INIT_ALLOC_NUM_OSTS;
674                         }
675
676                         for (token = buf; token && *token; token = next) {
677                                 p = strchr(token, ',');
678                                 next = 0;
679                                 if (p) {
680                                         *p = 0;
681                                         next = p+1;
682                                 }
683                                 strcpy((char *)&param.obduuid[param.num_obds++].uuid,
684                                        token);
685                         }
686
687                         if (buf)
688                                 free(buf);
689                         break;
690                 }
691                 case 'p':
692                         new_fashion = 1;
693                         param.zeroend = 1;
694                         break;
695                 case 'P':
696                         break;
697                 case 'q':
698                         new_fashion = 0;
699                         param.quiet++;
700                         param.verbose = 0;
701                         break;
702                 case 'r':
703                         new_fashion = 0;
704                         param.recursive = 1;
705                         break;
706                 case 't':
707                         param.exclude_type = !!neg_opt;
708                         switch(optarg[0]) {
709                         case 'b': param.type = S_IFBLK; break;
710                         case 'c': param.type = S_IFCHR; break;
711                         case 'd': param.type = S_IFDIR; break;
712                         case 'f': param.type = S_IFREG; break;
713                         case 'l': param.type = S_IFLNK; break;
714                         case 'p': param.type = S_IFIFO; break;
715                         case 's': param.type = S_IFSOCK; break;
716 #ifdef S_IFDOOR /* Solaris only */
717                         case 'D': param.type = S_IFDOOR; break;
718 #endif
719                         default: fprintf(stderr, "error: %s: bad type '%s'\n",
720                                          argv[0], optarg);
721                                  return CMD_HELP;
722                         };
723                         break;
724                 case 's':
725                         if (optarg[0] == '+')
726                                 param.size_sign = -1;
727                         else if (optarg[0] == '-')
728                                 param.size_sign = +1;
729
730                         if (param.size_sign)
731                                 optarg++;
732                         ret = parse_size(optarg, &param.size,
733                                          &param.size_units, 0);
734                         if (ret) {
735                                 fprintf(stderr,"error: bad size '%s'\n",
736                                         optarg);
737                                 return ret;
738                         }
739                         param.check_size = 1;
740                         param.exclude_size = !!neg_opt;
741                         break;
742                 case 'v':
743                         new_fashion = 0;
744                         param.verbose++;
745                         param.quiet = 0;
746                         break;
747                 case '?':
748                         return CMD_HELP;
749                 default:
750                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
751                                 argv[0], argv[optind - 1]);
752                         return CMD_HELP;
753                 };
754         }
755
756         if (pathstart == -1) {
757                 fprintf(stderr, "error: %s: no filename|pathname\n",
758                         argv[0]);
759                 return CMD_HELP;
760         } else if (pathend == -1) {
761                 /* no options */
762                 pathend = argc;
763         }
764
765         if (new_fashion) {
766                 param.quiet = 1;
767         } else {
768                 static int deprecated_warning;
769                 if (!deprecated_warning) {
770                         fprintf(stderr, "lfs find: -q, -r, -v options "
771                                 "deprecated.  Use 'lfs getstripe' instead.\n");
772                         deprecated_warning = 1;
773                 }
774                 if (!param.recursive && param.maxdepth == -1)
775                         param.maxdepth = 1;
776         }
777
778         do {
779                 if (new_fashion)
780                         ret = llapi_find(argv[pathstart], &param);
781                 else
782                         ret = llapi_getstripe(argv[pathstart], &param);
783         } while (++pathstart < pathend && !ret);
784
785         if (ret)
786                 fprintf(stderr, "error: %s failed for %s.\n",
787                         argv[0], argv[optind - 1]);
788
789         if (param.obduuid && param.num_alloc_obds)
790                 free(param.obduuid);
791
792         return ret;
793 }
794
795 static int lfs_getstripe(int argc, char **argv)
796 {
797         struct option long_opts[] = {
798                 {"count", 0, 0, 'c'},
799                 {"directory", 0, 0, 'd'},
800                 {"index", 0, 0, 'i'},
801                 {"mdt", 0, 0, 'M'},
802                 {"offset", 0, 0, 'o'},
803                 {"obd", 1, 0, 'O'},
804                 {"pool", 0, 0, 'p'},
805                 {"quiet", 0, 0, 'q'},
806                 {"recursive", 0, 0, 'r'},
807                 {"raw", 0, 0, 'R'},
808                 {"size", 0, 0, 's'},
809                 {"verbose", 0, 0, 'v'},
810                 {0, 0, 0, 0}
811         };
812         int c, rc;
813         struct find_param param = { 0 };
814
815         param.maxdepth = 1;
816         optind = 0;
817         while ((c = getopt_long(argc, argv, "cdhiMoO:pqrRsv",
818                                 long_opts, NULL)) != -1) {
819                 switch (c) {
820                 case 'O':
821                         if (param.obduuid) {
822                                 fprintf(stderr,
823                                         "error: %s: only one obduuid allowed",
824                                         argv[0]);
825                                 return CMD_HELP;
826                         }
827                         param.obduuid = (struct obd_uuid *)optarg;
828                         break;
829                 case 'q':
830                         param.quiet++;
831                         break;
832                 case 'd':
833                         param.maxdepth = 0;
834                         break;
835                 case 'r':
836                         param.recursive = 1;
837                         break;
838                 case 'v':
839                         param.verbose = VERBOSE_ALL | VERBOSE_DETAIL;
840                         break;
841                 case 'c':
842                         if (!(param.verbose & VERBOSE_DETAIL)) {
843                                 param.verbose |= VERBOSE_COUNT;
844                                 param.maxdepth = 0;
845                         }
846                         break;
847                 case 's':
848                         if (!(param.verbose & VERBOSE_DETAIL)) {
849                                 param.verbose |= VERBOSE_SIZE;
850                                 param.maxdepth = 0;
851                         }
852                         break;
853                 case 'i':
854                 case 'o':
855                         if (!(param.verbose & VERBOSE_DETAIL)) {
856                                 param.verbose |= VERBOSE_OFFSET;
857                                 param.maxdepth = 0;
858                         }
859                         break;
860                 case 'p':
861                         if (!(param.verbose & VERBOSE_DETAIL)) {
862                                 param.verbose |= VERBOSE_POOL;
863                                 param.maxdepth = 0;
864                         }
865                         break;
866                 case 'M':
867                         param.get_mdt_index = 1;
868                         break;
869                 case 'R':
870                         param.raw = 1;
871                         break;
872                 case '?':
873                         return CMD_HELP;
874                 default:
875                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
876                                 argv[0], argv[optind - 1]);
877                         return CMD_HELP;
878                 }
879         }
880
881         if (optind >= argc)
882                 return CMD_HELP;
883
884         if (param.recursive)
885                 param.maxdepth = -1;
886
887         if (!param.verbose)
888                 param.verbose = VERBOSE_ALL;
889         if (param.quiet)
890                 param.verbose = VERBOSE_OBJID;
891
892         do {
893                 rc = llapi_getstripe(argv[optind], &param);
894         } while (++optind < argc && !rc);
895
896         if (rc)
897                 fprintf(stderr, "error: %s failed for %s.\n",
898                         argv[0], argv[optind - 1]);
899         return rc;
900 }
901
902 static int lfs_osts(int argc, char **argv)
903 {
904         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
905         struct find_param param;
906         int index = 0, rc=0;
907
908         if (argc > 2)
909                 return CMD_HELP;
910
911         if (argc == 2 && !realpath(argv[1], path)) {
912                 rc = -errno;
913                 fprintf(stderr, "error: invalid path '%s': %s\n",
914                         argv[1], strerror(-rc));
915                 return rc;
916         }
917
918         while (!llapi_search_mounts(path, index++, mntdir, NULL)) {
919                 /* Check if we have a mount point */
920                 if (mntdir[0] == '\0')
921                         continue;
922
923                 memset(&param, 0, sizeof(param));
924                 rc = llapi_ostlist(mntdir, &param);
925                 if (rc) {
926                         fprintf(stderr, "error: %s: failed on %s\n",
927                                 argv[0], mntdir);
928                 }
929                 if (path[0] != '\0')
930                         break;
931                 memset(mntdir, 0, PATH_MAX);
932         }
933
934         return rc;
935 }
936
937 #define COOK(value)                                                     \
938 ({                                                                      \
939         int radix = 0;                                                  \
940         while (value > 1024) {                                          \
941                 value /= 1024;                                          \
942                 radix++;                                                \
943         }                                                               \
944         radix;                                                          \
945 })
946 #define UUF     "%-20s"
947 #define CSF     "%11s"
948 #define CDF     "%11llu"
949 #define HDF     "%8.1f%c"
950 #define RSF     "%4s"
951 #define RDF     "%3d%%"
952
953 static int showdf(char *mntdir, struct obd_statfs *stat,
954                   char *uuid, int ishow, int cooked,
955                   char *type, int index, int rc)
956 {
957         long long avail, used, total;
958         double ratio = 0;
959         char *suffix = "KMGTPEZY";
960         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
961         char tbuf[20], ubuf[20], abuf[20], rbuf[20];
962
963         if (!uuid || !stat)
964                 return -EINVAL;
965
966         switch (rc) {
967         case 0:
968                 if (ishow) {
969                         avail = stat->os_ffree;
970                         used = stat->os_files - stat->os_ffree;
971                         total = stat->os_files;
972                 } else {
973                         int shift = cooked ? 0 : 10;
974
975                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
976                         used  = ((stat->os_blocks - stat->os_bfree) *
977                                  stat->os_bsize) >> shift;
978                         total = (stat->os_blocks * stat->os_bsize) >> shift;
979                 }
980
981                 if ((used + avail) > 0)
982                         ratio = (double)used / (double)(used + avail);
983
984                 if (cooked) {
985                         int i;
986                         double cook_val;
987
988                         cook_val = (double)total;
989                         i = COOK(cook_val);
990                         if (i > 0)
991                                 sprintf(tbuf, HDF, cook_val, suffix[i - 1]);
992                         else
993                                 sprintf(tbuf, CDF, total);
994
995                         cook_val = (double)used;
996                         i = COOK(cook_val);
997                         if (i > 0)
998                                 sprintf(ubuf, HDF, cook_val, suffix[i - 1]);
999                         else
1000                                 sprintf(ubuf, CDF, used);
1001
1002                         cook_val = (double)avail;
1003                         i = COOK(cook_val);
1004                         if (i > 0)
1005                                 sprintf(abuf, HDF, cook_val, suffix[i - 1]);
1006                         else
1007                                 sprintf(abuf, CDF, avail);
1008                 } else {
1009                         sprintf(tbuf, CDF, total);
1010                         sprintf(ubuf, CDF, used);
1011                         sprintf(abuf, CDF, avail);
1012                 }
1013
1014                 sprintf(rbuf, RDF, (int)(ratio * 100 + 0.5));
1015                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
1016                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
1017                 if (type)
1018                         printf("[%s:%d]\n", type, index);
1019                 else
1020                         printf("\n");
1021
1022                 break;
1023         case -ENODATA:
1024                 printf(UUF": inactive device\n", uuid);
1025                 break;
1026         default:
1027                 printf(UUF": %s\n", uuid, strerror(-rc));
1028                 break;
1029         }
1030
1031         return 0;
1032 }
1033
1034 struct ll_stat_type {
1035         int   st_op;
1036         char *st_name;
1037 };
1038
1039 static int mntdf(char *mntdir, char *fsname, char *pool, int ishow, int cooked)
1040 {
1041         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
1042         struct obd_uuid uuid_buf;
1043         char *poolname = NULL;
1044         struct ll_stat_type types[] = { { LL_STATFS_MDC, "MDT" },
1045                                         { LL_STATFS_LOV, "OST" },
1046                                         { 0, NULL } };
1047         struct ll_stat_type *tp;
1048         __u32 index;
1049         int rc;
1050
1051         if (pool) {
1052                 poolname = strchr(pool, '.');
1053                 if (poolname != NULL) {
1054                         if (strncmp(fsname, pool, strlen(fsname))) {
1055                                 fprintf(stderr, "filesystem name incorrect\n");
1056                                 return -ENODEV;
1057                         }
1058                         poolname++;
1059                 } else
1060                         poolname = pool;
1061         }
1062
1063         if (ishow)
1064                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
1065                        "UUID", "Inodes", "IUsed", "IFree",
1066                        "IUse%", "Mounted on");
1067         else
1068                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
1069                        "UUID", cooked ? "bytes" : "1K-blocks",
1070                        "Used", "Available", "Use%", "Mounted on");
1071
1072         for (tp = types; tp->st_name != NULL; tp++) {
1073                 for (index = 0; ; index++) {
1074                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
1075                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
1076                         rc = llapi_obd_statfs(mntdir, tp->st_op, index,
1077                                               &stat_buf, &uuid_buf);
1078                         if (rc == -ENODEV)
1079                                 break;
1080
1081                         if (poolname && tp->st_op == LL_STATFS_LOV &&
1082                             llapi_search_ost(fsname, poolname,
1083                                              obd_uuid2str(&uuid_buf)) != 1)
1084                                 continue;
1085
1086                         /* the llapi_obd_statfs() call may have returned with
1087                          * an error, but if it filled in uuid_buf we will at
1088                          * lease use that to print out a message for that OBD.
1089                          * If we didn't get anything in the uuid_buf, then fill
1090                          * it in so that we can print an error message. */
1091                         if (uuid_buf.uuid[0] == '\0')
1092                                 sprintf(uuid_buf.uuid, "%s%04x",
1093                                         tp->st_name, index);
1094                         showdf(mntdir,&stat_buf,obd_uuid2str(&uuid_buf),
1095                                ishow, cooked, tp->st_name, index, rc);
1096
1097                         if (rc == 0) {
1098                                 if (tp->st_op == LL_STATFS_MDC) {
1099                                         sum.os_ffree += stat_buf.os_ffree;
1100                                         sum.os_files += stat_buf.os_files;
1101                                 } else /* if (tp->st_op == LL_STATFS_LOV) */ {
1102                                         sum.os_blocks += stat_buf.os_blocks *
1103                                                 stat_buf.os_bsize;
1104                                         sum.os_bfree  += stat_buf.os_bfree *
1105                                                 stat_buf.os_bsize;
1106                                         sum.os_bavail += stat_buf.os_bavail *
1107                                                 stat_buf.os_bsize;
1108                                 }
1109                         } else if (rc == -EINVAL || rc == -EFAULT) {
1110                                 break;
1111                         }
1112                 }
1113         }
1114
1115         printf("\n");
1116         showdf(mntdir, &sum, "filesystem summary:", ishow, cooked, NULL, 0,0);
1117         printf("\n");
1118         return 0;
1119 }
1120
1121 static int lfs_df(int argc, char **argv)
1122 {
1123         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
1124         int ishow = 0, cooked = 0;
1125         int c, rc = 0, index = 0;
1126         char fsname[PATH_MAX] = "", *pool_name = NULL;
1127         struct option long_opts[] = {
1128                 {"pool", required_argument, 0, 'p'},
1129                 {0, 0, 0, 0}
1130         };
1131
1132         optind = 0;
1133         while ((c = getopt_long(argc, argv, "hip:", long_opts, NULL)) != -1) {
1134                 switch (c) {
1135                 case 'i':
1136                         ishow = 1;
1137                         break;
1138                 case 'h':
1139                         cooked = 1;
1140                         break;
1141                 case 'p':
1142                         pool_name = optarg;
1143                         break;
1144                 default:
1145                         return CMD_HELP;
1146                 }
1147         }
1148         if (optind < argc && !realpath(argv[optind], path)) {
1149                 rc = -errno;
1150                 fprintf(stderr, "error: invalid path '%s': %s\n",
1151                         argv[optind], strerror(-rc));
1152                 return rc;
1153         }
1154
1155         while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
1156                 /* Check if we have a mount point */
1157                 if (mntdir[0] == '\0')
1158                         continue;
1159
1160                 rc = mntdf(mntdir, fsname, pool_name, ishow, cooked);
1161                 if (rc || path[0] != '\0')
1162                         break;
1163                 fsname[0] = '\0'; /* avoid matching in next loop */
1164                 mntdir[0] = '\0'; /* avoid matching in next loop */
1165         }
1166
1167         return rc;
1168 }
1169
1170 static int lfs_getname(int argc, char **argv)
1171 {
1172         char mntdir[PATH_MAX] = "", path[PATH_MAX] = "", fsname[PATH_MAX] = "";
1173         int rc = 0, index = 0, c;
1174         char buf[sizeof(struct obd_uuid)];
1175
1176         optind = 0;
1177         while ((c = getopt(argc, argv, "h")) != -1)
1178                 return CMD_HELP;
1179
1180         if (optind == argc) { /* no paths specified, get all paths. */
1181                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
1182                         rc = llapi_getname(mntdir, buf, sizeof(buf));
1183                         if (rc < 0) {
1184                                 fprintf(stderr,
1185                                         "cannot get name for `%s': %s\n",
1186                                         mntdir, strerror(-rc));
1187                                 break;
1188                         }
1189
1190                         printf("%s %s\n", buf, mntdir);
1191
1192                         path[0] = fsname[0] = mntdir[0] = 0;
1193                 }
1194         } else { /* paths specified, only attempt to search these. */
1195                 for (; optind < argc; optind++) {
1196                         rc = llapi_getname(argv[optind], buf, sizeof(buf));
1197                         if (rc < 0) {
1198                                 fprintf(stderr,
1199                                         "cannot get name for `%s': %s\n",
1200                                         argv[optind], strerror(-rc));
1201                                 break;
1202                         }
1203
1204                         printf("%s %s\n", buf, argv[optind]);
1205                 }
1206         }
1207         return rc;
1208 }
1209
1210 static int lfs_check(int argc, char **argv)
1211 {
1212         int rc;
1213         char mntdir[PATH_MAX] = {'\0'};
1214         int num_types = 1;
1215         char *obd_types[2];
1216         char obd_type1[4];
1217         char obd_type2[4];
1218
1219         if (argc != 2)
1220                 return CMD_HELP;
1221
1222         obd_types[0] = obd_type1;
1223         obd_types[1] = obd_type2;
1224
1225         if (strcmp(argv[1], "osts") == 0) {
1226                 strcpy(obd_types[0], "osc");
1227         } else if (strcmp(argv[1], "mds") == 0) {
1228                 strcpy(obd_types[0], "mdc");
1229         } else if (strcmp(argv[1], "servers") == 0) {
1230                 num_types = 2;
1231                 strcpy(obd_types[0], "osc");
1232                 strcpy(obd_types[1], "mdc");
1233         } else {
1234                 fprintf(stderr, "error: %s: option '%s' unrecognized\n",
1235                                 argv[0], argv[1]);
1236                         return CMD_HELP;
1237         }
1238
1239         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
1240         if (rc < 0 || mntdir[0] == '\0') {
1241                 fprintf(stderr, "No suitable Lustre mount found\n");
1242                 return rc;
1243         }
1244
1245         rc = llapi_target_iterate(num_types, obd_types,
1246                                   mntdir, llapi_ping_target);
1247
1248         if (rc)
1249                 fprintf(stderr, "error: %s: %s status failed\n",
1250                                 argv[0],argv[1]);
1251
1252         return rc;
1253
1254 }
1255
1256 static int lfs_catinfo(int argc, char **argv)
1257 {
1258         char mntdir[PATH_MAX] = {'\0'};
1259         int rc;
1260
1261         if (argc < 2 || (!strcmp(argv[1],"config") && argc < 3))
1262                 return CMD_HELP;
1263
1264         if (strcmp(argv[1], "config") && strcmp(argv[1], "deletions"))
1265                 return CMD_HELP;
1266
1267         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
1268         if (rc == 0 && mntdir[0] != '\0') {
1269                 if (argc == 3)
1270                         rc = llapi_catinfo(mntdir, argv[1], argv[2]);
1271                 else
1272                         rc = llapi_catinfo(mntdir, argv[1], NULL);
1273         } else {
1274                 fprintf(stderr, "no lustre_lite mounted.\n");
1275                 rc = -1;
1276         }
1277
1278         return rc;
1279 }
1280
1281 static int lfs_join(int argc, char **argv)
1282 {
1283         fprintf(stderr, "join two lustre files into one.\n"
1284                         "obsolete, HEAD does not support it anymore.\n");
1285         return 0;
1286 }
1287
1288 #ifdef HAVE_SYS_QUOTA_H
1289 static int lfs_quotachown(int argc, char **argv)
1290 {
1291
1292         int c,rc;
1293         int flag = 0;
1294
1295         optind = 0;
1296         while ((c = getopt(argc, argv, "i")) != -1) {
1297                 switch (c) {
1298                 case 'i':
1299                         flag++;
1300                         break;
1301                 default:
1302                         fprintf(stderr, "error: %s: option '-%c' "
1303                                         "unrecognized\n", argv[0], c);
1304                         return CMD_HELP;
1305                 }
1306         }
1307         if (optind == argc)
1308                 return CMD_HELP;
1309         rc = llapi_quotachown(argv[optind], flag);
1310         if(rc)
1311                 fprintf(stderr,"error: change file owner/group failed.\n");
1312         return rc;
1313 }
1314
1315 static int lfs_quotacheck(int argc, char **argv)
1316 {
1317         int c, check_type = 0;
1318         char *mnt;
1319         struct if_quotacheck qchk;
1320         struct if_quotactl qctl;
1321         char *obd_type = (char *)qchk.obd_type;
1322         int rc;
1323
1324         memset(&qchk, 0, sizeof(qchk));
1325
1326         optind = 0;
1327         while ((c = getopt(argc, argv, "gu")) != -1) {
1328                 switch (c) {
1329                 case 'u':
1330                         check_type |= 0x01;
1331                         break;
1332                 case 'g':
1333                         check_type |= 0x02;
1334                         break;
1335                 default:
1336                         fprintf(stderr, "error: %s: option '-%c' "
1337                                         "unrecognized\n", argv[0], c);
1338                         return CMD_HELP;
1339                 }
1340         }
1341
1342         if (check_type)
1343                 check_type--;
1344         else    /* do quotacheck for both user & group quota by default */
1345                 check_type = 0x02;
1346
1347         if (argc == optind)
1348                 return CMD_HELP;
1349
1350         mnt = argv[optind];
1351
1352         rc = llapi_quotacheck(mnt, check_type);
1353         if (rc) {
1354                 fprintf(stderr, "quotacheck failed: %s\n", strerror(-rc));
1355                 return rc;
1356         }
1357
1358         rc = llapi_poll_quotacheck(mnt, &qchk);
1359         if (rc) {
1360                 if (*obd_type)
1361                         fprintf(stderr, "%s %s ", obd_type,
1362                                 obd_uuid2str(&qchk.obd_uuid));
1363                 fprintf(stderr, "quota check failed: %s\n", strerror(-rc));
1364                 return rc;
1365         }
1366
1367         memset(&qctl, 0, sizeof(qctl));
1368         qctl.qc_cmd = LUSTRE_Q_QUOTAON;
1369         qctl.qc_type = check_type;
1370         rc = llapi_quotactl(mnt, &qctl);
1371         if (rc && rc != -EALREADY) {
1372                 if (*obd_type)
1373                         fprintf(stderr, "%s %s ", (char *)qctl.obd_type,
1374                                 obd_uuid2str(&qctl.obd_uuid));
1375                 fprintf(stderr, "%s turn on quota failed: %s\n",
1376                         argv[0], strerror(-rc));
1377                 return rc;
1378         }
1379
1380         return 0;
1381 }
1382
1383 static int lfs_quotaon(int argc, char **argv)
1384 {
1385         int c;
1386         char *mnt;
1387         struct if_quotactl qctl;
1388         char *obd_type = (char *)qctl.obd_type;
1389         int rc;
1390
1391         memset(&qctl, 0, sizeof(qctl));
1392         qctl.qc_cmd = LUSTRE_Q_QUOTAON;
1393
1394         optind = 0;
1395         while ((c = getopt(argc, argv, "fgu")) != -1) {
1396                 switch (c) {
1397                 case 'u':
1398                         qctl.qc_type |= 0x01;
1399                         break;
1400                 case 'g':
1401                         qctl.qc_type |= 0x02;
1402                         break;
1403                 case 'f':
1404                         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
1405                         break;
1406                 default:
1407                         fprintf(stderr, "error: %s: option '-%c' "
1408                                         "unrecognized\n", argv[0], c);
1409                         return CMD_HELP;
1410                 }
1411         }
1412
1413         if (qctl.qc_type)
1414                 qctl.qc_type--;
1415         else /* by default, enable quota for both user & group */
1416                 qctl.qc_type = 0x02;
1417
1418         if (argc == optind)
1419                 return CMD_HELP;
1420
1421         mnt = argv[optind];
1422
1423         rc = llapi_quotactl(mnt, &qctl);
1424         if (rc) {
1425                 if (rc == -EALREADY) {
1426                         rc = 0;
1427                 } else if (rc == -ENOENT) {
1428                         fprintf(stderr, "error: cannot find quota database, "
1429                                         "make sure you have run quotacheck\n");
1430                 } else {
1431                         if (*obd_type)
1432                                 fprintf(stderr, "%s %s ", obd_type,
1433                                         obd_uuid2str(&qctl.obd_uuid));
1434                         fprintf(stderr, "%s failed: %s\n", argv[0],
1435                                 strerror(-rc));
1436                 }
1437         }
1438
1439         return rc;
1440 }
1441
1442 static int lfs_quotaoff(int argc, char **argv)
1443 {
1444         int c;
1445         char *mnt;
1446         struct if_quotactl qctl;
1447         char *obd_type = (char *)qctl.obd_type;
1448         int rc;
1449
1450         memset(&qctl, 0, sizeof(qctl));
1451         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
1452
1453         optind = 0;
1454         while ((c = getopt(argc, argv, "gu")) != -1) {
1455                 switch (c) {
1456                 case 'u':
1457                         qctl.qc_type |= 0x01;
1458                         break;
1459                 case 'g':
1460                         qctl.qc_type |= 0x02;
1461                         break;
1462                 default:
1463                         fprintf(stderr, "error: %s: option '-%c' "
1464                                         "unrecognized\n", argv[0], c);
1465                         return CMD_HELP;
1466                 }
1467         }
1468
1469         if (qctl.qc_type)
1470                 qctl.qc_type--;
1471         else /* by default, disable quota for both user & group */
1472                 qctl.qc_type = 0x02;
1473
1474         if (argc == optind)
1475                 return CMD_HELP;
1476
1477         mnt = argv[optind];
1478
1479         rc = llapi_quotactl(mnt, &qctl);
1480         if (rc) {
1481                 if (rc == -EALREADY) {
1482                         rc = 0;
1483                 } else {
1484                         if (*obd_type)
1485                                 fprintf(stderr, "%s %s ", obd_type,
1486                                         obd_uuid2str(&qctl.obd_uuid));
1487                         fprintf(stderr, "quotaoff failed: %s\n",
1488                                 strerror(-rc));
1489                 }
1490         }
1491
1492         return rc;
1493 }
1494
1495 static int lfs_quotainv(int argc, char **argv)
1496 {
1497         int c;
1498         char *mnt;
1499         struct if_quotactl qctl;
1500         int rc;
1501
1502         memset(&qctl, 0, sizeof(qctl));
1503         qctl.qc_cmd = LUSTRE_Q_INVALIDATE;
1504
1505         optind = 0;
1506         while ((c = getopt(argc, argv, "fgu")) != -1) {
1507                 switch (c) {
1508                 case 'u':
1509                         qctl.qc_type |= 0x01;
1510                         break;
1511                 case 'g':
1512                         qctl.qc_type |= 0x02;
1513                         break;
1514                 case 'f':
1515                         qctl.qc_cmd = LUSTRE_Q_FINVALIDATE;
1516                         break;
1517                 default:
1518                         fprintf(stderr, "error: %s: option '-%c' "
1519                                         "unrecognized\n", argv[0], c);
1520                         return CMD_HELP;
1521                 }
1522         }
1523
1524         if (qctl.qc_type)
1525                 qctl.qc_type--;
1526         else /* by default, invalidate quota for both user & group */
1527                 qctl.qc_type = 0x02;
1528
1529         if (argc == optind)
1530                 return CMD_HELP;
1531
1532         mnt = argv[optind];
1533
1534         rc = llapi_quotactl(mnt, &qctl);
1535         if (rc) {
1536                 fprintf(stderr, "quotainv failed: %s\n", strerror(-rc));
1537                 return rc;
1538         }
1539
1540         return 0;
1541 }
1542
1543 #define ARG2INT(nr, str, msg)                                           \
1544 do {                                                                    \
1545         char *endp;                                                     \
1546         nr = strtol(str, &endp, 0);                                     \
1547         if (*endp) {                                                    \
1548                 fprintf(stderr, "error: bad %s: %s\n", msg, str);       \
1549                 return CMD_HELP;                                        \
1550         }                                                               \
1551 } while (0)
1552
1553 #define ADD_OVERFLOW(a,b) ((a + b) < a) ? (a = ULONG_MAX) : (a = a + b)
1554
1555 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
1556  * returns the value or ULONG_MAX on integer overflow or incorrect format
1557  * Notes:
1558  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
1559  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
1560  *        3. empty integer value is interpreted as 0
1561  */
1562 static unsigned long str2sec(const char* timestr)
1563 {
1564         const char spec[] = "smhdw";
1565         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
1566         unsigned long val = 0;
1567         char *tail;
1568
1569         if (strpbrk(timestr, spec) == NULL) {
1570                 /* no specifiers inside the time string,
1571                    should treat it as an integer value */
1572                 val = strtoul(timestr, &tail, 10);
1573                 return *tail ? ULONG_MAX : val;
1574         }
1575
1576         /* format string is XXwXXdXXhXXmXXs */
1577         while (*timestr) {
1578                 unsigned long v;
1579                 int ind;
1580                 char* ptr;
1581
1582                 v = strtoul(timestr, &tail, 10);
1583                 if (v == ULONG_MAX || *tail == '\0')
1584                         /* value too large (ULONG_MAX or more)
1585                            or missing specifier */
1586                         goto error;
1587
1588                 ptr = strchr(spec, *tail);
1589                 if (ptr == NULL)
1590                         /* unknown specifier */
1591                         goto error;
1592
1593                 ind = ptr - spec;
1594
1595                 /* check if product will overflow the type */
1596                 if (!(v < ULONG_MAX / mult[ind]))
1597                         goto error;
1598
1599                 ADD_OVERFLOW(val, mult[ind] * v);
1600                 if (val == ULONG_MAX)
1601                         goto error;
1602
1603                 timestr = tail + 1;
1604         }
1605
1606         return val;
1607
1608 error:
1609         return ULONG_MAX;
1610 }
1611
1612 #define ARG2ULL(nr, str, def_units)                                     \
1613 do {                                                                    \
1614         unsigned long long limit, units = def_units;                    \
1615         int rc;                                                         \
1616                                                                         \
1617         rc = parse_size(str, &limit, &units, 1);                        \
1618         if (rc < 0) {                                                   \
1619                 fprintf(stderr, "error: bad limit value %s\n", str);    \
1620                 return CMD_HELP;                                        \
1621         }                                                               \
1622         nr = limit;                                                     \
1623 } while (0)
1624
1625 static inline int has_times_option(int argc, char **argv)
1626 {
1627         int i;
1628
1629         for (i = 1; i < argc; i++)
1630                 if (!strcmp(argv[i], "-t"))
1631                         return 1;
1632
1633         return 0;
1634 }
1635
1636 int lfs_setquota_times(int argc, char **argv)
1637 {
1638         int c, rc;
1639         struct if_quotactl qctl;
1640         char *mnt, *obd_type = (char *)qctl.obd_type;
1641         struct obd_dqblk *dqb = &qctl.qc_dqblk;
1642         struct obd_dqinfo *dqi = &qctl.qc_dqinfo;
1643         struct option long_opts[] = {
1644                 {"block-grace",     required_argument, 0, 'b'},
1645                 {"group",           no_argument,       0, 'g'},
1646                 {"inode-grace",     required_argument, 0, 'i'},
1647                 {"times",           no_argument,       0, 't'},
1648                 {"user",            no_argument,       0, 'u'},
1649                 {0, 0, 0, 0}
1650         };
1651
1652         memset(&qctl, 0, sizeof(qctl));
1653         qctl.qc_cmd  = LUSTRE_Q_SETINFO;
1654         qctl.qc_type = UGQUOTA;
1655
1656         optind = 0;
1657         while ((c = getopt_long(argc, argv, "b:gi:tu", long_opts, NULL)) != -1) {
1658                 switch (c) {
1659                 case 'u':
1660                 case 'g':
1661                         if (qctl.qc_type != UGQUOTA) {
1662                                 fprintf(stderr, "error: -u and -g can't be used "
1663                                                 "more than once\n");
1664                                 return CMD_HELP;
1665                         }
1666                         qctl.qc_type = (c == 'u') ? USRQUOTA : GRPQUOTA;
1667                         break;
1668                 case 'b':
1669                         if ((dqi->dqi_bgrace = str2sec(optarg)) == ULONG_MAX) {
1670                                 fprintf(stderr, "error: bad block-grace: %s\n",
1671                                         optarg);
1672                                 return CMD_HELP;
1673                         }
1674                         dqb->dqb_valid |= QIF_BTIME;
1675                         break;
1676                 case 'i':
1677                         if ((dqi->dqi_igrace = str2sec(optarg)) == ULONG_MAX) {
1678                                 fprintf(stderr, "error: bad inode-grace: %s\n",
1679                                         optarg);
1680                                 return CMD_HELP;
1681                         }
1682                         dqb->dqb_valid |= QIF_ITIME;
1683                         break;
1684                 case 't': /* Yes, of course! */
1685                         break;
1686                 default: /* getopt prints error message for us when opterr != 0 */
1687                         return CMD_HELP;
1688                 }
1689         }
1690
1691         if (qctl.qc_type == UGQUOTA) {
1692                 fprintf(stderr, "error: neither -u nor -g specified\n");
1693                 return CMD_HELP;
1694         }
1695
1696         if (optind != argc - 1) {
1697                 fprintf(stderr, "error: unexpected parameters encountered\n");
1698                 return CMD_HELP;
1699         }
1700
1701         mnt = argv[optind];
1702         rc = llapi_quotactl(mnt, &qctl);
1703         if (rc) {
1704                 if (*obd_type)
1705                         fprintf(stderr, "%s %s ", obd_type,
1706                                 obd_uuid2str(&qctl.obd_uuid));
1707                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
1708                 return rc;
1709         }
1710
1711         return 0;
1712 }
1713
1714 #define BSLIMIT (1 << 0)
1715 #define BHLIMIT (1 << 1)
1716 #define ISLIMIT (1 << 2)
1717 #define IHLIMIT (1 << 3)
1718
1719 int lfs_setquota(int argc, char **argv)
1720 {
1721         int c, rc;
1722         struct if_quotactl qctl;
1723         char *mnt, *obd_type = (char *)qctl.obd_type;
1724         struct obd_dqblk *dqb = &qctl.qc_dqblk;
1725         struct option long_opts[] = {
1726                 {"block-softlimit", required_argument, 0, 'b'},
1727                 {"block-hardlimit", required_argument, 0, 'B'},
1728                 {"group",           required_argument, 0, 'g'},
1729                 {"inode-softlimit", required_argument, 0, 'i'},
1730                 {"inode-hardlimit", required_argument, 0, 'I'},
1731                 {"user",            required_argument, 0, 'u'},
1732                 {0, 0, 0, 0}
1733         };
1734         unsigned limit_mask = 0;
1735         char *endptr;
1736
1737         if (has_times_option(argc, argv))
1738                 return lfs_setquota_times(argc, argv);
1739
1740         memset(&qctl, 0, sizeof(qctl));
1741         qctl.qc_cmd  = LUSTRE_Q_SETQUOTA;
1742         qctl.qc_type = UGQUOTA; /* UGQUOTA makes no sense for setquota,
1743                                  * so it can be used as a marker that qc_type
1744                                  * isn't reinitialized from command line */
1745
1746         optind = 0;
1747         while ((c = getopt_long(argc, argv, "b:B:g:i:I:u:", long_opts, NULL)) != -1) {
1748                 switch (c) {
1749                 case 'u':
1750                 case 'g':
1751                         if (qctl.qc_type != UGQUOTA) {
1752                                 fprintf(stderr, "error: -u and -g can't be used"
1753                                                 " more than once\n");
1754                                 return CMD_HELP;
1755                         }
1756                         qctl.qc_type = (c == 'u') ? USRQUOTA : GRPQUOTA;
1757                         rc = name2id(&qctl.qc_id, optarg,
1758                                      (qctl.qc_type == USRQUOTA) ? USER : GROUP);
1759                         if (rc) {
1760                                 qctl.qc_id = strtoul(optarg, &endptr, 10);
1761                                 if (*endptr != '\0') {
1762                                         fprintf(stderr, "error: can't find id "
1763                                                 "for name %s\n", optarg);
1764                                         return CMD_HELP;
1765                                 }
1766                         }
1767                         break;
1768                 case 'b':
1769                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
1770                         dqb->dqb_bsoftlimit >>= 10;
1771                         limit_mask |= BSLIMIT;
1772                         break;
1773                 case 'B':
1774                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
1775                         dqb->dqb_bhardlimit >>= 10;
1776                         limit_mask |= BHLIMIT;
1777                         break;
1778                 case 'i':
1779                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
1780                         limit_mask |= ISLIMIT;
1781                         break;
1782                 case 'I':
1783                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
1784                         limit_mask |= IHLIMIT;
1785                         break;
1786                 default: /* getopt prints error message for us when opterr != 0 */
1787                         return CMD_HELP;
1788                 }
1789         }
1790
1791         if (qctl.qc_type == UGQUOTA) {
1792                 fprintf(stderr, "error: neither -u nor -g was specified\n");
1793                 return CMD_HELP;
1794         }
1795
1796         if (limit_mask == 0) {
1797                 fprintf(stderr, "error: at least one limit must be specified\n");
1798                 return CMD_HELP;
1799         }
1800
1801         if (optind != argc - 1) {
1802                 fprintf(stderr, "error: unexpected parameters encountered\n");
1803                 return CMD_HELP;
1804         }
1805
1806         mnt = argv[optind];
1807
1808         if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
1809             (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
1810                 /* sigh, we can't just set blimits/ilimits */
1811                 struct if_quotactl tmp_qctl = {.qc_cmd  = LUSTRE_Q_GETQUOTA,
1812                                                .qc_type = qctl.qc_type,
1813                                                .qc_id   = qctl.qc_id};
1814
1815                 rc = llapi_quotactl(mnt, &tmp_qctl);
1816                 if (rc < 0) {
1817                         fprintf(stderr, "error: setquota failed while retrieving"
1818                                         " current quota settings (%s)\n",
1819                                         strerror(-rc));
1820                         return rc;
1821                 }
1822
1823                 if (!(limit_mask & BHLIMIT))
1824                         dqb->dqb_bhardlimit = tmp_qctl.qc_dqblk.dqb_bhardlimit;
1825                 if (!(limit_mask & BSLIMIT))
1826                         dqb->dqb_bsoftlimit = tmp_qctl.qc_dqblk.dqb_bsoftlimit;
1827                 if (!(limit_mask & IHLIMIT))
1828                         dqb->dqb_ihardlimit = tmp_qctl.qc_dqblk.dqb_ihardlimit;
1829                 if (!(limit_mask & ISLIMIT))
1830                         dqb->dqb_isoftlimit = tmp_qctl.qc_dqblk.dqb_isoftlimit;
1831
1832                 /* Keep grace times if we have got no softlimit arguments */
1833                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
1834                         dqb->dqb_valid |= QIF_BTIME;
1835                         dqb->dqb_btime = tmp_qctl.qc_dqblk.dqb_btime;
1836                 }
1837
1838                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
1839                         dqb->dqb_valid |= QIF_ITIME;
1840                         dqb->dqb_itime = tmp_qctl.qc_dqblk.dqb_itime;
1841                 }
1842         }
1843
1844         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
1845         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
1846
1847         rc = llapi_quotactl(mnt, &qctl);
1848         if (rc) {
1849                 if (*obd_type)
1850                         fprintf(stderr, "%s %s ", obd_type,
1851                                 obd_uuid2str(&qctl.obd_uuid));
1852                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
1853                 return rc;
1854         }
1855
1856         return 0;
1857 }
1858
1859 static inline char *type2name(int check_type)
1860 {
1861         if (check_type == USRQUOTA)
1862                 return "user";
1863         else if (check_type == GRPQUOTA)
1864                 return "group";
1865         else
1866                 return "unknown";
1867 }
1868
1869 /* Converts seconds value into format string
1870  * result is returned in buf
1871  * Notes:
1872  *        1. result is in descenting order: 1w2d3h4m5s
1873  *        2. zero fields are not filled (except for p. 3): 5d1s
1874  *        3. zero seconds value is presented as "0s"
1875  */
1876 static char * __sec2str(time_t seconds, char *buf)
1877 {
1878         const char spec[] = "smhdw";
1879         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
1880         unsigned long c;
1881         char *tail = buf;
1882         int i;
1883
1884         for (i = sizeof(mult) / sizeof(mult[0]) - 1 ; i >= 0; i--) {
1885                 c = seconds / mult[i];
1886
1887                 if (c > 0 || (i == 0 && buf == tail))
1888                         tail += snprintf(tail, 40-(tail-buf), "%lu%c", c, spec[i]);
1889
1890                 seconds %= mult[i];
1891         }
1892
1893         return tail;
1894 }
1895
1896 static void sec2str(time_t seconds, char *buf, int rc)
1897 {
1898         char *tail = buf;
1899
1900         if (rc)
1901                 *tail++ = '[';
1902
1903         tail = __sec2str(seconds, tail);
1904
1905         if (rc && tail - buf < 39) {
1906                 *tail++ = ']';
1907                 *tail++ = 0;
1908         }
1909 }
1910
1911 static void diff2str(time_t seconds, char *buf, time_t now)
1912 {
1913
1914         buf[0] = 0;
1915         if (!seconds)
1916                 return;
1917         if (seconds <= now) {
1918                 strcpy(buf, "none");
1919                 return;
1920         }
1921         __sec2str(seconds - now, buf);
1922 }
1923
1924 static void print_quota_title(char *name, struct if_quotactl *qctl)
1925 {
1926         printf("Disk quotas for %s %s (%cid %u):\n",
1927                type2name(qctl->qc_type), name,
1928                *type2name(qctl->qc_type), qctl->qc_id);
1929         printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
1930                "Filesystem",
1931                "kbytes", "quota", "limit", "grace",
1932                "files", "quota", "limit", "grace");
1933 }
1934
1935 static void print_quota(char *mnt, struct if_quotactl *qctl, int type, int rc)
1936 {
1937         time_t now;
1938
1939         time(&now);
1940
1941         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA) {
1942                 int bover = 0, iover = 0;
1943                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
1944
1945                 if (dqb->dqb_bhardlimit &&
1946                     toqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
1947                         bover = 1;
1948                 } else if (dqb->dqb_bsoftlimit &&
1949                            toqb(dqb->dqb_curspace) >= dqb->dqb_bsoftlimit) {
1950                         if (dqb->dqb_btime > now) {
1951                                 bover = 2;
1952                         } else {
1953                                 bover = 3;
1954                         }
1955                 }
1956
1957                 if (dqb->dqb_ihardlimit &&
1958                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
1959                         iover = 1;
1960                 } else if (dqb->dqb_isoftlimit &&
1961                            dqb->dqb_curinodes >= dqb->dqb_isoftlimit) {
1962                         if (dqb->dqb_btime > now) {
1963                                 iover = 2;
1964                         } else {
1965                                 iover = 3;
1966                         }
1967                 }
1968
1969 #if 0           /* XXX: always print quotas even when no usages */
1970                 if (dqb->dqb_curspace || dqb->dqb_curinodes)
1971 #endif
1972                 {
1973                         char numbuf[3][32];
1974                         char timebuf[40];
1975
1976                         if (strlen(mnt) > 15)
1977                                 printf("%s\n%15s", mnt, "");
1978                         else
1979                                 printf("%15s", mnt);
1980
1981                         if (bover)
1982                                 diff2str(dqb->dqb_btime, timebuf, now);
1983                         if (rc == -EREMOTEIO)
1984                                 sprintf(numbuf[0], LPU64"*",
1985                                         toqb(dqb->dqb_curspace));
1986                         else
1987                                 sprintf(numbuf[0],
1988                                         (dqb->dqb_valid & QIF_SPACE) ?
1989                                         LPU64 : "["LPU64"]",
1990                                         toqb(dqb->dqb_curspace));
1991                         if (type == QC_GENERAL)
1992                                 sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS)
1993                                         ? LPU64 : "["LPU64"]",
1994                                         dqb->dqb_bsoftlimit);
1995                         else
1996                                 sprintf(numbuf[1], "%s", "-");
1997                         sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS)
1998                                 ? LPU64 : "["LPU64"]", dqb->dqb_bhardlimit);
1999                         printf(" %7s%c %6s %7s %7s",
2000                                numbuf[0], bover ? '*' : ' ', numbuf[1],
2001                                numbuf[2], bover > 1 ? timebuf : "-");
2002
2003                         if (iover)
2004                                 diff2str(dqb->dqb_itime, timebuf, now);
2005
2006                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_INODES) ?
2007                                 LPU64 : "["LPU64"]", dqb->dqb_curinodes);
2008                        if (type == QC_GENERAL)
2009                                 sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS)
2010                                         ? LPU64 : "["LPU64"]",
2011                                         dqb->dqb_isoftlimit);
2012                         else
2013                                 sprintf(numbuf[1], "%s", "-");
2014                         sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
2015                                 LPU64 : "["LPU64"]", dqb->dqb_ihardlimit);
2016                         if (type != QC_OSTIDX)
2017                                 printf(" %7s%c %6s %7s %7s",
2018                                        numbuf[0], iover ? '*' : ' ', numbuf[1],
2019                                        numbuf[2], iover > 1 ? timebuf : "-");
2020                         else
2021                                 printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
2022                         printf("\n");
2023                 }
2024         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO ||
2025                    qctl->qc_cmd == Q_GETOINFO) {
2026                 char bgtimebuf[40];
2027                 char igtimebuf[40];
2028
2029                 sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
2030                 sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
2031                 printf("Block grace time: %s; Inode grace time: %s\n",
2032                        bgtimebuf, igtimebuf);
2033         }
2034 }
2035
2036 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt)
2037 {
2038         int rc = 0, rc1 = 0, count = 0;
2039         __u32 valid = qctl->qc_valid;
2040
2041         rc = llapi_get_obd_count(mnt, &count, is_mdt);
2042         if (rc) {
2043                 fprintf(stderr, "can not get %s count: %s\n",
2044                         is_mdt ? "mdt": "ost", strerror(-rc));
2045                 return rc;
2046         }
2047
2048         for (qctl->qc_idx = 0; qctl->qc_idx < count; qctl->qc_idx++) {
2049                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
2050                 rc = llapi_quotactl(mnt, qctl);
2051                 if (rc) {
2052                         /* It is remote client case. */
2053                         if (-rc == EOPNOTSUPP) {
2054                                 rc = 0;
2055                                 goto out;
2056                         }
2057
2058                         if (!rc1)
2059                                 rc1 = rc;
2060                         fprintf(stderr, "quotactl %s%d failed.\n",
2061                                 is_mdt ? "mdt": "ost", qctl->qc_idx);
2062                         continue;
2063                 }
2064
2065                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl, qctl->qc_valid, 0);
2066         }
2067
2068 out:
2069         qctl->qc_valid = valid;
2070         return rc ? : rc1;
2071 }
2072
2073 static int lfs_quota(int argc, char **argv)
2074 {
2075         int c;
2076         char *mnt, *name = NULL;
2077         struct if_quotactl qctl = { .qc_cmd = LUSTRE_Q_GETQUOTA,
2078                                     .qc_type = UGQUOTA };
2079         char *obd_type = (char *)qctl.obd_type;
2080         char *obd_uuid = (char *)qctl.obd_uuid.uuid;
2081         int rc, rc1 = 0, rc2 = 0, rc3 = 0,
2082             verbose = 0, pass = 0, quiet = 0, inacc;
2083         char *endptr;
2084         __u32 valid = QC_GENERAL, idx = 0;
2085
2086         optind = 0;
2087         while ((c = getopt(argc, argv, "gi:I:o:qtuv")) != -1) {
2088                 switch (c) {
2089                 case 'u':
2090                         if (qctl.qc_type != UGQUOTA) {
2091                                 fprintf(stderr, "error: use either -u or -g\n");
2092                                 return CMD_HELP;
2093                         }
2094                         qctl.qc_type = USRQUOTA;
2095                         break;
2096                 case 'g':
2097                         if (qctl.qc_type != UGQUOTA) {
2098                                 fprintf(stderr, "error: use either -u or -g\n");
2099                                 return CMD_HELP;
2100                         }
2101                         qctl.qc_type = GRPQUOTA;
2102                         break;
2103                 case 't':
2104                         qctl.qc_cmd = LUSTRE_Q_GETINFO;
2105                         break;
2106                 case 'o':
2107                         valid = qctl.qc_valid = QC_UUID;
2108                         strncpy(obd_uuid, optarg, sizeof(qctl.obd_uuid));
2109                         break;
2110                 case 'i':
2111                         valid = qctl.qc_valid = QC_MDTIDX;
2112                         idx = qctl.qc_idx = atoi(optarg);
2113                         break;
2114                 case 'I':
2115                         valid = qctl.qc_valid = QC_OSTIDX;
2116                         idx = qctl.qc_idx = atoi(optarg);
2117                         break;
2118                 case 'v':
2119                         verbose = 1;
2120                         break;
2121                 case 'q':
2122                         quiet = 1;
2123                         break;
2124                 default:
2125                         fprintf(stderr, "error: %s: option '-%c' "
2126                                         "unrecognized\n", argv[0], c);
2127                         return CMD_HELP;
2128                 }
2129         }
2130
2131         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
2132         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA && qctl.qc_type == UGQUOTA &&
2133             optind == argc - 1) {
2134 ug_output:
2135                 memset(&qctl, 0, sizeof(qctl)); /* spoiled by print_*_quota */
2136                 qctl.qc_cmd = LUSTRE_Q_GETQUOTA;
2137                 qctl.qc_valid = valid;
2138                 qctl.qc_idx = idx;
2139                 if (pass++ == 0) {
2140                         qctl.qc_type = USRQUOTA;
2141                         qctl.qc_id = geteuid();
2142                 } else {
2143                         qctl.qc_type = GRPQUOTA;
2144                         qctl.qc_id = getegid();
2145                 }
2146                 rc = id2name(&name, qctl.qc_id,
2147                              (qctl.qc_type == USRQUOTA) ? USER : GROUP);
2148                 if (rc)
2149                         name = "<unknown>";
2150         /* lfs quota -u username /path/to/lustre/mount */
2151         } else if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) {
2152                 /* options should be followed by u/g-name and mntpoint */
2153                 if (optind + 2 != argc || qctl.qc_type == UGQUOTA) {
2154                         fprintf(stderr, "error: missing quota argument(s)\n");
2155                         return CMD_HELP;
2156                 }
2157
2158                 name = argv[optind++];
2159                 rc = name2id(&qctl.qc_id, name,
2160                              (qctl.qc_type == USRQUOTA) ? USER : GROUP);
2161                 if (rc) {
2162                         qctl.qc_id = strtoul(name, &endptr, 10);
2163                         if (*endptr != '\0') {
2164                                 fprintf(stderr, "error: can't find id for name "
2165                                         "%s\n", name);
2166                                 return CMD_HELP;
2167                         }
2168                 }
2169         } else if (optind + 1 != argc || qctl.qc_type == UGQUOTA) {
2170                 fprintf(stderr, "error: missing quota info argument(s)\n");
2171                 return CMD_HELP;
2172         }
2173
2174         mnt = argv[optind];
2175
2176         rc1 = llapi_quotactl(mnt, &qctl);
2177         if (rc1 < 0) {
2178                 switch (rc1) {
2179                 case -ESRCH:
2180                         fprintf(stderr, "%s quotas are not enabled.\n",
2181                                 qctl.qc_type == USRQUOTA ? "user" : "group");
2182                         goto out;
2183                 case -EPERM:
2184                         fprintf(stderr, "Permission denied.\n");
2185                 case -ENOENT:
2186                         /* We already got a "No such file..." message. */
2187                         goto out;
2188                 default:
2189                         fprintf(stderr, "Unexpected quotactl error: %s\n",
2190                                 strerror(-rc1));
2191                 }
2192         }
2193
2194         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA && !quiet)
2195                 print_quota_title(name, &qctl);
2196
2197         if (rc1 && *obd_type)
2198                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
2199
2200         if (qctl.qc_valid != QC_GENERAL)
2201                 mnt = "";
2202
2203         inacc = (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) &&
2204                 ((qctl.qc_dqblk.dqb_valid&(QIF_LIMITS|QIF_USAGE))!=(QIF_LIMITS|QIF_USAGE));
2205
2206         print_quota(mnt, &qctl, QC_GENERAL, rc1);
2207
2208         if (qctl.qc_valid == QC_GENERAL && qctl.qc_cmd != LUSTRE_Q_GETINFO && verbose) {
2209                 rc2 = print_obd_quota(mnt, &qctl, 1);
2210                 rc3 = print_obd_quota(mnt, &qctl, 0);
2211         }
2212
2213         if (rc1 || rc2 || rc3 || inacc)
2214                 printf("Some errors happened when getting quota info. "
2215                        "Some devices may be not working or deactivated. "
2216                        "The data in \"[]\" is inaccurate.\n");
2217
2218 out:
2219         if (pass == 1)
2220                 goto ug_output;
2221
2222         return rc1;
2223 }
2224 #endif /* HAVE_SYS_QUOTA_H! */
2225
2226 static int flushctx_ioctl(char *mp)
2227 {
2228         int fd, rc;
2229
2230         fd = open(mp, O_RDONLY);
2231         if (fd == -1) {
2232                 fprintf(stderr, "flushctx: error open %s: %s\n",
2233                         mp, strerror(errno));
2234                 return -1;
2235         }
2236
2237         rc = ioctl(fd, LL_IOC_FLUSHCTX);
2238         if (rc == -1)
2239                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
2240                         mp, strerror(errno));
2241
2242         close(fd);
2243         return rc;
2244 }
2245
2246 static int lfs_flushctx(int argc, char **argv)
2247 {
2248         int     kdestroy = 0, c;
2249         FILE   *proc;
2250         char    procline[PATH_MAX], *line;
2251         int     rc = 0;
2252
2253         optind = 0;
2254         while ((c = getopt(argc, argv, "k")) != -1) {
2255                 switch (c) {
2256                 case 'k':
2257                         kdestroy = 1;
2258                         break;
2259                 default:
2260                         fprintf(stderr, "error: %s: option '-%c' "
2261                                         "unrecognized\n", argv[0], c);
2262                         return CMD_HELP;
2263                 }
2264         }
2265
2266         if (kdestroy) {
2267             int rc;
2268             if ((rc = system("kdestroy > /dev/null")) != 0) {
2269                 rc = WEXITSTATUS(rc);
2270                 fprintf(stderr, "error destroying tickets: %d, continuing\n", rc);
2271             }
2272         }
2273
2274         if (optind >= argc) {
2275                 /* flush for all mounted lustre fs. */
2276                 proc = fopen("/proc/mounts", "r");
2277                 if (!proc) {
2278                         fprintf(stderr, "error: %s: can't open /proc/mounts\n",
2279                                 argv[0]);
2280                         return -1;
2281                 }
2282
2283                 while ((line = fgets(procline, PATH_MAX, proc)) != NULL) {
2284                         char dev[PATH_MAX];
2285                         char mp[PATH_MAX];
2286                         char fs[PATH_MAX];
2287
2288                         if (sscanf(line, "%s %s %s", dev, mp, fs) != 3) {
2289                                 fprintf(stderr, "%s: unexpected format in "
2290                                                 "/proc/mounts\n",
2291                                         argv[0]);
2292                                 return -1;
2293                         }
2294
2295                         if (strcmp(fs, "lustre") != 0)
2296                                 continue;
2297                         /* we use '@' to determine it's a client. are there
2298                          * any other better way?
2299                          */
2300                         if (strchr(dev, '@') == NULL)
2301                                 continue;
2302
2303                         if (flushctx_ioctl(mp))
2304                                 rc = -1;
2305                 }
2306         } else {
2307                 /* flush fs as specified */
2308                 while (optind < argc) {
2309                         if (flushctx_ioctl(argv[optind++]))
2310                                 rc = -1;
2311                 }
2312         }
2313
2314         return rc;
2315 }
2316
2317 static int lfs_lsetfacl(int argc, char **argv)
2318 {
2319         argv[0]++;
2320         return(llapi_lsetfacl(argc, argv));
2321 }
2322
2323 static int lfs_lgetfacl(int argc, char **argv)
2324 {
2325         argv[0]++;
2326         return(llapi_lgetfacl(argc, argv));
2327 }
2328
2329 static int lfs_rsetfacl(int argc, char **argv)
2330 {
2331         argv[0]++;
2332         return(llapi_rsetfacl(argc, argv));
2333 }
2334
2335 static int lfs_rgetfacl(int argc, char **argv)
2336 {
2337         argv[0]++;
2338         return(llapi_rgetfacl(argc, argv));
2339 }
2340
2341 static int lfs_cp(int argc, char **argv)
2342 {
2343         return(llapi_cp(argc, argv));
2344 }
2345
2346 static int lfs_ls(int argc, char **argv)
2347 {
2348         return(llapi_ls(argc, argv));
2349 }
2350
2351 static int lfs_changelog(int argc, char **argv)
2352 {
2353         void *changelog_priv;
2354         struct changelog_rec *rec;
2355         long long startrec = 0, endrec = 0;
2356         char *mdd;
2357         struct option long_opts[] = {
2358                 {"follow", no_argument, 0, 'f'},
2359                 {0, 0, 0, 0}
2360         };
2361         char short_opts[] = "f";
2362         int rc, follow = 0;
2363
2364         optind = 0;
2365         while ((rc = getopt_long(argc, argv, short_opts,
2366                                 long_opts, NULL)) != -1) {
2367                 switch (rc) {
2368                 case 'f':
2369                         follow++;
2370                         break;
2371                 case '?':
2372                         return CMD_HELP;
2373                 default:
2374                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
2375                                 argv[0], argv[optind - 1]);
2376                         return CMD_HELP;
2377                 }
2378         }
2379         if (optind >= argc)
2380                 return CMD_HELP;
2381
2382         mdd = argv[optind++];
2383         if (argc > optind)
2384                 startrec = strtoll(argv[optind++], NULL, 10);
2385         if (argc > optind)
2386                 endrec = strtoll(argv[optind++], NULL, 10);
2387
2388         rc = llapi_changelog_start(&changelog_priv,
2389                                    CHANGELOG_FLAG_BLOCK |
2390                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
2391                                    mdd, startrec);
2392         if (rc < 0) {
2393                 fprintf(stderr, "Can't start changelog: %s\n",
2394                         strerror(errno = -rc));
2395                 return rc;
2396         }
2397
2398         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
2399                 time_t secs;
2400                 struct tm ts;
2401
2402                 if (endrec && rec->cr_index > endrec) {
2403                         llapi_changelog_free(&rec);
2404                         break;
2405                 }
2406                 if (rec->cr_index < startrec) {
2407                         llapi_changelog_free(&rec);
2408                         continue;
2409                 }
2410
2411                 secs = rec->cr_time >> 30;
2412                 gmtime_r(&secs, &ts);
2413                 printf(LPU64" %02d%-5s %02d:%02d:%02d.%06d %04d.%02d.%02d "
2414                        "0x%x t="DFID, rec->cr_index, rec->cr_type,
2415                        changelog_type2str(rec->cr_type),
2416                        ts.tm_hour, ts.tm_min, ts.tm_sec,
2417                        (int)(rec->cr_time & ((1<<30) - 1)),
2418                        ts.tm_year+1900, ts.tm_mon+1, ts.tm_mday,
2419                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
2420                 if (rec->cr_namelen)
2421                         /* namespace rec includes parent and filename */
2422                         printf(" p="DFID" %.*s\n", PFID(&rec->cr_pfid),
2423                                rec->cr_namelen, rec->cr_name);
2424                 else
2425                         printf("\n");
2426
2427                 llapi_changelog_free(&rec);
2428         }
2429
2430         llapi_changelog_fini(&changelog_priv);
2431
2432         if (rc < 0)
2433                 fprintf(stderr, "Changelog: %s\n", strerror(errno = -rc));
2434
2435         return (rc == 1 ? 0 : rc);
2436 }
2437
2438 static int lfs_changelog_clear(int argc, char **argv)
2439 {
2440         long long endrec;
2441         int rc;
2442
2443         if (argc != 4)
2444                 return CMD_HELP;
2445
2446         endrec = strtoll(argv[3], NULL, 10);
2447
2448         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
2449         if (rc)
2450                 fprintf(stderr, "%s error: %s\n", argv[0],
2451                         strerror(errno = -rc));
2452         return rc;
2453 }
2454
2455 static int lfs_fid2path(int argc, char **argv)
2456 {
2457         struct option long_opts[] = {
2458                 {"cur", no_argument, 0, 'c'},
2459                 {"link", required_argument, 0, 'l'},
2460                 {"rec", required_argument, 0, 'r'},
2461                 {0, 0, 0, 0}
2462         };
2463         char  short_opts[] = "cl:r:";
2464         char *device, *fid, *path;
2465         long long recno = -1;
2466         int linkno = -1;
2467         int lnktmp;
2468         int printcur = 0;
2469         int rc;
2470
2471         optind = 0;
2472
2473         while ((rc = getopt_long(argc, argv, short_opts,
2474                                 long_opts, NULL)) != -1) {
2475                 switch (rc) {
2476                 case 'c':
2477                         printcur++;
2478                         break;
2479                 case 'l':
2480                         linkno = strtol(optarg, NULL, 10);
2481                         break;
2482                 case 'r':
2483                         recno = strtoll(optarg, NULL, 10);
2484                         break;
2485                 case '?':
2486                         return CMD_HELP;
2487                 default:
2488                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
2489                                 argv[0], argv[optind - 1]);
2490                         return CMD_HELP;
2491                 }
2492         }
2493         device = argv[optind++];
2494         fid = argv[optind++];
2495         if (optind != argc)
2496                 return CMD_HELP;
2497
2498         path = calloc(1, PATH_MAX);
2499
2500         lnktmp = (linkno >= 0) ? linkno : 0;
2501         while (1) {
2502                 int oldtmp = lnktmp;
2503                 long long rectmp = recno;
2504                 rc = llapi_fid2path(device, fid, path, PATH_MAX, &rectmp,
2505                                     &lnktmp);
2506                 if (rc < 0) {
2507                         fprintf(stderr, "%s error: %s\n", argv[0],
2508                                 strerror(errno = -rc));
2509                         break;
2510                 }
2511
2512                 if (printcur)
2513                         fprintf(stdout, "%lld ", rectmp);
2514                 if (device[0] == '/') {
2515                         fprintf(stdout, "%s", device);
2516                         if (device[strlen(device) - 1] != '/')
2517                                 fprintf(stdout, "/");
2518                 } else if (path[0] == '\0') {
2519                         fprintf(stdout, "/");
2520                 }
2521                 fprintf(stdout, "%s\n", path);
2522
2523                 if (linkno >= 0)
2524                         /* specified linkno */
2525                         break;
2526                 if (oldtmp == lnktmp)
2527                         /* no more links */
2528                         break;
2529         }
2530
2531         free(path);
2532         return rc;
2533 }
2534
2535 static int lfs_path2fid(int argc, char **argv)
2536 {
2537         char *path;
2538         lustre_fid fid;
2539         int rc;
2540
2541         if (argc != 2)
2542                 return CMD_HELP;
2543
2544         path = argv[1];
2545         rc = llapi_path2fid(path, &fid);
2546         if (rc) {
2547                 fprintf(stderr, "can't get fid for %s: %s\n", path,
2548                         strerror(errno = -rc));
2549                 return rc;
2550         }
2551
2552         printf(DFID"\n", PFID(&fid));
2553
2554         return 0;
2555 }
2556
2557 int main(int argc, char **argv)
2558 {
2559         int rc;
2560
2561         setlinebuf(stdout);
2562
2563         ptl_initialize(argc, argv);
2564         if (obd_initialize(argc, argv) < 0)
2565                 exit(2);
2566         if (dbg_initialize(argc, argv) < 0)
2567                 exit(3);
2568
2569         Parser_init("lfs > ", cmdlist);
2570
2571         if (argc > 1) {
2572                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
2573         } else {
2574                 rc = Parser_commands();
2575         }
2576
2577         obd_finalize(argc, argv);
2578         return rc < 0 ? -rc : rc;
2579 }
2580