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