Whamcloud - gitweb
b=20984 cleanup md_op_data and add getstripe -M
[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  2008 Sun Microsystems, Inc. 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 <dir|file> ... \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 [-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                         if (param.num_alloc_obds == 0) {
679                                 param.obduuid = malloc(FIND_MAX_OSTS *
680                                                        sizeof(struct obd_uuid));
681                                 if (param.obduuid == NULL)
682                                         return -ENOMEM;
683                                 param.num_alloc_obds = INIT_ALLOC_NUM_OSTS;
684                         }
685
686                         for (token = buf; token && *token; token = next) {
687                                 p = strchr(token, ',');
688                                 next = 0;
689                                 if (p) {
690                                         *p = 0;
691                                         next = p+1;
692                                 }
693                                 strcpy((char *)&param.obduuid[param.num_obds++].uuid,
694                                        token);
695                         }
696
697                         if (buf)
698                                 free(buf);
699                         break;
700                 }
701                 case 'p':
702                         new_fashion = 1;
703                         param.zeroend = 1;
704                         break;
705                 case 'P':
706                         break;
707                 case 'q':
708                         new_fashion = 0;
709                         param.quiet++;
710                         param.verbose = 0;
711                         break;
712                 case 'r':
713                         new_fashion = 0;
714                         param.recursive = 1;
715                         break;
716                 case 't':
717                         param.exclude_type = !!neg_opt;
718                         switch(optarg[0]) {
719                         case 'b': param.type = S_IFBLK; break;
720                         case 'c': param.type = S_IFCHR; break;
721                         case 'd': param.type = S_IFDIR; break;
722                         case 'f': param.type = S_IFREG; break;
723                         case 'l': param.type = S_IFLNK; break;
724                         case 'p': param.type = S_IFIFO; break;
725                         case 's': param.type = S_IFSOCK; break;
726 #ifdef S_IFDOOR /* Solaris only */
727                         case 'D': param.type = S_IFDOOR; break;
728 #endif
729                         default: fprintf(stderr, "error: %s: bad type '%s'\n",
730                                          argv[0], optarg);
731                                  return CMD_HELP;
732                         };
733                         break;
734                 case 's':
735                         if (neg_opt) {
736                                 if (optarg[0] == '-')
737                                         optarg[0] = '+';
738                                 else if (optarg[0] == '+')
739                                         optarg[0] = '-';
740                                 else {
741                                         str[0] = '-';
742                                         str[1] = '\0';
743                                         strcat(str, optarg);
744                                         optarg = str;
745                                 }
746                         }
747                         if (optarg[0] == '+')
748                                 param.size_sign = -1;
749                         else if (optarg[0] == '-')
750                                 param.size_sign = +1;
751
752                         if (param.size_sign)
753                                 optarg++;
754                         ret = parse_size(optarg, &param.size,
755                                          &param.size_units, 0);
756                         if (ret) {
757                                 fprintf(stderr,"error: bad size '%s'\n",
758                                         optarg);
759                                 return ret;
760                         }
761                         break;
762                 case 'v':
763                         new_fashion = 0;
764                         param.verbose++;
765                         param.quiet = 0;
766                         break;
767                 case '?':
768                         return CMD_HELP;
769                 default:
770                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
771                                 argv[0], argv[optind - 1]);
772                         return CMD_HELP;
773                 };
774         }
775
776         if (pathstart == -1) {
777                 fprintf(stderr, "error: %s: no filename|pathname\n",
778                         argv[0]);
779                 return CMD_HELP;
780         } else if (pathend == -1) {
781                 /* no options */
782                 pathend = argc;
783         }
784
785         if (new_fashion) {
786                 param.quiet = 1;
787         } else {
788                 static int deprecated_warning;
789                 if (!deprecated_warning) {
790                         fprintf(stderr, "lfs find: -q, -r, -v options "
791                                 "deprecated.  Use 'lfs getstripe' instead.\n");
792                         deprecated_warning = 1;
793                 }
794                 if (!param.recursive && param.maxdepth == -1)
795                         param.maxdepth = 1;
796         }
797
798         do {
799                 if (new_fashion)
800                         ret = llapi_find(argv[pathstart], &param);
801                 else
802                         ret = llapi_getstripe(argv[pathstart], &param);
803         } while (++pathstart < pathend && !ret);
804
805         if (ret)
806                 fprintf(stderr, "error: %s failed for %s.\n",
807                         argv[0], argv[optind - 1]);
808
809         if (param.obduuid && param.num_alloc_obds)
810                 free(param.obduuid);
811
812         return ret;
813 }
814
815 static int lfs_getstripe(int argc, char **argv)
816 {
817         struct option long_opts[] = {
818                 {"obd", 1, 0, 'O'},
819                 {"quiet", 0, 0, 'q'},
820                 {"recursive", 0, 0, 'r'},
821                 {"count", 0, 0, 'c'},
822                 {"size", 0, 0, 's'},
823                 {"index", 0, 0, 'i'},
824                 {"offset", 0, 0, 'o'},
825                 {"pool", 0, 0, 'p'},
826                 {"verbose", 0, 0, 'v'},
827                 {"directory", 0, 0, 'd'},
828                 {"mdt", 0, 0, 'M'},
829                 {0, 0, 0, 0}
830         };
831         int c, rc;
832         struct find_param param = { 0 };
833
834         param.maxdepth = 1;
835         optind = 0;
836         while ((c = getopt_long(argc, argv, "cdhiMoO:pqrsv",
837                                 long_opts, NULL)) != -1) {
838                 switch (c) {
839                 case 'O':
840                         if (param.obduuid) {
841                                 fprintf(stderr,
842                                         "error: %s: only one obduuid allowed",
843                                         argv[0]);
844                                 return CMD_HELP;
845                         }
846                         param.obduuid = (struct obd_uuid *)optarg;
847                         break;
848                 case 'q':
849                         param.quiet++;
850                         break;
851                 case 'd':
852                         param.maxdepth = 0;
853                         break;
854                 case 'r':
855                         param.recursive = 1;
856                         break;
857                 case 'v':
858                         param.verbose = VERBOSE_ALL | VERBOSE_DETAIL;
859                         break;
860                 case 'c':
861                         if (!(param.verbose & VERBOSE_DETAIL)) {
862                                 param.verbose |= VERBOSE_COUNT;
863                                 param.maxdepth = 0;
864                         }
865                         break;
866                 case 's':
867                         if (!(param.verbose & VERBOSE_DETAIL)) {
868                                 param.verbose |= VERBOSE_SIZE;
869                                 param.maxdepth = 0;
870                         }
871                         break;
872                 case 'i':
873                 case 'o':
874                         if (!(param.verbose & VERBOSE_DETAIL)) {
875                                 param.verbose |= VERBOSE_OFFSET;
876                                 param.maxdepth = 0;
877                         }
878                         break;
879                 case 'p':
880                         param.verbose |= VERBOSE_POOL;
881                         break;
882                 case 'M':
883                         param.get_mdt_index = 1;
884                         break;
885                 case '?':
886                         return CMD_HELP;
887                 default:
888                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
889                                 argv[0], argv[optind - 1]);
890                         return CMD_HELP;
891                 }
892         }
893
894         if (optind >= argc)
895                 return CMD_HELP;
896
897         if (param.recursive)
898                 param.maxdepth = -1;
899
900         if (!param.verbose)
901                 param.verbose = VERBOSE_ALL;
902         if (param.quiet)
903                 param.verbose = VERBOSE_OBJID;
904
905         do {
906                 rc = llapi_getstripe(argv[optind], &param);
907         } while (++optind < argc && !rc);
908
909         if (rc)
910                 fprintf(stderr, "error: %s failed for %s.\n",
911                         argv[0], argv[optind - 1]);
912         return rc;
913 }
914
915 static int lfs_osts(int argc, char **argv)
916 {
917         char mntdir[PATH_MAX] = {'\0'};
918         struct find_param param;
919         int index = 0, rc=0;
920
921         if (argc != 1)
922                 return CMD_HELP;
923
924         while (llapi_search_mounts(NULL, index++, mntdir, NULL) == 0) {
925                 memset(&param, 0, sizeof(param));
926                 rc = llapi_ostlist(mntdir, &param);
927                 if (rc) {
928                         fprintf(stderr, "error: %s: failed on %s\n",
929                                 argv[0], mntdir);
930                 }
931                 memset(mntdir, 0, PATH_MAX);
932         }
933
934         return rc;
935 }
936
937 #define COOK(value)                                                     \
938 ({                                                                      \
939         int radix = 0;                                                  \
940         while (value > 1024) {                                          \
941                 value /= 1024;                                          \
942                 radix++;                                                \
943         }                                                               \
944         radix;                                                          \
945 })
946 #define UUF     "%-20s"
947 #define CSF     "%9s"
948 #define CDF     "%9llu"
949 #define HSF     "%8s"
950 #define HDF     "%6.1f"
951 #define RSF     "%5s"
952 #define RDF     "%4d%%"
953
954 static int showdf(char *mntdir, struct obd_statfs *stat,
955                   char *uuid, int ishow, int cooked,
956                   char *type, int index, int rc)
957 {
958         long long avail, used, total;
959         double ratio = 0;
960         char *suffix = "KMGTPEZY";
961         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
962         char tbuf[20], ubuf[20], abuf[20], rbuf[20];
963
964         if (!uuid || !stat)
965                 return -EINVAL;
966
967         switch (rc) {
968         case 0:
969                 if (ishow) {
970                         avail = stat->os_ffree;
971                         used = stat->os_files - stat->os_ffree;
972                         total = stat->os_files;
973                 } else {
974                         int shift = cooked ? 0 : 10;
975
976                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
977                         used  = ((stat->os_blocks - stat->os_bfree) *
978                                  stat->os_bsize) >> shift;
979                         total = (stat->os_blocks * stat->os_bsize) >> shift;
980                 }
981
982                 if (total > 0)
983                         ratio = (double)used / (double)total;
984
985                 if (cooked) {
986                         int i;
987                         double cook_val;
988
989                         cook_val = (double)total;
990                         i = COOK(cook_val);
991                         if (i > 0)
992                                 sprintf(tbuf, HDF"%c", cook_val, suffix[i - 1]);
993                         else
994                                 sprintf(tbuf, CDF, total);
995
996                         cook_val = (double)used;
997                         i = COOK(cook_val);
998                         if (i > 0)
999                                 sprintf(ubuf, HDF"%c", cook_val, suffix[i - 1]);
1000                         else
1001                                 sprintf(ubuf, CDF, used);
1002
1003                         cook_val = (double)avail;
1004                         i = COOK(cook_val);
1005                         if (i > 0)
1006                                 sprintf(abuf, HDF"%c", cook_val, suffix[i - 1]);
1007                         else
1008                                 sprintf(abuf, CDF, avail);
1009                 } else {
1010                         sprintf(tbuf, CDF, total);
1011                         sprintf(ubuf, CDF, used);
1012                         sprintf(abuf, CDF, avail);
1013                 }
1014
1015                 sprintf(rbuf, RDF, (int)(ratio * 100));
1016                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
1017                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
1018                 if (type)
1019                         printf("[%s:%d]\n", type, index);
1020                 else
1021                         printf("\n");
1022
1023                 break;
1024         case -ENODATA:
1025                 printf(UUF": inactive device\n", uuid);
1026                 break;
1027         default:
1028                 printf(UUF": %s\n", uuid, strerror(-rc));
1029                 break;
1030         }
1031
1032         return 0;
1033 }
1034
1035 static int mntdf(char *mntdir, char *fsname, char *pool, int ishow, int cooked)
1036 {
1037         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
1038         struct obd_uuid uuid_buf;
1039         char *poolname = NULL;
1040         __u32 index;
1041         int rc;
1042
1043         if (pool) {
1044                 poolname = strchr(pool, '.');
1045                 if (poolname != NULL) {
1046                         if (strncmp(fsname, pool, strlen(fsname))) {
1047                                 fprintf(stderr, "filesystem name incorrect\n");
1048                                 return -ENODEV;
1049                         }
1050                         poolname++;
1051                 } else
1052                         poolname = pool;
1053         }
1054
1055         if (ishow)
1056                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
1057                        "UUID", "Inodes", "IUsed", "IFree",
1058                        "IUse%", "Mounted on");
1059         else
1060                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
1061                        "UUID", cooked ? "bytes" : "1K-blocks",
1062                        "Used", "Available", "Use%", "Mounted on");
1063
1064         for (index = 0; ; index++) {
1065                 memset(&stat_buf, 0, sizeof(struct obd_statfs));
1066                 memset(&uuid_buf, 0, sizeof(struct obd_uuid));
1067                 rc = llapi_obd_statfs(mntdir, LL_STATFS_MDC, index,
1068                                       &stat_buf, &uuid_buf);
1069                 if (rc == -ENODEV)
1070                         break;
1071
1072                 if (rc == -EAGAIN)
1073                         continue;
1074
1075                 if (rc == -ENOTCONN || rc == -ETIMEDOUT || rc == -EIO ||
1076                     rc == -ENODATA || rc == 0) {
1077                         showdf(mntdir, &stat_buf, obd_uuid2str(&uuid_buf),
1078                                ishow, cooked, "MDT", index, rc);
1079                 } else {
1080                         fprintf(stderr,
1081                                 "error: llapi_obd_statfs(%s): %s (%d)\n",
1082                                 obd_uuid2str(&uuid_buf), strerror(-rc), rc);
1083                         return rc;
1084                 }
1085                 if (rc == 0) {
1086                         sum.os_ffree += stat_buf.os_ffree;
1087                         sum.os_files += stat_buf.os_files;
1088                 }
1089         }
1090
1091         for (index = 0; ; index++) {
1092                 memset(&stat_buf, 0, sizeof(struct obd_statfs));
1093                 memset(&uuid_buf, 0, sizeof(struct obd_uuid));
1094                 rc = llapi_obd_statfs(mntdir, LL_STATFS_LOV, index,
1095                                       &stat_buf, &uuid_buf);
1096                 if (rc == -ENODEV)
1097                         break;
1098
1099                 if (rc == -EAGAIN)
1100                         continue;
1101
1102                 if (llapi_search_ost(fsname, poolname,
1103                                      obd_uuid2str(&uuid_buf)) != 1)
1104                         continue;
1105
1106                 if (rc == -ENOTCONN || rc == -ETIMEDOUT || rc == -EIO ||
1107                     rc == -ENODATA || rc == 0) {
1108                         showdf(mntdir, &stat_buf, obd_uuid2str(&uuid_buf),
1109                                ishow, cooked, "OST", index, rc);
1110                 } else {
1111                         fprintf(stderr,
1112                                 "error: llapi_obd_statfs failed: %s (%d)\n",
1113                                 strerror(-rc), rc);
1114                         return rc;
1115                 }
1116                 if (rc == 0) {
1117                         sum.os_blocks += stat_buf.os_blocks * stat_buf.os_bsize;
1118                         sum.os_bfree  += stat_buf.os_bfree * stat_buf.os_bsize;
1119                         sum.os_bavail += stat_buf.os_bavail * stat_buf.os_bsize;
1120                 }
1121         }
1122
1123         printf("\n");
1124         showdf(mntdir, &sum, "filesystem summary:", ishow, cooked, NULL, 0,0);
1125
1126         return 0;
1127 }
1128
1129 static int lfs_df(int argc, char **argv)
1130 {
1131         char *path = NULL;
1132         char *mntdir = NULL;
1133         int ishow = 0, cooked = 0;
1134         int c, rc = 0;
1135         char fsname[PATH_MAX], *pool_name = NULL;
1136         struct option long_opts[] = {
1137                 {"pool", required_argument, 0, 'p'},
1138                 {0, 0, 0, 0}
1139         };
1140
1141         optind = 0;
1142         while ((c = getopt_long(argc, argv, "hip:", long_opts, NULL)) != -1) {
1143                 switch (c) {
1144                 case 'i':
1145                         ishow = 1;
1146                         break;
1147                 case 'h':
1148                         cooked = 1;
1149                         break;
1150                 case 'p':
1151                         pool_name = optarg;
1152                         break;
1153                 default:
1154                         return CMD_HELP;
1155                 }
1156         }
1157         if (optind < argc )
1158                 path = argv[optind];
1159
1160         if ((mntdir = malloc(PATH_MAX)) == NULL) {
1161                 fprintf(stderr, "error: cannot allocate %d bytes\n",
1162                         PATH_MAX);
1163                 return -ENOMEM;
1164         }
1165         memset(mntdir, 0, PATH_MAX);
1166
1167         if (path) {
1168                 char rpath[PATH_MAX] = {'\0'};
1169
1170                 if (!realpath(path, rpath)) {
1171                         rc = -errno;
1172                         fprintf(stderr, "error: invalid path '%s': %s\n",
1173                                         path, strerror(-rc));
1174                 } else {
1175                         rc = llapi_search_mounts(rpath, 0, mntdir, fsname);
1176                         if (rc == 0 && mntdir[0] != '\0') {
1177                                 rc = mntdf(mntdir, fsname, pool_name,
1178                                            ishow, cooked);
1179                                 printf("\n");
1180                         }
1181                 }
1182         } else {
1183                 int index = 0;
1184
1185                 while (llapi_search_mounts(NULL, index++, mntdir, fsname)==0) {
1186                         rc = mntdf(mntdir, fsname, pool_name,
1187                                    ishow, cooked);
1188                         if (rc)
1189                                 break;
1190                         printf("\n");
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                         fprintf(stderr, "\n%s quotas are enabled already.\n",
1415                                 qctl.qc_type == 0x02 ? "user/group" :
1416                                 (qctl.qc_type == 0x00 ? "user" : "group"));
1417                         rc = 0;
1418                 } else if (errno == ENOENT) {
1419                         fprintf(stderr, "error: cannot find quota database, "
1420                                         "make sure you have run quotacheck\n");
1421                 } else {
1422                         if (*obd_type)
1423                                 fprintf(stderr, "%s %s ", obd_type,
1424                                         obd_uuid2str(&qctl.obd_uuid));
1425                         fprintf(stderr, "%s failed: %s\n", argv[0],
1426                                 strerror(errno));
1427                 }
1428         }
1429
1430         return rc;
1431 }
1432
1433 static int lfs_quotaoff(int argc, char **argv)
1434 {
1435         int c;
1436         char *mnt;
1437         struct if_quotactl qctl;
1438         char *obd_type = (char *)qctl.obd_type;
1439         int rc;
1440
1441         memset(&qctl, 0, sizeof(qctl));
1442         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
1443
1444         optind = 0;
1445         while ((c = getopt(argc, argv, "ug")) != -1) {
1446                 switch (c) {
1447                 case 'u':
1448                         qctl.qc_type |= 0x01;
1449                         break;
1450                 case 'g':
1451                         qctl.qc_type |= 0x02;
1452                         break;
1453                 default:
1454                         fprintf(stderr, "error: %s: option '-%c' "
1455                                         "unrecognized\n", argv[0], c);
1456                         return CMD_HELP;
1457                 }
1458         }
1459
1460         if (qctl.qc_type)
1461                 qctl.qc_type--;
1462         else /* by default, disable quota for both user & group */
1463                 qctl.qc_type = 0x02;
1464
1465         if (argc == optind)
1466                 return CMD_HELP;
1467
1468         mnt = argv[optind];
1469
1470         rc = llapi_quotactl(mnt, &qctl);
1471         if (rc) {
1472                 if (errno == EALREADY) {
1473                         fprintf(stderr, "\n%s quotas are disabled already.\n",
1474                                 qctl.qc_type == 0x02 ? "user/group" :
1475                                 (qctl.qc_type == 0x00 ? "user" : "group"));
1476                         rc = 0;
1477                 } else {
1478                         if (*obd_type)
1479                                 fprintf(stderr, "%s %s ", obd_type,
1480                                         obd_uuid2str(&qctl.obd_uuid));
1481                         fprintf(stderr, "quotaoff failed: %s\n",
1482                                 strerror(errno));
1483                 }
1484         }
1485
1486         return rc;
1487 }
1488
1489 static int lfs_quotainv(int argc, char **argv)
1490 {
1491         int c;
1492         char *mnt;
1493         struct if_quotactl qctl;
1494         int rc;
1495
1496         memset(&qctl, 0, sizeof(qctl));
1497         qctl.qc_cmd = LUSTRE_Q_INVALIDATE;
1498
1499         optind = 0;
1500         while ((c = getopt(argc, argv, "ugf")) != -1) {
1501                 switch (c) {
1502                 case 'u':
1503                         qctl.qc_type |= 0x01;
1504                         break;
1505                 case 'g':
1506                         qctl.qc_type |= 0x02;
1507                         break;
1508                 case 'f':
1509                         qctl.qc_cmd = LUSTRE_Q_FINVALIDATE;
1510                         break;
1511                 default:
1512                         fprintf(stderr, "error: %s: option '-%c' "
1513                                         "unrecognized\n", argv[0], c);
1514                         return CMD_HELP;
1515                 }
1516         }
1517
1518         if (qctl.qc_type)
1519                 qctl.qc_type--;
1520         else /* by default, invalidate quota for both user & group */
1521                 qctl.qc_type = 0x02;
1522
1523         if (argc == optind)
1524                 return CMD_HELP;
1525
1526         mnt = argv[optind];
1527
1528         rc = llapi_quotactl(mnt, &qctl);
1529         if (rc) {
1530                 fprintf(stderr, "quotainv failed: %s\n", strerror(errno));
1531                 return rc;
1532         }
1533
1534         return 0;
1535 }
1536
1537 #define ARG2INT(nr, str, msg)                                           \
1538 do {                                                                    \
1539         char *endp;                                                     \
1540         nr = strtol(str, &endp, 0);                                     \
1541         if (*endp) {                                                    \
1542                 fprintf(stderr, "error: bad %s: %s\n", msg, str);       \
1543                 return CMD_HELP;                                        \
1544         }                                                               \
1545 } while (0)
1546
1547 #define ADD_OVERFLOW(a,b) ((a + b) < a) ? (a = ULONG_MAX) : (a = a + b)
1548
1549 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
1550  * returns the value or ULONG_MAX on integer overflow or incorrect format
1551  * Notes:
1552  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
1553  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
1554  *        3. empty integer value is interpreted as 0
1555  */
1556
1557 static unsigned long str2sec(const char* timestr) {
1558         const char spec[] = "smhdw";
1559         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
1560         unsigned long val = 0;
1561         char *tail;
1562
1563         if (strpbrk(timestr, spec) == NULL) {
1564                 /* no specifiers inside the time string,
1565                    should treat it as an integer value */
1566                 val = strtoul(timestr, &tail, 10);
1567                 return *tail ? ULONG_MAX : val;
1568         }
1569
1570         /* format string is XXwXXdXXhXXmXXs */
1571         while (*timestr) {
1572                 unsigned long v;
1573                 int ind;
1574                 char* ptr;
1575
1576                 v = strtoul(timestr, &tail, 10);
1577                 if (v == ULONG_MAX || *tail == '\0')
1578                         /* value too large (ULONG_MAX or more)
1579                            or missing specifier */
1580                         goto error;
1581
1582                 ptr = strchr(spec, *tail);
1583                 if (ptr == NULL)
1584                         /* unknown specifier */
1585                         goto error;
1586
1587                 ind = ptr - spec;
1588
1589                 /* check if product will overflow the type */
1590                 if (!(v < ULONG_MAX / mult[ind]))
1591                         goto error;
1592
1593                 ADD_OVERFLOW(val, mult[ind] * v);
1594                 if (val == ULONG_MAX)
1595                         goto error;
1596
1597                 timestr = tail + 1;
1598         }
1599
1600         return val;
1601
1602 error:
1603         return ULONG_MAX;
1604 }
1605
1606 #define ARG2ULL(nr, str, defscale)                                      \
1607 do {                                                                    \
1608         unsigned long long limit, units = 0;                            \
1609         int rc;                                                         \
1610                                                                         \
1611         rc = parse_size(str, &limit, &units, 1);                        \
1612         if (rc < 0) {                                                   \
1613                 fprintf(stderr, "error: bad limit value %s\n", str);    \
1614                 return CMD_HELP;                                        \
1615         }                                                               \
1616         nr = ((units == 0) ? (defscale) : 1) * limit;                   \
1617 } while (0)
1618
1619 static inline int has_times_option(int argc, char **argv)
1620 {
1621         int i;
1622
1623         for (i = 1; i < argc; i++)
1624                 if (!strcmp(argv[i], "-t"))
1625                         return 1;
1626
1627         return 0;
1628 }
1629
1630 int lfs_setquota_times(int argc, char **argv)
1631 {
1632         int c, rc;
1633         struct if_quotactl qctl;
1634         char *mnt, *obd_type = (char *)qctl.obd_type;
1635         struct obd_dqblk *dqb = &qctl.qc_dqblk;
1636         struct obd_dqinfo *dqi = &qctl.qc_dqinfo;
1637         struct option long_opts[] = {
1638                 {"user",            no_argument,       0, 'u'},
1639                 {"group",           no_argument,       0, 'g'},
1640                 {"block-grace",     required_argument, 0, 'b'},
1641                 {"inode-grace",     required_argument, 0, 'i'},
1642                 {"times",           no_argument,       0, 't'},
1643                 {0, 0, 0, 0}
1644         };
1645
1646         memset(&qctl, 0, sizeof(qctl));
1647         qctl.qc_cmd  = LUSTRE_Q_SETINFO;
1648         qctl.qc_type = UGQUOTA;
1649
1650         optind = 0;
1651         while ((c = getopt_long(argc, argv, "b:i:gtu", long_opts, NULL)) != -1) {
1652                 switch (c) {
1653                 case 'u':
1654                 case 'g':
1655                         if (qctl.qc_type != UGQUOTA) {
1656                                 fprintf(stderr, "error: -u and -g can't be used "
1657                                                 "more than once\n");
1658                                 return CMD_HELP;
1659                         }
1660                         qctl.qc_type = (c == 'u') ? USRQUOTA : GRPQUOTA;
1661                         break;
1662                 case 'b':
1663                         if ((dqi->dqi_bgrace = str2sec(optarg)) == ULONG_MAX) {
1664                                 fprintf(stderr, "error: bad block-grace: %s\n",
1665                                         optarg);
1666                                 return CMD_HELP;
1667                         }
1668                         dqb->dqb_valid |= QIF_BTIME;
1669                         break;
1670                 case 'i':
1671                         if ((dqi->dqi_igrace = str2sec(optarg)) == ULONG_MAX) {
1672                                 fprintf(stderr, "error: bad inode-grace: %s\n",
1673                                         optarg);
1674                                 return CMD_HELP;
1675                         }
1676                         dqb->dqb_valid |= QIF_ITIME;
1677                         break;
1678                 case 't': /* Yes, of course! */
1679                         break;
1680                 default: /* getopt prints error message for us when opterr != 0 */
1681                         return CMD_HELP;
1682                 }
1683         }
1684
1685         if (qctl.qc_type == UGQUOTA) {
1686                 fprintf(stderr, "error: neither -u nor -g specified\n");
1687                 return CMD_HELP;
1688         }
1689
1690         if (optind != argc - 1) {
1691                 fprintf(stderr, "error: unexpected parameters encountered\n");
1692                 return CMD_HELP;
1693         }
1694
1695         mnt = argv[optind];
1696         rc = llapi_quotactl(mnt, &qctl);
1697         if (rc) {
1698                 if (*obd_type)
1699                         fprintf(stderr, "%s %s ", obd_type,
1700                                 obd_uuid2str(&qctl.obd_uuid));
1701                 fprintf(stderr, "setquota failed: %s\n", strerror(errno));
1702                 return rc;
1703         }
1704
1705         return 0;
1706 }
1707
1708 #define BSLIMIT (1 << 0)
1709 #define BHLIMIT (1 << 1)
1710 #define ISLIMIT (1 << 2)
1711 #define IHLIMIT (1 << 3)
1712
1713 int lfs_setquota(int argc, char **argv)
1714 {
1715         int c, rc;
1716         struct if_quotactl qctl;
1717         char *mnt, *obd_type = (char *)qctl.obd_type;
1718         struct obd_dqblk *dqb = &qctl.qc_dqblk;
1719         struct option long_opts[] = {
1720                 {"user",            required_argument, 0, 'u'},
1721                 {"group",           required_argument, 0, 'g'},
1722                 {"block-softlimit", required_argument, 0, 'b'},
1723                 {"block-hardlimit", required_argument, 0, 'B'},
1724                 {"inode-softlimit", required_argument, 0, 'i'},
1725                 {"inode-hardlimit", required_argument, 0, 'I'},
1726                 {0, 0, 0, 0}
1727         };
1728         unsigned limit_mask = 0;
1729         char *endptr;
1730
1731         if (has_times_option(argc, argv))
1732                 return lfs_setquota_times(argc, argv);
1733
1734         memset(&qctl, 0, sizeof(qctl));
1735         qctl.qc_cmd  = LUSTRE_Q_SETQUOTA;
1736         qctl.qc_type = UGQUOTA; /* UGQUOTA makes no sense for setquota,
1737                                  * so it can be used as a marker that qc_type
1738                                  * isn't reinitialized from command line */
1739
1740         optind = 0;
1741         while ((c = getopt_long(argc, argv, "b:B:i:I:g:u:", long_opts, NULL)) != -1) {
1742                 switch (c) {
1743                 case 'u':
1744                 case 'g':
1745                         if (qctl.qc_type != UGQUOTA) {
1746                                 fprintf(stderr, "error: -u and -g can't be used"
1747                                                 " more than once\n");
1748                                 return CMD_HELP;
1749                         }
1750                         qctl.qc_type = (c == 'u') ? USRQUOTA : GRPQUOTA;
1751                         rc = name2id(&qctl.qc_id, optarg,
1752                                      (qctl.qc_type == USRQUOTA) ? USER : GROUP);
1753                         if (rc) {
1754                                 qctl.qc_id = strtoul(optarg, &endptr, 10);
1755                                 if (*endptr != '\0') {
1756                                         fprintf(stderr, "error: can't find id "
1757                                                 "for name %s\n", optarg); 
1758                                         return CMD_HELP;
1759                                 }
1760                         }
1761                         break;
1762                 case 'b':
1763                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
1764                         dqb->dqb_bsoftlimit >>= 10;
1765                         limit_mask |= BSLIMIT;
1766                         break;
1767                 case 'B':
1768                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
1769                         dqb->dqb_bhardlimit >>= 10;
1770                         limit_mask |= BHLIMIT;
1771                         break;
1772                 case 'i':
1773                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
1774                         limit_mask |= ISLIMIT;
1775                         break;
1776                 case 'I':
1777                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
1778                         limit_mask |= IHLIMIT;
1779                         break;
1780                 default: /* getopt prints error message for us when opterr != 0 */
1781                         return CMD_HELP;
1782                 }
1783         }
1784
1785         if (qctl.qc_type == UGQUOTA) {
1786                 fprintf(stderr, "error: neither -u nor -g was specified\n");
1787                 return CMD_HELP;
1788         }
1789
1790         if (limit_mask == 0) {
1791                 fprintf(stderr, "error: at least one limit must be specified\n");
1792                 return CMD_HELP;
1793         }
1794
1795         if (optind != argc - 1) {
1796                 fprintf(stderr, "error: unexpected parameters encountered\n");
1797                 return CMD_HELP;
1798         }
1799
1800         mnt = argv[optind];
1801
1802         if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
1803             (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
1804                 /* sigh, we can't just set blimits/ilimits */
1805                 struct if_quotactl tmp_qctl = {.qc_cmd  = LUSTRE_Q_GETQUOTA,
1806                                                .qc_type = qctl.qc_type,
1807                                                .qc_id   = qctl.qc_id};
1808
1809                 rc = llapi_quotactl(mnt, &tmp_qctl);
1810                 if (rc < 0) {
1811                         fprintf(stderr, "error: setquota failed while retrieving"
1812                                         " current quota settings (%s)\n",
1813                                         strerror(errno));
1814                         return rc;
1815                 }
1816
1817                 if (!(limit_mask & BHLIMIT))
1818                         dqb->dqb_bhardlimit = tmp_qctl.qc_dqblk.dqb_bhardlimit;
1819                 if (!(limit_mask & BSLIMIT))
1820                         dqb->dqb_bsoftlimit = tmp_qctl.qc_dqblk.dqb_bsoftlimit;
1821                 if (!(limit_mask & IHLIMIT))
1822                         dqb->dqb_ihardlimit = tmp_qctl.qc_dqblk.dqb_ihardlimit;
1823                 if (!(limit_mask & ISLIMIT))
1824                         dqb->dqb_isoftlimit = tmp_qctl.qc_dqblk.dqb_isoftlimit;
1825
1826                 /* Keep grace times if we have got no softlimit arguments */
1827                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
1828                         dqb->dqb_valid |= QIF_BTIME;
1829                         dqb->dqb_btime = tmp_qctl.qc_dqblk.dqb_btime;
1830                 }
1831
1832                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
1833                         dqb->dqb_valid |= QIF_ITIME;
1834                         dqb->dqb_itime = tmp_qctl.qc_dqblk.dqb_itime;
1835                 }
1836         }
1837
1838         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
1839         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
1840
1841         rc = llapi_quotactl(mnt, &qctl);
1842         if (rc) {
1843                 if (*obd_type)
1844                         fprintf(stderr, "%s %s ", obd_type,
1845                                 obd_uuid2str(&qctl.obd_uuid));
1846                 fprintf(stderr, "setquota failed: %s\n", strerror(errno));
1847                 return rc;
1848         }
1849
1850         return 0;
1851 }
1852
1853 static inline char *type2name(int check_type)
1854 {
1855         if (check_type == USRQUOTA)
1856                 return "user";
1857         else if (check_type == GRPQUOTA)
1858                 return "group";
1859         else
1860                 return "unknown";
1861 }
1862
1863
1864 /* Converts seconds value into format string
1865  * result is returned in buf
1866  * Notes:
1867  *        1. result is in descenting order: 1w2d3h4m5s
1868  *        2. zero fields are not filled (except for p. 3): 5d1s
1869  *        3. zero seconds value is presented as "0s"
1870  */
1871 static void sec2str(time_t seconds, char *buf)
1872 {
1873         const char spec[] = "smhdw";
1874         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
1875         unsigned long c;
1876         char* tail = buf;
1877         int i;
1878
1879         for (i = sizeof(mult) / sizeof(mult[0]) - 1 ; i >= 0; i--) {
1880                 c = seconds / mult[i];
1881
1882                 if (c > 0 || (i == 0 && buf == tail))
1883                         tail += snprintf(tail, 40-(tail-buf), "%lu%c", c, spec[i]);
1884
1885                 seconds %= mult[i];
1886         }
1887 }
1888
1889
1890 static void diff2str(time_t seconds, char *buf, time_t now)
1891 {
1892
1893         buf[0] = 0;
1894         if (!seconds)
1895                 return;
1896         if (seconds <= now) {
1897                 strcpy(buf, "none");
1898                 return;
1899         }
1900         sec2str(seconds - now, buf);
1901 }
1902
1903 static void print_quota_title(char *name, struct if_quotactl *qctl)
1904 {
1905         printf("Disk quotas for %s %s (%cid %u):\n",
1906                type2name(qctl->qc_type), name,
1907                *type2name(qctl->qc_type), qctl->qc_id);
1908         printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
1909                "Filesystem",
1910                "kbytes", "quota", "limit", "grace",
1911                "files", "quota", "limit", "grace");
1912 }
1913
1914 static void print_quota(char *mnt, struct if_quotactl *qctl, int type, int rc)
1915 {
1916         time_t now;
1917
1918         time(&now);
1919
1920         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA) {
1921                 int bover = 0, iover = 0;
1922                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
1923
1924                 if (dqb->dqb_bhardlimit &&
1925                     toqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
1926                         bover = 1;
1927                 } else if (dqb->dqb_bsoftlimit &&
1928                            toqb(dqb->dqb_curspace) >= dqb->dqb_bsoftlimit) {
1929                         if (dqb->dqb_btime > now) {
1930                                 bover = 2;
1931                         } else {
1932                                 bover = 3;
1933                         }
1934                 }
1935
1936                 if (dqb->dqb_ihardlimit &&
1937                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
1938                         iover = 1;
1939                 } else if (dqb->dqb_isoftlimit &&
1940                            dqb->dqb_curinodes >= dqb->dqb_isoftlimit) {
1941                         if (dqb->dqb_btime > now) {
1942                                 iover = 2;
1943                         } else {
1944                                 iover = 3;
1945                         }
1946                 }
1947
1948 #if 0           /* XXX: always print quotas even when no usages */
1949                 if (dqb->dqb_curspace || dqb->dqb_curinodes)
1950 #endif
1951                 {
1952                         char numbuf[3][32];
1953                         char timebuf[40];
1954
1955                         if (strlen(mnt) > 15)
1956                                 printf("%s\n%15s", mnt, "");
1957                         else
1958                                 printf("%15s", mnt);
1959
1960                         if (bover)
1961                                 diff2str(dqb->dqb_btime, timebuf, now);
1962                         if (rc == -1 && errno == EREMOTEIO)
1963                                 sprintf(numbuf[0], LPU64"*",
1964                                         toqb(dqb->dqb_curspace));
1965                         else
1966                                 sprintf(numbuf[0],
1967                                         (dqb->dqb_valid & QIF_SPACE) ?
1968                                         LPU64 : "["LPU64"]",
1969                                         toqb(dqb->dqb_curspace));
1970                         if (type == QC_GENERAL)
1971                                 sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS)
1972                                         ? LPU64 : "["LPU64"]",
1973                                         dqb->dqb_bsoftlimit);
1974                         else
1975                                 sprintf(numbuf[1], "%s", "");
1976                         sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS)
1977                                 ? LPU64 : "["LPU64"]", dqb->dqb_bhardlimit);
1978                         printf(" %7s%c %6s %7s %7s",
1979                                numbuf[0], bover ? '*' : ' ', numbuf[1],
1980                                numbuf[2], bover > 1 ? timebuf : "");
1981
1982                         if (iover)
1983                                 diff2str(dqb->dqb_itime, timebuf, now);
1984
1985                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_INODES) ?
1986                                 LPU64 : "["LPU64"]", dqb->dqb_curinodes);
1987                        if (type == QC_GENERAL)
1988                                 sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS)
1989                                         ? LPU64 : "["LPU64"]",
1990                                         dqb->dqb_isoftlimit);
1991                         else
1992                                 sprintf(numbuf[1], "%s", "");
1993                         sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
1994                                 LPU64 : "["LPU64"]", dqb->dqb_ihardlimit);
1995                         if (type != QC_OSTIDX)
1996                                 printf(" %7s%c %6s %7s %7s",
1997                                        numbuf[0], iover ? '*' : ' ', numbuf[1],
1998                                        numbuf[2], iover > 1 ? timebuf : "");
1999                         printf("\n");
2000                 }
2001         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO ||
2002                    qctl->qc_cmd == Q_GETOINFO) {
2003                 char bgtimebuf[40];
2004                 char igtimebuf[40];
2005
2006                 sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf);
2007                 sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf);
2008                 printf("Block grace time: %s; Inode grace time: %s\n",
2009                        bgtimebuf, igtimebuf);
2010         }
2011 }
2012
2013 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt)
2014 {
2015         int rc = 0, rc1 = 0, count = 0;
2016         __u32 valid = qctl->qc_valid;
2017
2018         rc = llapi_get_obd_count(mnt, &count, is_mdt);
2019         if (rc) {
2020                 fprintf(stderr, "can not get %s count: %s\n",
2021                         is_mdt ? "mdt": "ost", strerror(errno));
2022                 return rc;
2023         }
2024
2025         for (qctl->qc_idx = 0; qctl->qc_idx < count; qctl->qc_idx++) {
2026                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
2027                 rc = llapi_quotactl(mnt, qctl);
2028                 if (rc) {
2029                         /* It is remote client case. */
2030                         if (errno == EOPNOTSUPP) {
2031                                 rc = 0;
2032                                 goto out;
2033                         }
2034
2035                         if (!rc1)
2036                                 rc1 = rc;
2037                         fprintf(stderr, "quotactl %s%d failed.\n",
2038                                 is_mdt ? "mdt": "ost", qctl->qc_idx);
2039                         continue;
2040                 }
2041
2042                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl, qctl->qc_valid, 0);
2043         }
2044
2045 out:
2046         qctl->qc_valid = valid;
2047         return rc ? : rc1;
2048 }
2049
2050 static int lfs_quota(int argc, char **argv)
2051 {
2052         int c;
2053         char *mnt, *name = NULL;
2054         struct if_quotactl qctl = { .qc_cmd = LUSTRE_Q_GETQUOTA,
2055                                     .qc_type = UGQUOTA };
2056         char *obd_type = (char *)qctl.obd_type;
2057         char *obd_uuid = (char *)qctl.obd_uuid.uuid;
2058         int rc, rc1 = 0, rc2 = 0, rc3 = 0, verbose = 0, pass = 0;
2059         char *endptr;
2060         __u32 valid = QC_GENERAL, idx = 0;
2061
2062         optind = 0;
2063         while ((c = getopt(argc, argv, "ugto:i:I:v")) != -1) {
2064                 switch (c) {
2065                 case 'u':
2066                         if (qctl.qc_type != UGQUOTA) {
2067                                 fprintf(stderr, "error: use either -u or -g\n");
2068                                 return CMD_HELP;
2069                         }
2070                         qctl.qc_type = USRQUOTA;
2071                         break;
2072                 case 'g':
2073                         if (qctl.qc_type != UGQUOTA) {
2074                                 fprintf(stderr, "error: use either -u or -g\n");
2075                                 return CMD_HELP;
2076                         }
2077                         qctl.qc_type = GRPQUOTA;
2078                         break;
2079                 case 't':
2080                         qctl.qc_cmd = LUSTRE_Q_GETINFO;
2081                         break;
2082                 case 'o':
2083                         valid = qctl.qc_valid = QC_UUID;
2084                         strncpy(obd_uuid, optarg, sizeof(qctl.obd_uuid));
2085                         break;
2086                 case 'i':
2087                         valid = qctl.qc_valid = QC_MDTIDX;
2088                         idx = qctl.qc_idx = atoi(optarg);
2089                         break;
2090                 case 'I':
2091                         valid = qctl.qc_valid = QC_OSTIDX;
2092                         idx = qctl.qc_idx = atoi(optarg);
2093                         break;
2094                 case 'v':
2095                         verbose = 1;
2096                         break;
2097                 default:
2098                         fprintf(stderr, "error: %s: option '-%c' "
2099                                         "unrecognized\n", argv[0], c);
2100                         return CMD_HELP;
2101                 }
2102         }
2103
2104         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
2105         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA && qctl.qc_type == UGQUOTA &&
2106             optind == argc - 1) {
2107 ug_output:
2108                 memset(&qctl, 0, sizeof(qctl)); /* spoiled by print_*_quota */
2109                 qctl.qc_cmd = LUSTRE_Q_GETQUOTA;
2110                 qctl.qc_valid = valid;
2111                 qctl.qc_idx = idx;
2112                 if (pass++ == 0) {
2113                         qctl.qc_type = USRQUOTA;
2114                         qctl.qc_id = geteuid();
2115                 } else {
2116                         qctl.qc_type = GRPQUOTA;
2117                         qctl.qc_id = getegid();
2118                 }
2119                 rc = id2name(&name, qctl.qc_id,
2120                              (qctl.qc_type == USRQUOTA) ? USER : GROUP);
2121                 if (rc)
2122                         name = "<unknown>";
2123         /* lfs quota -u username /path/to/lustre/mount */
2124         } else if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) {
2125                 /* options should be followed by u/g-name and mntpoint */
2126                 if (optind + 2 != argc || qctl.qc_type == UGQUOTA) {
2127                         fprintf(stderr, "error: missing quota argument(s)\n");
2128                         return CMD_HELP;
2129                 }
2130
2131                 name = argv[optind++];
2132                 rc = name2id(&qctl.qc_id, name,
2133                              (qctl.qc_type == USRQUOTA) ? USER : GROUP);
2134                 if (rc) {
2135                         qctl.qc_id = strtoul(name, &endptr, 10);
2136                         if (*endptr != '\0') {
2137                                 fprintf(stderr, "error: can't find id for name "
2138                                         "%s\n", name);
2139                                 return CMD_HELP;
2140                         }
2141                 }
2142         } else if (optind + 1 != argc || qctl.qc_type == UGQUOTA) {
2143                 fprintf(stderr, "error: missing quota info argument(s)\n");
2144                 return CMD_HELP;
2145         }
2146
2147         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA)
2148                 print_quota_title(name, &qctl);
2149
2150         mnt = argv[optind];
2151
2152         rc1 = llapi_quotactl(mnt, &qctl);
2153         if (rc1 == -1 && errno == EALREADY) {
2154                 fprintf(stderr, "\n%s quotas are not enabled.\n",
2155                         qctl.qc_type == USRQUOTA ? "user" : "group");
2156                 goto out;
2157         }
2158         if (rc1 && *obd_type)
2159                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
2160
2161         if (qctl.qc_valid != QC_GENERAL)
2162                 mnt = "";
2163
2164         print_quota(mnt, &qctl, QC_GENERAL, rc1);
2165
2166         if (qctl.qc_valid == QC_GENERAL && qctl.qc_cmd != LUSTRE_Q_GETINFO && verbose) {
2167                 rc2 = print_obd_quota(mnt, &qctl, 1);
2168                 rc3 = print_obd_quota(mnt, &qctl, 0);
2169         }
2170
2171         if (rc1 || rc2 || rc3)
2172                 printf("Some errors happened when getting quota info. "
2173                        "Some devices may be not working or deactivated. "
2174                        "The data in \"[]\" is inaccurate.\n");
2175
2176 out:
2177         if (pass == 1)
2178                 goto ug_output;
2179
2180         return 0;
2181 }
2182 #endif /* HAVE_SYS_QUOTA_H! */
2183
2184 static int flushctx_ioctl(char *mp)
2185 {
2186         int fd, rc;
2187
2188         fd = open(mp, O_RDONLY);
2189         if (fd == -1) {
2190                 fprintf(stderr, "flushctx: error open %s: %s\n",
2191                         mp, strerror(errno));
2192                 return -1;
2193         }
2194
2195         rc = ioctl(fd, LL_IOC_FLUSHCTX);
2196         if (rc == -1)
2197                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
2198                         mp, strerror(errno));
2199
2200         close(fd);
2201         return rc;
2202 }
2203
2204 static int lfs_flushctx(int argc, char **argv)
2205 {
2206         int     kdestroy = 0, c;
2207         FILE   *proc;
2208         char    procline[PATH_MAX], *line;
2209         int     rc = 0;
2210
2211         optind = 0;
2212         while ((c = getopt(argc, argv, "k")) != -1) {
2213                 switch (c) {
2214                 case 'k':
2215                         kdestroy = 1;
2216                         break;
2217                 default:
2218                         fprintf(stderr, "error: %s: option '-%c' "
2219                                         "unrecognized\n", argv[0], c);
2220                         return CMD_HELP;
2221                 }
2222         }
2223
2224         if (kdestroy) {
2225             int rc;
2226             if ((rc = system("kdestroy > /dev/null")) != 0) {
2227                 rc = WEXITSTATUS(rc);
2228                 fprintf(stderr, "error destroying tickets: %d, continuing\n", rc);
2229             }
2230         }
2231
2232         if (optind >= argc) {
2233                 /* flush for all mounted lustre fs. */
2234                 proc = fopen("/proc/mounts", "r");
2235                 if (!proc) {
2236                         fprintf(stderr, "error: %s: can't open /proc/mounts\n",
2237                                 argv[0]);
2238                         return -1;
2239                 }
2240
2241                 while ((line = fgets(procline, PATH_MAX, proc)) != NULL) {
2242                         char dev[PATH_MAX];
2243                         char mp[PATH_MAX];
2244                         char fs[PATH_MAX];
2245
2246                         if (sscanf(line, "%s %s %s", dev, mp, fs) != 3) {
2247                                 fprintf(stderr, "%s: unexpected format in "
2248                                                 "/proc/mounts\n",
2249                                         argv[0]);
2250                                 return -1;
2251                         }
2252
2253                         if (strcmp(fs, "lustre") != 0)
2254                                 continue;
2255                         /* we use '@' to determine it's a client. are there
2256                          * any other better way?
2257                          */
2258                         if (strchr(dev, '@') == NULL)
2259                                 continue;
2260
2261                         if (flushctx_ioctl(mp))
2262                                 rc = -1;
2263                 }
2264         } else {
2265                 /* flush fs as specified */
2266                 while (optind < argc) {
2267                         if (flushctx_ioctl(argv[optind++]))
2268                                 rc = -1;
2269                 }
2270         }
2271
2272         return rc;
2273 }
2274
2275 static int lfs_lsetfacl(int argc, char **argv)
2276 {
2277         argv[0]++;
2278         return(llapi_lsetfacl(argc, argv));
2279 }
2280
2281 static int lfs_lgetfacl(int argc, char **argv)
2282 {
2283         argv[0]++;
2284         return(llapi_lgetfacl(argc, argv));
2285 }
2286
2287 static int lfs_rsetfacl(int argc, char **argv)
2288 {
2289         argv[0]++;
2290         return(llapi_rsetfacl(argc, argv));
2291 }
2292
2293 static int lfs_rgetfacl(int argc, char **argv)
2294 {
2295         argv[0]++;
2296         return(llapi_rgetfacl(argc, argv));
2297 }
2298
2299 static int lfs_cp(int argc, char **argv)
2300 {
2301         return(llapi_cp(argc, argv));
2302 }
2303
2304 static int lfs_ls(int argc, char **argv)
2305 {
2306         return(llapi_ls(argc, argv));
2307 }
2308
2309 static int lfs_changelog(int argc, char **argv)
2310 {
2311         void *changelog_priv;
2312         struct changelog_rec *rec;
2313         long long startrec = 0, endrec = 0;
2314         char *mdd;
2315         struct option long_opts[] = {
2316                 {"follow", no_argument, 0, 'f'},
2317                 {0, 0, 0, 0}
2318         };
2319         char short_opts[] = "f";
2320         int rc, follow = 0;
2321
2322         optind = 0;
2323         while ((rc = getopt_long(argc, argv, short_opts,
2324                                 long_opts, NULL)) != -1) {
2325                 switch (rc) {
2326                 case 'f':
2327                         follow++;
2328                         break;
2329                 case '?':
2330                         return CMD_HELP;
2331                 default:
2332                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
2333                                 argv[0], argv[optind - 1]);
2334                         return CMD_HELP;
2335                 }
2336         }
2337         if (optind >= argc)
2338                 return CMD_HELP;
2339
2340         mdd = argv[optind++];
2341         if (argc > optind)
2342                 startrec = strtoll(argv[optind++], NULL, 10);
2343         if (argc > optind)
2344                 endrec = strtoll(argv[optind++], NULL, 10);
2345
2346         rc = llapi_changelog_start(&changelog_priv,
2347                                    CHANGELOG_FLAG_BLOCK |
2348                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
2349                                    mdd, startrec);
2350         if (rc < 0) {
2351                 fprintf(stderr, "Can't start changelog: %s\n",
2352                         strerror(errno = -rc));
2353                 return rc;
2354         }
2355
2356         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
2357                 time_t secs;
2358                 struct tm ts;
2359
2360                 if (endrec && rec->cr_index > endrec)
2361                         break;
2362                 if (rec->cr_index < startrec)
2363                         continue;
2364
2365                 secs = rec->cr_time >> 30;
2366                 gmtime_r(&secs, &ts);
2367                 printf(LPU64" %02d%-5s %02d:%02d:%02d.%06d %04d.%02d.%02d "
2368                        "0x%x t="DFID, rec->cr_index, rec->cr_type,
2369                        changelog_type2str(rec->cr_type),
2370                        ts.tm_hour, ts.tm_min, ts.tm_sec,
2371                        (int)(rec->cr_time & ((1<<30) - 1)),
2372                        ts.tm_year+1900, ts.tm_mon+1, ts.tm_mday,
2373                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
2374                 if (rec->cr_namelen)
2375                         /* namespace rec includes parent and filename */
2376                         printf(" p="DFID" %.*s\n", PFID(&rec->cr_pfid),
2377                                rec->cr_namelen, rec->cr_name);
2378                 else
2379                         printf("\n");
2380
2381                 llapi_changelog_free(&rec);
2382         }
2383
2384         llapi_changelog_fini(&changelog_priv);
2385
2386         if (rc < 0)
2387                 fprintf(stderr, "Changelog: %s\n", strerror(errno = -rc));
2388
2389         return (rc == 1 ? 0 : rc);
2390 }
2391
2392 static int lfs_changelog_clear(int argc, char **argv)
2393 {
2394         long long endrec;
2395         int rc;
2396
2397         if (argc != 4)
2398                 return CMD_HELP;
2399
2400         endrec = strtoll(argv[3], NULL, 10);
2401
2402         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
2403         if (rc)
2404                 fprintf(stderr, "%s error: %s\n", argv[0],
2405                         strerror(errno = -rc));
2406         return rc;
2407 }
2408
2409 static int lfs_fid2path(int argc, char **argv)
2410 {
2411         struct option long_opts[] = {
2412                 {"cur", no_argument, 0, 'c'},
2413                 {"link", required_argument, 0, 'l'},
2414                 {"rec", required_argument, 0, 'r'},
2415                 {0, 0, 0, 0}
2416         };
2417         char  short_opts[] = "cl:r:";
2418         char *device, *fid, *path;
2419         long long recno = -1;
2420         int linkno = -1;
2421         int lnktmp;
2422         int printcur = 0;
2423         int rc;
2424
2425         optind = 0;
2426
2427         while ((rc = getopt_long(argc, argv, short_opts,
2428                                 long_opts, NULL)) != -1) {
2429                 switch (rc) {
2430                 case 'c':
2431                         printcur++;
2432                         break;
2433                 case 'l':
2434                         linkno = strtol(optarg, NULL, 10);
2435                         break;
2436                 case 'r':
2437                         recno = strtoll(optarg, NULL, 10);
2438                         break;
2439                 case '?':
2440                         return CMD_HELP;
2441                 default:
2442                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
2443                                 argv[0], argv[optind - 1]);
2444                         return CMD_HELP;
2445                 }
2446         }
2447         device = argv[optind++];
2448         fid = argv[optind++];
2449         if (optind != argc)
2450                 return CMD_HELP;
2451
2452         path = calloc(1, PATH_MAX);
2453
2454         lnktmp = (linkno >= 0) ? linkno : 0;
2455         while (1) {
2456                 int oldtmp = lnktmp;
2457                 long long rectmp = recno;
2458                 rc = llapi_fid2path(device, fid, path, PATH_MAX, &rectmp,
2459                                     &lnktmp);
2460                 if (rc < 0) {
2461                         fprintf(stderr, "%s error: %s\n", argv[0],
2462                                 strerror(errno = -rc));
2463                         break;
2464                 }
2465
2466                 if (printcur)
2467                         fprintf(stdout, "%lld %s\n", rectmp, path);
2468                 else
2469                         fprintf(stdout, "%s\n", path);
2470
2471                 if (linkno >= 0)
2472                         /* specified linkno */
2473                         break;
2474                 if (oldtmp == lnktmp)
2475                         /* no more links */
2476                         break;
2477         }
2478
2479         free(path);
2480         return rc;
2481 }
2482
2483 static int lfs_path2fid(int argc, char **argv)
2484 {
2485         char *path;
2486         lustre_fid fid;
2487         int rc;
2488
2489         if (argc != 2)
2490                 return CMD_HELP;
2491
2492         path = argv[1];
2493         rc = llapi_path2fid(path, &fid);
2494         if (rc) {
2495                 fprintf(stderr, "can't get fid for %s: %s\n", path,
2496                         strerror(errno = -rc));
2497                 return rc;
2498         }
2499
2500         printf(DFID"\n", PFID(&fid));
2501
2502         return 0;
2503 }
2504
2505 int main(int argc, char **argv)
2506 {
2507         int rc;
2508
2509         setlinebuf(stdout);
2510
2511         ptl_initialize(argc, argv);
2512         if (obd_initialize(argc, argv) < 0)
2513                 exit(2);
2514         if (dbg_initialize(argc, argv) < 0)
2515                 exit(3);
2516
2517         Parser_init("lfs > ", cmdlist);
2518
2519         if (argc > 1) {
2520                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
2521         } else {
2522                 rc = Parser_commands();
2523         }
2524
2525         obd_finalize(argc, argv);
2526         return rc < 0 ? -rc : rc;
2527 }
2528