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