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