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