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