Whamcloud - gitweb
b=15534
[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
77 #include <libcfs/libcfsutil.h>
78 #include "obdctl.h"
79
80 unsigned int libcfs_subsystem_debug = 0;
81
82 /* all functions */
83 static int lfs_setstripe(int argc, char **argv);
84 static int lfs_find(int argc, char **argv);
85 static int lfs_getstripe(int argc, char **argv);
86 static int lfs_osts(int argc, char **argv);
87 static int lfs_df(int argc, char **argv);
88 static int lfs_check(int argc, char **argv);
89 static int lfs_catinfo(int argc, char **argv);
90 #ifdef HAVE_SYS_QUOTA_H
91 static int lfs_quotachown(int argc, char **argv);
92 static int lfs_quotacheck(int argc, char **argv);
93 static int lfs_quotaon(int argc, char **argv);
94 static int lfs_quotaoff(int argc, char **argv);
95 static int lfs_setquota(int argc, char **argv);
96 static int lfs_quota(int argc, char **argv);
97 static int lfs_quotainv(int argc, char **argv);
98 #endif
99 static int lfs_flushctx(int argc, char **argv);
100 static int lfs_join(int argc, char **argv);
101 static int lfs_lsetfacl(int argc, char **argv);
102 static int lfs_lgetfacl(int argc, char **argv);
103 static int lfs_rsetfacl(int argc, char **argv);
104 static int lfs_rgetfacl(int argc, char **argv);
105 static int lfs_cp(int argc, char **argv);
106 static int lfs_ls(int argc, char **argv);
107 static int lfs_poollist(int argc, char **argv);
108 static int lfs_changelog(int argc, char **argv);
109 static int lfs_changelog_clear(int argc, char **argv);
110 static int lfs_fid2path(int argc, char **argv);
111 static int lfs_path2fid(int argc, char **argv);
112
113 /* all avaialable commands */
114 command_t cmdlist[] = {
115         {"setstripe", lfs_setstripe, 0,
116          "Create a new file with a specific striping pattern or\n"
117          "set the default striping pattern on an existing directory or\n"
118          "delete the default striping pattern from an existing directory\n"
119          "usage: setstripe [--size|-s stripe_size] [--offset|-o start_ost]\n"
120          "                 [--count|-c stripe_count] [--pool|-p <pool>]\n"
121          "                 <dir|filename>\n"
122          "       or \n"
123          "       setstripe -d <dir>   (to delete default striping)\n"
124          "\tstripe_size:  Number of bytes on each OST (0 filesystem default)\n"
125          "\t              Can be specified with k, m or g (in KB, MB and GB\n"
126          "\t              respectively)\n"
127          "\tstart_ost:    OST index of first stripe (-1 filesystem default)\n"
128          "\tstripe_count: Number of OSTs to stripe over (0 default, -1 all)\n"
129          "\tpool:         Name of OST pool"},
130         {"getstripe", lfs_getstripe, 0,
131          "To list the striping info for a given file or files in a\n"
132          "directory or recursively for all files in a directory tree.\n"
133          "usage: getstripe [--obd|-O <uuid>] [--quiet | -q] [--verbose | -v]\n"
134          "                 [--count | -c ] [--size | -s ] [--index | -i ]\n"
135          "                 [--offset | -o ] [--pool | -p ]\n"
136          "                 [--recursive | -r] <dir|file> ..."},
137         {"pool_list", lfs_poollist, 0,
138          "List pools or pool OSTs\n"
139          "usage: pool_list <fsname>[.<pool>] | <pathname>\n"},
140         {"find", lfs_find, 0,
141          "To find files that match given parameters recursively in a directory tree.\n"
142          "usage: find <dir|file> ... \n"
143          "     [[!] --atime|-A [+-]N] [[!] --mtime|-M [+-]N] [[!] --ctime|-C [+-]N]\n"
144          "     [--maxdepth|-D N] [[!] --name|-n <pattern>] [--print0|-P]\n"
145          "     [--print|-p] [--obd|-O <uuid[s]>] [[!] --size|-s [+-]N[bkMGTP]]\n"
146          "     [[!] --type|-t <filetype>] [[!] --gid|-g|--group|-G <gid>|<gname>]\n"
147          "     [[!] --uid|-u|--user|-U <uid>|<uname>]\n"
148          "     [[!] --pool <pool>]\n"
149          "\t !: used before an option indicates 'NOT' the requested attribute\n"
150          "\t -: used before an value indicates 'AT MOST' the requested value\n"
151          "\t +: used before an option indicates 'AT LEAST' the requested value\n"},
152         {"check", lfs_check, 0,
153          "Display the status of MDS or OSTs (as specified in the command)\n"
154          "or all the servers (MDS and OSTs).\n"
155          "usage: check <osts|mds|servers>"},
156         {"catinfo", lfs_catinfo, 0,
157          "Show information of specified type logs.\n"
158          "usage: catinfo {keyword} [node name]\n"
159          "\tkeywords are one of followings: config, deletions.\n"
160          "\tnode name must be provided when use keyword config."},
161         {"join", lfs_join, 0,
162          "join two lustre files into one - join A, B, will be like cat B >> A & del B\n"
163          "usage: join <filename_A> <filename_B>\n"},
164         {"osts", lfs_osts, 0, "osts"},
165         {"df", lfs_df, 0,
166          "report filesystem disk space usage or inodes usage"
167          "of each MDS and all OSDs or a batch belonging to a specific pool .\n"
168          "Usage: df [-i] [-h] [--pool|-p <fsname>[.<pool>] [path]"},
169 #ifdef HAVE_SYS_QUOTA_H
170         {"quotachown",lfs_quotachown, 0,
171          "Change files' owner or group on the specified filesystem.\n"
172          "usage: quotachown [-i] <filesystem>\n"
173          "\t-i: ignore error if file is not exist\n"},
174         {"quotacheck", lfs_quotacheck, 0,
175          "Scan the specified filesystem for disk usage, and create,\n"
176          "or update quota files.\n"
177          "usage: quotacheck [ -ug ] <filesystem>"},
178         {"quotaon", lfs_quotaon, 0, "Turn filesystem quotas on.\n"
179          "usage: quotaon [ -ugf ] <filesystem>"},
180         {"quotaoff", lfs_quotaoff, 0, "Turn filesystem quotas off.\n"
181          "usage: quotaoff [ -ug ] <filesystem>"},
182         {"setquota", lfs_setquota, 0, "Set filesystem quotas.\n"
183          "usage: setquota <-u|-g> <uname>|<uid>|<gname>|<gid>\n"
184          "                -b <block-softlimit> -B <block-hardlimit>\n"
185          "                -i <inode-softlimit> -I <inode-hardlimit> <filesystem>\n"
186          "       setquota -t <-u|-g> <block-grace> <inode-grace> <filesystem>\n"
187          "       setquota <-u|--user|-g|--group> <uname>|<uid>|<gname>|<gid>\n"
188          "                [--block-softlimit <block-softlimit>]\n"
189          "                [--block-hardlimit <block-hardlimit>]\n"
190          "                [--inode-softlimit <inode-softlimit>]\n"
191          "                [--inode-hardlimit <inode-hardlimit>] <filesystem>\n"
192          "       setquota [-t] <-u|--user|-g|--group>\n"
193          "                [--block-grace <block-grace>]\n"
194          "                [--inode-grace <inode-grace>] <filesystem>\n"
195          "       -b can be used instead of --block-softlimit/--block-grace\n"
196          "       -B can be used instead of --block-hardlimit\n"
197          "       -i can be used instead of --inode-softlimit/--inode-grace\n"
198          "       -I can be used instead of --inode-hardlimit"},
199         {"quota", lfs_quota, 0, "Display disk usage and limits.\n"
200          "usage: quota [-v] [-o obd_uuid|-i mdt_idx|-I ost_idx]\n" 
201          "             [<-u|-g> <uname>|<uid>|<gname>|<gid>] <filesystem>\n"
202          "       quota [-o obd_uuid|-i mdt_idx|-I ost_idx] -t <-u|-g> <filesystem>"},
203         {"quotainv", lfs_quotainv, 0, "Invalidate quota data.\n"
204          "usage: quotainv [-u|-g] <filesystem>"},
205 #endif
206         {"flushctx", lfs_flushctx, 0, "Flush security context for current user.\n"
207          "usage: flushctx [-k] [mountpoint...]"},
208         {"lsetfacl", lfs_lsetfacl, 0,
209          "Remote user setfacl for user/group on the same remote client.\n"
210          "usage: lsetfacl [-bkndRLPvh] [{-m|-x} acl_spec] [{-M|-X} acl_file] file ..."},
211         {"lgetfacl", lfs_lgetfacl, 0,
212          "Remote user getfacl for user/group on the same remote client.\n"
213          "usage: lgetfacl [-dRLPvh] file ..."},
214         {"rsetfacl", lfs_rsetfacl, 0,
215          "Remote user setfacl for user/group on other clients.\n"
216          "usage: rsetfacl [-bkndRLPvh] [{-m|-x} acl_spec] [{-M|-X} acl_file] file ..."},
217         {"rgetfacl", lfs_rgetfacl, 0,
218          "Remote user getfacl for user/group on other clients.\n"
219          "usage: rgetfacl [-dRLPvh] file ..."},
220         {"cp", lfs_cp, 0,
221          "Remote user copy files and directories.\n"
222          "usage: cp [OPTION]... [-T] SOURCE DEST\n\tcp [OPTION]... SOURCE... DIRECTORY\n\tcp [OPTION]... -t DIRECTORY SOURCE..."},
223         {"ls", lfs_ls, 0,
224          "Remote user list directory contents.\n"
225          "usage: ls [OPTION]... [FILE]..."},
226         {"changelog", lfs_changelog, 0,
227          "Show the metadata changes on an MDT."
228          "\nusage: changelog [--follow] <mdtname> [startrec [endrec]]"
229          "\n(note: --follow is only valid when run on MDT node)"},
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                 {0, 0, 0, 0}
828         };
829         char short_opts[] = "hO:qrvcsiop";
830         int c, rc;
831         struct find_param param = { 0 };
832
833         optind = 0;
834         while ((c = getopt_long(argc, argv, short_opts,
835                                 long_opts, NULL)) != -1) {
836                 switch (c) {
837                 case 'O':
838                         if (param.obduuid) {
839                                 fprintf(stderr,
840                                         "error: %s: only one obduuid allowed",
841                                         argv[0]);
842                                 return CMD_HELP;
843                         }
844                         param.obduuid = (struct obd_uuid *)optarg;
845                         break;
846                 case 'q':
847                         param.quiet++;
848                         break;
849                 case 'r':
850                         param.recursive = 1;
851                         break;
852                 case 'v':
853                         param.verbose = VERBOSE_ALL | VERBOSE_DETAIL;
854                         param.quiet = 0;
855                         break;
856                 case 'c':
857                         param.verbose |= VERBOSE_COUNT;
858                         break;
859                 case 's':
860                         param.verbose |= VERBOSE_SIZE;
861                         break;
862                 case 'i':
863                 case 'o':
864                         param.verbose |= VERBOSE_OFFSET;
865                         break;
866                 case 'p':
867                         param.verbose |= VERBOSE_POOL;
868                         break;
869                 case '?':
870                         return CMD_HELP;
871                 default:
872                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
873                                 argv[0], argv[optind - 1]);
874                         return CMD_HELP;
875                 }
876         }
877
878         if (optind >= argc)
879                 return CMD_HELP;
880
881         param.maxdepth = param.recursive ? -1 : 1;
882
883         do {
884                 rc = llapi_getstripe(argv[optind], &param);
885         } while (++optind < argc && !rc);
886
887         if (rc)
888                 fprintf(stderr, "error: %s failed for %s.\n",
889                         argv[0], argv[optind - 1]);
890         return rc;
891 }
892
893 static int lfs_osts(int argc, char **argv)
894 {
895         char mntdir[PATH_MAX] = {'\0'};
896         struct find_param param;
897         int index = 0, rc=0;
898
899         if (argc != 1)
900                 return CMD_HELP;
901
902         while (llapi_search_mounts(NULL, index++, mntdir, NULL) == 0) {
903                 memset(&param, 0, sizeof(param));
904                 rc = llapi_getstripe(mntdir, &param);
905                 if (rc) {
906                         fprintf(stderr, "error: %s: failed on %s\n",
907                                 argv[0], mntdir);
908                 }
909                 memset(mntdir, 0, PATH_MAX);
910         }
911
912         return rc;
913 }
914
915 #define COOK(value)                                                     \
916 ({                                                                      \
917         int radix = 0;                                                  \
918         while (value > 1024) {                                          \
919                 value /= 1024;                                          \
920                 radix++;                                                \
921         }                                                               \
922         radix;                                                          \
923 })
924 #define UUF     "%-20s"
925 #define CSF     "%9s"
926 #define CDF     "%9llu"
927 #define HSF     "%8s"
928 #define HDF     "%6.1f"
929 #define RSF     "%5s"
930 #define RDF     "%4d%%"
931
932 static int showdf(char *mntdir, struct obd_statfs *stat,
933                   char *uuid, int ishow, int cooked,
934                   char *type, int index, int rc)
935 {
936         long long avail, used, total;
937         double ratio = 0;
938         char *suffix = "KMGTPEZY";
939         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
940         char tbuf[20], ubuf[20], abuf[20], rbuf[20];
941
942         if (!uuid || !stat)
943                 return -EINVAL;
944
945         switch (rc) {
946         case 0:
947                 if (ishow) {
948                         avail = stat->os_ffree;
949                         used = stat->os_files - stat->os_ffree;
950                         total = stat->os_files;
951                 } else {
952                         int shift = cooked ? 0 : 10;
953
954                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
955                         used  = ((stat->os_blocks - stat->os_bfree) *
956                                  stat->os_bsize) >> shift;
957                         total = (stat->os_blocks * stat->os_bsize) >> shift;
958                 }
959
960                 if (total > 0)
961                         ratio = (double)used / (double)total;
962
963                 if (cooked) {
964                         int i;
965                         double cook_val;
966
967                         cook_val = (double)total;
968                         i = COOK(cook_val);
969                         if (i > 0)
970                                 sprintf(tbuf, HDF"%c", cook_val, suffix[i - 1]);
971                         else
972                                 sprintf(tbuf, CDF, total);
973
974                         cook_val = (double)used;
975                         i = COOK(cook_val);
976                         if (i > 0)
977                                 sprintf(ubuf, HDF"%c", cook_val, suffix[i - 1]);
978                         else
979                                 sprintf(ubuf, CDF, used);
980
981                         cook_val = (double)avail;
982                         i = COOK(cook_val);
983                         if (i > 0)
984                                 sprintf(abuf, HDF"%c", cook_val, suffix[i - 1]);
985                         else
986                                 sprintf(abuf, CDF, avail);
987                 } else {
988                         sprintf(tbuf, CDF, total);
989                         sprintf(ubuf, CDF, used);
990                         sprintf(abuf, CDF, avail);
991                 }
992
993                 sprintf(rbuf, RDF, (int)(ratio * 100));
994                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
995                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
996                 if (type)
997                         printf("[%s:%d]\n", type, index);
998                 else
999                         printf("\n");
1000
1001                 break;
1002         case -ENODATA:
1003                 printf(UUF": inactive device\n", uuid);
1004                 break;
1005         default:
1006                 printf(UUF": %s\n", uuid, strerror(-rc));
1007                 break;
1008         }
1009
1010         return 0;
1011 }
1012
1013 static int mntdf(char *mntdir, char *fsname, char *pool, int ishow, int cooked)
1014 {
1015         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
1016         struct obd_uuid uuid_buf;
1017         char *poolname = NULL;
1018         __u32 index;
1019         int rc;
1020
1021         if (pool) {
1022                 poolname = strchr(pool, '.');
1023                 if (poolname != NULL) {
1024                         if (strncmp(fsname, pool, strlen(fsname))) {
1025                                 fprintf(stderr, "filesystem name incorrect\n");
1026                                 return -ENODEV;
1027                         }
1028                         poolname++;
1029                 } else
1030                         poolname = pool;
1031         }
1032
1033         if (ishow)
1034                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
1035                        "UUID", "Inodes", "IUsed", "IFree",
1036                        "IUse%", "Mounted on");
1037         else
1038                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
1039                        "UUID", cooked ? "bytes" : "1K-blocks",
1040                        "Used", "Available", "Use%", "Mounted on");
1041
1042         for (index = 0; ; index++) {
1043                 memset(&stat_buf, 0, sizeof(struct obd_statfs));
1044                 memset(&uuid_buf, 0, sizeof(struct obd_uuid));
1045                 rc = llapi_obd_statfs(mntdir, LL_STATFS_MDC, index,
1046                                       &stat_buf, &uuid_buf);
1047                 if (rc == -ENODEV)
1048                         break;
1049
1050                 if (rc == -EAGAIN)
1051                         continue;
1052
1053                 if (rc == -ENOTCONN || rc == -ETIMEDOUT || rc == -EIO ||
1054                     rc == -ENODATA || rc == 0) {
1055                         showdf(mntdir, &stat_buf, obd_uuid2str(&uuid_buf),
1056                                ishow, cooked, "MDT", index, rc);
1057                 } else {
1058                         fprintf(stderr,
1059                                 "error: llapi_obd_statfs(%s): %s (%d)\n",
1060                                 obd_uuid2str(&uuid_buf), strerror(-rc), rc);
1061                         return rc;
1062                 }
1063                 if (rc == 0) {
1064                         sum.os_ffree += stat_buf.os_ffree;
1065                         sum.os_files += stat_buf.os_files;
1066                 }
1067         }
1068
1069         for (index = 0; ; index++) {
1070                 memset(&stat_buf, 0, sizeof(struct obd_statfs));
1071                 memset(&uuid_buf, 0, sizeof(struct obd_uuid));
1072                 rc = llapi_obd_statfs(mntdir, LL_STATFS_LOV, index,
1073                                       &stat_buf, &uuid_buf);
1074                 if (rc == -ENODEV)
1075                         break;
1076
1077                 if (rc == -EAGAIN)
1078                         continue;
1079
1080                 if (llapi_search_ost(fsname, poolname,
1081                                      obd_uuid2str(&uuid_buf)) != 1)
1082                         continue;
1083
1084                 if (rc == -ENOTCONN || rc == -ETIMEDOUT || rc == -EIO ||
1085                     rc == -ENODATA || rc == 0) {
1086                         showdf(mntdir, &stat_buf, obd_uuid2str(&uuid_buf),
1087                                ishow, cooked, "OST", index, rc);
1088                 } else {
1089                         fprintf(stderr,
1090                                 "error: llapi_obd_statfs failed: %s (%d)\n",
1091                                 strerror(-rc), rc);
1092                         return rc;
1093                 }
1094                 if (rc == 0) {
1095                         sum.os_blocks += stat_buf.os_blocks * stat_buf.os_bsize;
1096                         sum.os_bfree  += stat_buf.os_bfree * stat_buf.os_bsize;
1097                         sum.os_bavail += stat_buf.os_bavail * stat_buf.os_bsize;
1098                 }
1099         }
1100
1101         printf("\n");
1102         showdf(mntdir, &sum, "filesystem summary:", ishow, cooked, NULL, 0,0);
1103
1104         return 0;
1105 }
1106
1107 static int lfs_df(int argc, char **argv)
1108 {
1109         char *path = NULL;
1110         char *mntdir = NULL;
1111         int ishow = 0, cooked = 0;
1112         int c, rc = 0;
1113         char fsname[PATH_MAX], *pool_name = NULL;
1114         struct option long_opts[] = {
1115                 {"pool", required_argument, 0, 'p'},
1116                 {0, 0, 0, 0}
1117         };
1118
1119         optind = 0;
1120         while ((c = getopt_long(argc, argv, "ihp:", long_opts, NULL)) != -1) {
1121                 switch (c) {
1122                 case 'i':
1123                         ishow = 1;
1124                         break;
1125                 case 'h':
1126                         cooked = 1;
1127                         break;
1128                 case 'p':
1129                         pool_name = optarg;
1130                         break;
1131                 default:
1132                         return CMD_HELP;
1133                 }
1134         }
1135         if (optind < argc )
1136                 path = argv[optind];
1137
1138         if ((mntdir = malloc(PATH_MAX)) == NULL) {
1139                 fprintf(stderr, "error: cannot allocate %d bytes\n",
1140                         PATH_MAX);
1141                 return -ENOMEM;
1142         }
1143         memset(mntdir, 0, PATH_MAX);
1144
1145         if (path) {
1146                 char rpath[PATH_MAX] = {'\0'};
1147
1148                 if (!realpath(path, rpath)) {
1149                         rc = -errno;
1150                         fprintf(stderr, "error: invalid path '%s': %s\n",
1151                                         path, strerror(-rc));
1152                 } else {
1153                         rc = llapi_search_mounts(rpath, 0, mntdir, fsname);
1154                         if (rc == 0 && mntdir[0] != '\0') {
1155                                 rc = mntdf(mntdir, fsname, pool_name,
1156                                            ishow, cooked);
1157                                 printf("\n");
1158                         }
1159                 }
1160         } else {
1161                 int index = 0;
1162
1163                 while (llapi_search_mounts(NULL, index++, mntdir, fsname)==0) {
1164                         rc = mntdf(mntdir, fsname, pool_name,
1165                                    ishow, cooked);
1166                         if (rc)
1167                                 break;
1168                         printf("\n");
1169                 }
1170         }
1171
1172         free(mntdir);
1173         return rc;
1174 }
1175
1176 static int lfs_check(int argc, char **argv)
1177 {
1178         int rc;
1179         char mntdir[PATH_MAX] = {'\0'};
1180         int num_types = 1;
1181         char *obd_types[2];
1182         char obd_type1[4];
1183         char obd_type2[4];
1184
1185         if (argc != 2)
1186                 return CMD_HELP;
1187
1188         obd_types[0] = obd_type1;
1189         obd_types[1] = obd_type2;
1190
1191         if (strcmp(argv[1], "osts") == 0) {
1192                 strcpy(obd_types[0], "osc");
1193         } else if (strcmp(argv[1], "mds") == 0) {
1194                 strcpy(obd_types[0], "mdc");
1195         } else if (strcmp(argv[1], "servers") == 0) {
1196                 num_types = 2;
1197                 strcpy(obd_types[0], "osc");
1198                 strcpy(obd_types[1], "mdc");
1199         } else {
1200                 fprintf(stderr, "error: %s: option '%s' unrecognized\n",
1201                                 argv[0], argv[1]);
1202                         return CMD_HELP;
1203         }
1204
1205         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
1206         if (rc < 0 || mntdir[0] == '\0') {
1207                 fprintf(stderr, "No suitable Lustre mount found\n");
1208                 return rc;
1209         }
1210
1211         rc = llapi_target_iterate(num_types, obd_types,
1212                                   mntdir, llapi_ping_target);
1213
1214         if (rc)
1215                 fprintf(stderr, "error: %s: %s status failed\n",
1216                                 argv[0],argv[1]);
1217
1218         return rc;
1219
1220 }
1221
1222 static int lfs_catinfo(int argc, char **argv)
1223 {
1224         char mntdir[PATH_MAX] = {'\0'};
1225         int rc;
1226
1227         if (argc < 2 || (!strcmp(argv[1],"config") && argc < 3))
1228                 return CMD_HELP;
1229
1230         if (strcmp(argv[1], "config") && strcmp(argv[1], "deletions"))
1231                 return CMD_HELP;
1232
1233         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
1234         if (rc == 0 && mntdir[0] != '\0') {
1235                 if (argc == 3)
1236                         rc = llapi_catinfo(mntdir, argv[1], argv[2]);
1237                 else
1238                         rc = llapi_catinfo(mntdir, argv[1], NULL);
1239         } else {
1240                 fprintf(stderr, "no lustre_lite mounted.\n");
1241                 rc = -1;
1242         }
1243
1244         return rc;
1245 }
1246
1247 int lfs_join(int argc, char **argv)
1248 {
1249         char *name_head, *name_tail;
1250         int fd, rc;
1251         loff_t size;
1252
1253         if (argc != 3)
1254                 return CMD_HELP;
1255         name_head = argv[1];
1256         fd = open(name_head, O_WRONLY);
1257         if (fd < 0) {
1258                 fprintf(stderr, "Can not open name_head %s rc=%d\n",
1259                         name_head, fd);
1260                 return fd;
1261         }
1262         size = lseek(fd, 0, SEEK_END);
1263         if (size % JOIN_FILE_ALIGN) {
1264                 fprintf(stderr,"head file %s size %llu must be mutiple of %d\n",
1265                         name_head, (long long)size, JOIN_FILE_ALIGN);
1266                 rc = -EINVAL;
1267                 goto out;
1268         }
1269         name_tail = argv[2];
1270         rc = ioctl(fd, LL_IOC_JOIN, name_tail);
1271 out:
1272         close(fd);
1273         if (rc) {
1274                 fprintf(stderr, "Lustre joining files: %s, %s, failed\n",
1275                         argv[1], argv[2]);
1276         }
1277         return rc;
1278 }
1279
1280 #ifdef HAVE_SYS_QUOTA_H
1281 static int lfs_quotachown(int argc, char **argv)
1282 {
1283
1284         int c,rc;
1285         int flag = 0;
1286
1287         optind = 0;
1288         while ((c = getopt(argc, argv, "i")) != -1) {
1289                 switch (c) {
1290                 case 'i':
1291                         flag++;
1292                         break;
1293                 default:
1294                         fprintf(stderr, "error: %s: option '-%c' "
1295                                         "unrecognized\n", argv[0], c);
1296                         return CMD_HELP;
1297                 }
1298         }
1299         if (optind == argc)
1300                 return CMD_HELP;
1301         rc = llapi_quotachown(argv[optind], flag);
1302         if(rc)
1303                 fprintf(stderr,"error: change file owner/group failed.\n");
1304         return rc;
1305 }
1306
1307 static int lfs_quotacheck(int argc, char **argv)
1308 {
1309         int c, check_type = 0;
1310         char *mnt;
1311         struct if_quotacheck qchk;
1312         struct if_quotactl qctl;
1313         char *obd_type = (char *)qchk.obd_type;
1314         int rc;
1315
1316         memset(&qchk, 0, sizeof(qchk));
1317
1318         optind = 0;
1319         while ((c = getopt(argc, argv, "ug")) != -1) {
1320                 switch (c) {
1321                 case 'u':
1322                         check_type |= 0x01;
1323                         break;
1324                 case 'g':
1325                         check_type |= 0x02;
1326                         break;
1327                 default:
1328                         fprintf(stderr, "error: %s: option '-%c' "
1329                                         "unrecognized\n", argv[0], c);
1330                         return CMD_HELP;
1331                 }
1332         }
1333
1334         if (check_type)
1335                 check_type--;
1336         else    /* do quotacheck for both user & group quota by default */
1337                 check_type = 0x02;
1338
1339         if (argc == optind)
1340                 return CMD_HELP;
1341
1342         mnt = argv[optind];
1343
1344         rc = llapi_quotacheck(mnt, check_type);
1345         if (rc) {
1346                 fprintf(stderr, "quotacheck failed: %s\n", strerror(errno));
1347                 return rc;
1348         }
1349
1350         rc = llapi_poll_quotacheck(mnt, &qchk);
1351         if (rc) {
1352                 if (*obd_type)
1353                         fprintf(stderr, "%s %s ", obd_type,
1354                                 obd_uuid2str(&qchk.obd_uuid));
1355                 fprintf(stderr, "quota check failed: %s\n", strerror(errno));
1356                 return rc;
1357         }
1358
1359         memset(&qctl, 0, sizeof(qctl));
1360         qctl.qc_cmd = LUSTRE_Q_QUOTAON;
1361         qctl.qc_type = check_type;
1362         rc = llapi_quotactl(mnt, &qctl);
1363         if (rc && errno != EALREADY) {
1364                 if (*obd_type)
1365                         fprintf(stderr, "%s %s ", (char *)qctl.obd_type,
1366                                 obd_uuid2str(&qctl.obd_uuid));
1367                 fprintf(stderr, "%s turn on quota failed: %s\n",
1368                         argv[0], strerror(errno));
1369                 return rc;
1370         }
1371
1372         return 0;
1373 }
1374
1375 static int lfs_quotaon(int argc, char **argv)
1376 {
1377         int c;
1378         char *mnt;
1379         struct if_quotactl qctl;
1380         char *obd_type = (char *)qctl.obd_type;
1381         int rc;
1382
1383         memset(&qctl, 0, sizeof(qctl));
1384         qctl.qc_cmd = LUSTRE_Q_QUOTAON;
1385
1386         optind = 0;
1387         while ((c = getopt(argc, argv, "ugf")) != -1) {
1388                 switch (c) {
1389                 case 'u':
1390                         qctl.qc_type |= 0x01;
1391                         break;
1392                 case 'g':
1393                         qctl.qc_type |= 0x02;
1394                         break;
1395                 case 'f':
1396                         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
1397                         break;
1398                 default:
1399                         fprintf(stderr, "error: %s: option '-%c' "
1400                                         "unrecognized\n", argv[0], c);
1401                         return CMD_HELP;
1402                 }
1403         }
1404
1405         if (qctl.qc_type)
1406                 qctl.qc_type--;
1407         else /* by default, enable quota for both user & group */
1408                 qctl.qc_type = 0x02;
1409
1410         if (argc == optind)
1411                 return CMD_HELP;
1412
1413         mnt = argv[optind];
1414
1415         rc = llapi_quotactl(mnt, &qctl);
1416         if (rc) {
1417                 if (errno == EALREADY) {
1418                         fprintf(stderr, "\n%s quotas are enabled already.\n",
1419                                 qctl.qc_type == 0x02 ? "user/group" :
1420                                 (qctl.qc_type == 0x00 ? "user" : "group"));
1421                         rc = 0;
1422                 } else if (errno == ENOENT) {
1423                         fprintf(stderr, "error: cannot find quota database, "
1424                                         "make sure you have run quotacheck\n");
1425                 } else {
1426                         if (*obd_type)
1427                                 fprintf(stderr, "%s %s ", obd_type,
1428                                         obd_uuid2str(&qctl.obd_uuid));
1429                         fprintf(stderr, "%s failed: %s\n", argv[0],
1430                                 strerror(errno));
1431                 }
1432         }
1433
1434         return rc;
1435 }
1436
1437 static int lfs_quotaoff(int argc, char **argv)
1438 {
1439         int c;
1440         char *mnt;
1441         struct if_quotactl qctl;
1442         char *obd_type = (char *)qctl.obd_type;
1443         int rc;
1444
1445         memset(&qctl, 0, sizeof(qctl));
1446         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
1447
1448         optind = 0;
1449         while ((c = getopt(argc, argv, "ug")) != -1) {
1450                 switch (c) {
1451                 case 'u':
1452                         qctl.qc_type |= 0x01;
1453                         break;
1454                 case 'g':
1455                         qctl.qc_type |= 0x02;
1456                         break;
1457                 default:
1458                         fprintf(stderr, "error: %s: option '-%c' "
1459                                         "unrecognized\n", argv[0], c);
1460                         return CMD_HELP;
1461                 }
1462         }
1463
1464         if (qctl.qc_type)
1465                 qctl.qc_type--;
1466         else /* by default, disable quota for both user & group */
1467                 qctl.qc_type = 0x02;
1468
1469         if (argc == optind)
1470                 return CMD_HELP;
1471
1472         mnt = argv[optind];
1473
1474         rc = llapi_quotactl(mnt, &qctl);
1475         if (rc) {
1476                 if (errno == EALREADY) {
1477                         fprintf(stderr, "\n%s quotas are disabled already.\n",
1478                                 qctl.qc_type == 0x02 ? "user/group" :
1479                                 (qctl.qc_type == 0x00 ? "user" : "group"));
1480                         rc = 0;
1481                 } else {
1482                         if (*obd_type)
1483                                 fprintf(stderr, "%s %s ", obd_type,
1484                                         obd_uuid2str(&qctl.obd_uuid));
1485                         fprintf(stderr, "quotaoff failed: %s\n",
1486                                 strerror(errno));
1487                 }
1488         }
1489
1490         return rc;
1491 }
1492
1493 static int lfs_quotainv(int argc, char **argv)
1494 {
1495         int c;
1496         char *mnt;
1497         struct if_quotactl qctl;
1498         int rc;
1499
1500         memset(&qctl, 0, sizeof(qctl));
1501         qctl.qc_cmd = LUSTRE_Q_INVALIDATE;
1502
1503         optind = 0;
1504         while ((c = getopt(argc, argv, "ugf")) != -1) {
1505                 switch (c) {
1506                 case 'u':
1507                         qctl.qc_type |= 0x01;
1508                         break;
1509                 case 'g':
1510                         qctl.qc_type |= 0x02;
1511                         break;
1512                 case 'f':
1513                         qctl.qc_cmd = LUSTRE_Q_FINVALIDATE;
1514                         break;
1515                 default:
1516                         fprintf(stderr, "error: %s: option '-%c' "
1517                                         "unrecognized\n", argv[0], c);
1518                         return CMD_HELP;
1519                 }
1520         }
1521
1522         if (qctl.qc_type)
1523                 qctl.qc_type--;
1524         else /* by default, invalidate quota for both user & group */
1525                 qctl.qc_type = 0x02;
1526
1527         if (argc == optind)
1528                 return CMD_HELP;
1529
1530         mnt = argv[optind];
1531
1532         rc = llapi_quotactl(mnt, &qctl);
1533         if (rc) {
1534                 fprintf(stderr, "quotainv failed: %s\n", strerror(errno));
1535                 return rc;
1536         }
1537
1538         return 0;
1539 }
1540
1541 #define ARG2INT(nr, str, msg)                                           \
1542 do {                                                                    \
1543         char *endp;                                                     \
1544         nr = strtol(str, &endp, 0);                                     \
1545         if (*endp) {                                                    \
1546                 fprintf(stderr, "error: bad %s: %s\n", msg, str);       \
1547                 return CMD_HELP;                                        \
1548         }                                                               \
1549 } while (0)
1550
1551 #define ADD_OVERFLOW(a,b) ((a + b) < a) ? (a = ULONG_MAX) : (a = a + b)
1552
1553 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
1554  * returns the value or ULONG_MAX on integer overflow or incorrect format
1555  * Notes:
1556  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
1557  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
1558  *        3. empty integer value is interpreted as 0
1559  */
1560
1561 static unsigned long str2sec(const char* timestr) {
1562         const char spec[] = "smhdw";
1563         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
1564         unsigned long val = 0;
1565         char *tail;
1566
1567         if (strpbrk(timestr, spec) == NULL) {
1568                 /* no specifiers inside the time string,
1569                    should treat it as an integer value */
1570                 val = strtoul(timestr, &tail, 10);
1571                 return *tail ? ULONG_MAX : val;
1572         }
1573
1574         /* format string is XXwXXdXXhXXmXXs */
1575         while (*timestr) {
1576                 unsigned long v;
1577                 int ind;
1578                 char* ptr;
1579
1580                 v = strtoul(timestr, &tail, 10);
1581                 if (v == ULONG_MAX || *tail == '\0')
1582                         /* value too large (ULONG_MAX or more)
1583                            or missing specifier */
1584                         goto error;
1585
1586                 ptr = strchr(spec, *tail);
1587                 if (ptr == NULL)
1588                         /* unknown specifier */
1589                         goto error;
1590
1591                 ind = ptr - spec;
1592
1593                 /* check if product will overflow the type */
1594                 if (!(v < ULONG_MAX / mult[ind]))
1595                         goto error;
1596
1597                 ADD_OVERFLOW(val, mult[ind] * v);
1598                 if (val == ULONG_MAX)
1599                         goto error;
1600
1601                 timestr = tail + 1;
1602         }
1603
1604         return val;
1605
1606 error:
1607         return ULONG_MAX;
1608 }
1609
1610 #define ARG2ULL(nr, str, defscale)                                      \
1611 do {                                                                    \
1612         unsigned long long limit, units = 0;                            \
1613         int rc;                                                         \
1614                                                                         \
1615         rc = parse_size(str, &limit, &units, 1);                        \
1616         if (rc < 0) {                                                   \
1617                 fprintf(stderr, "error: bad limit value %s\n", str);    \
1618                 return CMD_HELP;                                        \
1619         }                                                               \
1620         nr = ((units == 0) ? (defscale) : 1) * limit;                   \
1621 } while (0)
1622
1623 static inline int has_times_option(int argc, char **argv)
1624 {
1625         int i;
1626
1627         for (i = 1; i < argc; i++)
1628                 if (!strcmp(argv[i], "-t"))
1629                         return 1;
1630
1631         return 0;
1632 }
1633
1634 int lfs_setquota_times(int argc, char **argv)
1635 {
1636         int c, rc;
1637         struct if_quotactl qctl;
1638         char *mnt, *obd_type = (char *)qctl.obd_type;
1639         struct obd_dqblk *dqb = &qctl.qc_dqblk;
1640         struct obd_dqinfo *dqi = &qctl.qc_dqinfo;
1641         struct option long_opts[] = {
1642                 {"user",            no_argument,       0, 'u'},
1643                 {"group",           no_argument,       0, 'g'},
1644                 {"block-grace",     required_argument, 0, 'b'},
1645                 {"inode-grace",     required_argument, 0, 'i'},
1646                 {"times",           no_argument,       0, 't'},
1647                 {0, 0, 0, 0}
1648         };
1649
1650         memset(&qctl, 0, sizeof(qctl));
1651         qctl.qc_cmd  = LUSTRE_Q_SETINFO;
1652         qctl.qc_type = UGQUOTA;
1653
1654         optind = 0;
1655         while ((c = getopt_long(argc, argv, "ugb:i:t", long_opts, NULL)) != -1) {
1656                 switch (c) {
1657                 case 'u':
1658                 case 'g':
1659                         if (qctl.qc_type != UGQUOTA) {
1660                                 fprintf(stderr, "error: -u and -g can't be used "
1661                                                 "more than once\n");
1662                                 return CMD_HELP;
1663                         }
1664                         qctl.qc_type = (c == 'u') ? USRQUOTA : GRPQUOTA;
1665                         break;
1666                 case 'b':
1667                         if ((dqi->dqi_bgrace = str2sec(optarg)) == ULONG_MAX) {
1668                                 fprintf(stderr, "error: bad block-grace: %s\n",
1669                                         optarg);
1670                                 return CMD_HELP;
1671                         }
1672                         dqb->dqb_valid |= QIF_BTIME;
1673                         break;
1674                 case 'i':
1675                         if ((dqi->dqi_igrace = str2sec(optarg)) == ULONG_MAX) {
1676                                 fprintf(stderr, "error: bad inode-grace: %s\n",
1677                                         optarg);
1678                                 return CMD_HELP;
1679                         }
1680                         dqb->dqb_valid |= QIF_ITIME;
1681                         break;
1682                 case 't': /* Yes, of course! */
1683                         break;
1684                 default: /* getopt prints error message for us when opterr != 0 */
1685                         return CMD_HELP;
1686                 }
1687         }
1688
1689         if (qctl.qc_type == UGQUOTA) {
1690                 fprintf(stderr, "error: neither -u nor -g specified\n");
1691                 return CMD_HELP;
1692         }
1693
1694         if (optind != argc - 1) {
1695                 fprintf(stderr, "error: unexpected parameters encountered\n");
1696                 return CMD_HELP;
1697         }
1698
1699         mnt = argv[optind];
1700         rc = llapi_quotactl(mnt, &qctl);
1701         if (rc) {
1702                 if (*obd_type)
1703                         fprintf(stderr, "%s %s ", obd_type,
1704                                 obd_uuid2str(&qctl.obd_uuid));
1705                 fprintf(stderr, "setquota failed: %s\n", strerror(errno));
1706                 return rc;
1707         }
1708
1709         return 0;
1710 }
1711
1712 #define BSLIMIT (1 << 0)
1713 #define BHLIMIT (1 << 1)
1714 #define ISLIMIT (1 << 2)
1715 #define IHLIMIT (1 << 3)
1716
1717 int lfs_setquota(int argc, char **argv)
1718 {
1719         int c, rc;
1720         struct if_quotactl qctl;
1721         char *mnt, *obd_type = (char *)qctl.obd_type;
1722         struct obd_dqblk *dqb = &qctl.qc_dqblk;
1723         struct option long_opts[] = {
1724                 {"user",            required_argument, 0, 'u'},
1725                 {"group",           required_argument, 0, 'g'},
1726                 {"block-softlimit", required_argument, 0, 'b'},
1727                 {"block-hardlimit", required_argument, 0, 'B'},
1728                 {"inode-softlimit", required_argument, 0, 'i'},
1729                 {"inode-hardlimit", required_argument, 0, 'I'},
1730                 {0, 0, 0, 0}
1731         };
1732         unsigned limit_mask = 0;
1733         char *endptr;
1734
1735         if (has_times_option(argc, argv))
1736                 return lfs_setquota_times(argc, argv);
1737
1738         memset(&qctl, 0, sizeof(qctl));
1739         qctl.qc_cmd  = LUSTRE_Q_SETQUOTA;
1740         qctl.qc_type = UGQUOTA; /* UGQUOTA makes no sense for setquota,
1741                                  * so it can be used as a marker that qc_type
1742                                  * isn't reinitialized from command line */
1743
1744         optind = 0;
1745         while ((c = getopt_long(argc, argv, "u:g:b:B:i:I:", long_opts, NULL)) != -1) {
1746                 switch (c) {
1747                 case 'u':
1748                 case 'g':
1749                         if (qctl.qc_type != UGQUOTA) {
1750                                 fprintf(stderr, "error: -u and -g can't be used"
1751                                                 " more than once\n");
1752                                 return CMD_HELP;
1753                         }
1754                         qctl.qc_type = (c == 'u') ? USRQUOTA : GRPQUOTA;
1755                         rc = name2id(&qctl.qc_id, optarg,
1756                                      (qctl.qc_type == USRQUOTA) ? USER : GROUP);
1757                         if (rc) {
1758                                 qctl.qc_id = strtoul(optarg, &endptr, 10);
1759                                 if (*endptr != '\0') {
1760                                         fprintf(stderr, "error: can't find id "
1761                                                 "for name %s\n", optarg); 
1762                                         return CMD_HELP;
1763                                 }
1764                         }
1765                         break;
1766                 case 'b':
1767                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
1768                         dqb->dqb_bsoftlimit >>= 10;
1769                         limit_mask |= BSLIMIT;
1770                         break;
1771                 case 'B':
1772                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
1773                         dqb->dqb_bhardlimit >>= 10;
1774                         limit_mask |= BHLIMIT;
1775                         break;
1776                 case 'i':
1777                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
1778                         limit_mask |= ISLIMIT;
1779                         break;
1780                 case 'I':
1781                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
1782                         limit_mask |= IHLIMIT;
1783                         break;
1784                 default: /* getopt prints error message for us when opterr != 0 */
1785                         return CMD_HELP;
1786                 }
1787         }
1788
1789         if (qctl.qc_type == UGQUOTA) {
1790                 fprintf(stderr, "error: neither -u nor -g was specified\n");
1791                 return CMD_HELP;
1792         }
1793
1794         if (limit_mask == 0) {
1795                 fprintf(stderr, "error: at least one limit must be specified\n");
1796                 return CMD_HELP;
1797         }
1798
1799         if (optind != argc - 1) {
1800                 fprintf(stderr, "error: unexpected parameters encountered\n");
1801                 return CMD_HELP;
1802         }
1803
1804         mnt = argv[optind];
1805
1806         if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
1807             (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
1808                 /* sigh, we can't just set blimits/ilimits */
1809                 struct if_quotactl tmp_qctl = {.qc_cmd  = LUSTRE_Q_GETQUOTA,
1810                                                .qc_type = qctl.qc_type,
1811                                                .qc_id   = qctl.qc_id};
1812
1813                 rc = llapi_quotactl(mnt, &tmp_qctl);
1814                 if (rc < 0) {
1815                         fprintf(stderr, "error: setquota failed while retrieving"
1816                                         " current quota settings (%s)\n",
1817                                         strerror(errno));
1818                         return rc;
1819                 }
1820
1821                 if (!(limit_mask & BHLIMIT))
1822                         dqb->dqb_bhardlimit = tmp_qctl.qc_dqblk.dqb_bhardlimit;
1823                 if (!(limit_mask & BSLIMIT))
1824                         dqb->dqb_bsoftlimit = tmp_qctl.qc_dqblk.dqb_bsoftlimit;
1825                 if (!(limit_mask & IHLIMIT))
1826                         dqb->dqb_ihardlimit = tmp_qctl.qc_dqblk.dqb_ihardlimit;
1827                 if (!(limit_mask & ISLIMIT))
1828                         dqb->dqb_isoftlimit = tmp_qctl.qc_dqblk.dqb_isoftlimit;
1829
1830                 /* Keep grace times if we have got no softlimit arguments */
1831                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
1832                         dqb->dqb_valid |= QIF_BTIME;
1833                         dqb->dqb_btime = tmp_qctl.qc_dqblk.dqb_btime;
1834                 }
1835
1836                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
1837                         dqb->dqb_valid |= QIF_ITIME;
1838                         dqb->dqb_itime = tmp_qctl.qc_dqblk.dqb_itime;
1839                 }
1840         }
1841
1842         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
1843         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
1844
1845         rc = llapi_quotactl(mnt, &qctl);
1846         if (rc) {
1847                 if (*obd_type)
1848                         fprintf(stderr, "%s %s ", obd_type,
1849                                 obd_uuid2str(&qctl.obd_uuid));
1850                 fprintf(stderr, "setquota failed: %s\n", strerror(errno));
1851                 return rc;
1852         }
1853
1854         return 0;
1855 }
1856
1857 static inline char *type2name(int check_type)
1858 {
1859         if (check_type == USRQUOTA)
1860                 return "user";
1861         else if (check_type == GRPQUOTA)
1862                 return "group";
1863         else
1864                 return "unknown";
1865 }
1866
1867
1868 /* Converts seconds value into format string
1869  * result is returned in buf
1870  * Notes:
1871  *        1. result is in descenting order: 1w2d3h4m5s
1872  *        2. zero fields are not filled (except for p. 3): 5d1s
1873  *        3. zero seconds value is presented as "0s"
1874  */
1875 static void sec2str(time_t seconds, char *buf)
1876 {
1877         const char spec[] = "smhdw";
1878         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
1879         unsigned long c;
1880         char* tail = buf;
1881         int i;
1882
1883         for (i = sizeof(mult) / sizeof(mult[0]) - 1 ; i >= 0; i--) {
1884                 c = seconds / mult[i];
1885
1886                 if (c > 0 || (i == 0 && buf == tail))
1887                         tail += snprintf(tail, 40-(tail-buf), "%lu%c", c, spec[i]);
1888
1889                 seconds %= mult[i];
1890         }
1891 }
1892
1893
1894 static void diff2str(time_t seconds, char *buf, time_t now)
1895 {
1896
1897         buf[0] = 0;
1898         if (!seconds)
1899                 return;
1900         if (seconds <= now) {
1901                 strcpy(buf, "none");
1902                 return;
1903         }
1904         sec2str(seconds - now, buf);
1905 }
1906
1907 static void print_quota_title(char *name, struct if_quotactl *qctl)
1908 {
1909         printf("Disk quotas for %s %s (%cid %u):\n",
1910                type2name(qctl->qc_type), name,
1911                *type2name(qctl->qc_type), qctl->qc_id);
1912         printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
1913                "Filesystem",
1914                "kbytes", "quota", "limit", "grace",
1915                "files", "quota", "limit", "grace");
1916 }
1917
1918 static void print_quota(char *mnt, struct if_quotactl *qctl, int type, int rc)
1919 {
1920         time_t now;
1921
1922         time(&now);
1923
1924         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA) {
1925                 int bover = 0, iover = 0;
1926                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
1927
1928                 if (dqb->dqb_bhardlimit &&
1929                     toqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
1930                         bover = 1;
1931                 } else if (dqb->dqb_bsoftlimit &&
1932                            toqb(dqb->dqb_curspace) >= dqb->dqb_bsoftlimit) {
1933                         if (dqb->dqb_btime > now) {
1934                                 bover = 2;
1935                         } else {
1936                                 bover = 3;
1937                         }
1938                 }
1939
1940                 if (dqb->dqb_ihardlimit &&
1941                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
1942                         iover = 1;
1943                 } else if (dqb->dqb_isoftlimit &&
1944                            dqb->dqb_curinodes >= dqb->dqb_isoftlimit) {
1945                         if (dqb->dqb_btime > now) {
1946                                 iover = 2;
1947                         } else {
1948                                 iover = 3;
1949                         }
1950                 }
1951
1952 #if 0           /* XXX: always print quotas even when no usages */
1953                 if (dqb->dqb_curspace || dqb->dqb_curinodes)
1954 #endif
1955                 {
1956                         char numbuf[3][32];
1957                         char timebuf[40];
1958
1959                         if (strlen(mnt) > 15)
1960                                 printf("%s\n%15s", mnt, "");
1961                         else
1962                                 printf("%15s", mnt);
1963
1964                         if (bover)
1965                                 diff2str(dqb->dqb_btime, timebuf, now);
1966                         if (rc == -1 && errno == EREMOTEIO)
1967                                 sprintf(numbuf[0], LPU64"*",
1968                                         toqb(dqb->dqb_curspace));
1969                         else
1970                                 sprintf(numbuf[0],
1971                                         (dqb->dqb_valid & QIF_SPACE) ?
1972                                         LPU64 : "["LPU64"]",
1973                                         toqb(dqb->dqb_curspace));
1974                         if (type == QC_GENERAL)
1975                                 sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS)
1976                                         ? LPU64 : "["LPU64"]",
1977                                         dqb->dqb_bsoftlimit);
1978                         else
1979                                 sprintf(numbuf[1], "%s", "");
1980                         sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS)
1981                                 ? LPU64 : "["LPU64"]", dqb->dqb_bhardlimit);
1982                         printf(" %7s%c %6s %7s %7s",
1983                                numbuf[0], bover ? '*' : ' ', numbuf[1],
1984                                numbuf[2], bover > 1 ? timebuf : "");
1985
1986                         if (iover)
1987                                 diff2str(dqb->dqb_itime, timebuf, now);
1988
1989                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_INODES) ?
1990                                 LPU64 : "["LPU64"]", dqb->dqb_curinodes);
1991                        if (type == QC_GENERAL)
1992                                 sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS)
1993                                         ? LPU64 : "["LPU64"]",
1994                                         dqb->dqb_isoftlimit);
1995                         else
1996                                 sprintf(numbuf[1], "%s", "");
1997                         sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
1998                                 LPU64 : "["LPU64"]", dqb->dqb_ihardlimit);
1999                         if (type != QC_OSTIDX)
2000                                 printf(" %7s%c %6s %7s %7s",
2001                                        numbuf[0], iover ? '*' : ' ', numbuf[1],
2002                                        numbuf[2], iover > 1 ? timebuf : "");
2003                         printf("\n");
2004                 }
2005         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO ||
2006                    qctl->qc_cmd == Q_GETOINFO) {
2007                 char bgtimebuf[40];
2008                 char igtimebuf[40];
2009
2010                 sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf);
2011                 sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf);
2012                 printf("Block grace time: %s; Inode grace time: %s\n",
2013                        bgtimebuf, igtimebuf);
2014         }
2015 }
2016
2017 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt)
2018 {
2019         int rc = 0, rc1 = 0, count = 0;
2020         __u32 valid = qctl->qc_valid;
2021
2022         rc = llapi_get_obd_count(mnt, &count, is_mdt);
2023         if (rc) {
2024                 fprintf(stderr, "can not get %s count: %s\n",
2025                         is_mdt ? "mdt": "ost", strerror(errno));
2026                 return rc;
2027         }
2028
2029         for (qctl->qc_idx = 0; qctl->qc_idx < count; qctl->qc_idx++) {
2030                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
2031                 rc = llapi_quotactl(mnt, qctl);
2032                 if (rc) {
2033                         /* It is remote client case. */
2034                         if (errno == EOPNOTSUPP) {
2035                                 rc = 0;
2036                                 goto out;
2037                         }
2038
2039                         if (!rc1)
2040                                 rc1 = rc;
2041                         fprintf(stderr, "quotactl %s%d failed.\n",
2042                                 is_mdt ? "mdt": "ost", qctl->qc_idx);
2043                         continue;
2044                 }
2045
2046                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl, qctl->qc_valid, 0);
2047         }
2048
2049 out:
2050         qctl->qc_valid = valid;
2051         return rc ? : rc1;
2052 }
2053
2054 static int lfs_quota(int argc, char **argv)
2055 {
2056         int c;
2057         char *mnt, *name = NULL;
2058         struct if_quotactl qctl = { .qc_cmd = LUSTRE_Q_GETQUOTA,
2059                                     .qc_type = UGQUOTA };
2060         char *obd_type = (char *)qctl.obd_type;
2061         char *obd_uuid = (char *)qctl.obd_uuid.uuid;
2062         int rc, rc1 = 0, rc2 = 0, rc3 = 0, verbose = 0, pass = 0;
2063         char *endptr;
2064         __u32 valid = QC_GENERAL, idx = 0;
2065
2066         optind = 0;
2067         while ((c = getopt(argc, argv, "ugto:i:I:v")) != -1) {
2068                 switch (c) {
2069                 case 'u':
2070                         if (qctl.qc_type != UGQUOTA) {
2071                                 fprintf(stderr, "error: use either -u or -g\n");
2072                                 return CMD_HELP;
2073                         }
2074                         qctl.qc_type = USRQUOTA;
2075                         break;
2076                 case 'g':
2077                         if (qctl.qc_type != UGQUOTA) {
2078                                 fprintf(stderr, "error: use either -u or -g\n");
2079                                 return CMD_HELP;
2080                         }
2081                         qctl.qc_type = GRPQUOTA;
2082                         break;
2083                 case 't':
2084                         qctl.qc_cmd = LUSTRE_Q_GETINFO;
2085                         break;
2086                 case 'o':
2087                         valid = qctl.qc_valid = QC_UUID;
2088                         strncpy(obd_uuid, optarg, sizeof(qctl.obd_uuid));
2089                         break;
2090                 case 'i':
2091                         valid = qctl.qc_valid = QC_MDTIDX;
2092                         idx = qctl.qc_idx = atoi(optarg);
2093                         break;
2094                 case 'I':
2095                         valid = qctl.qc_valid = QC_OSTIDX;
2096                         idx = qctl.qc_idx = atoi(optarg);
2097                         break;
2098                 case 'v':
2099                         verbose = 1;
2100                         break;
2101                 default:
2102                         fprintf(stderr, "error: %s: option '-%c' "
2103                                         "unrecognized\n", argv[0], c);
2104                         return CMD_HELP;
2105                 }
2106         }
2107
2108         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
2109         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA && qctl.qc_type == UGQUOTA &&
2110             optind == argc - 1) {
2111 ug_output:
2112                 memset(&qctl, 0, sizeof(qctl)); /* spoiled by print_*_quota */
2113                 qctl.qc_cmd = LUSTRE_Q_GETQUOTA;
2114                 qctl.qc_valid = valid;
2115                 qctl.qc_idx = idx;
2116                 if (pass++ == 0) {
2117                         qctl.qc_type = USRQUOTA;
2118                         qctl.qc_id = geteuid();
2119                 } else {
2120                         qctl.qc_type = GRPQUOTA;
2121                         qctl.qc_id = getegid();
2122                 }
2123                 rc = id2name(&name, qctl.qc_id,
2124                              (qctl.qc_type == USRQUOTA) ? USER : GROUP);
2125                 if (rc)
2126                         name = "<unknown>";
2127         /* lfs quota -u username /path/to/lustre/mount */
2128         } else if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) {
2129                 /* options should be followed by u/g-name and mntpoint */
2130                 if (optind + 2 != argc || qctl.qc_type == UGQUOTA) {
2131                         fprintf(stderr, "error: missing quota argument(s)\n");
2132                         return CMD_HELP;
2133                 }
2134
2135                 name = argv[optind++];
2136                 rc = name2id(&qctl.qc_id, name,
2137                              (qctl.qc_type == USRQUOTA) ? USER : GROUP);
2138                 if (rc) {
2139                         qctl.qc_id = strtoul(name, &endptr, 10);
2140                         if (*endptr != '\0') {
2141                                 fprintf(stderr, "error: can't find id for name "
2142                                         "%s\n", name);
2143                                 return CMD_HELP;
2144                         }
2145                 }
2146         } else if (optind + 1 != argc || qctl.qc_type == UGQUOTA) {
2147                 fprintf(stderr, "error: missing quota info argument(s)\n");
2148                 return CMD_HELP;
2149         }
2150
2151         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA)
2152                 print_quota_title(name, &qctl);
2153
2154         mnt = argv[optind];
2155
2156         rc1 = llapi_quotactl(mnt, &qctl);
2157         if (rc1 == -1 && errno == EALREADY) {
2158                 fprintf(stderr, "\n%s quotas are not enabled.\n",
2159                         qctl.qc_type == USRQUOTA ? "user" : "group");
2160                 goto out;
2161         }
2162         if (rc1 && *obd_type)
2163                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
2164
2165         if (qctl.qc_valid != QC_GENERAL)
2166                 mnt = "";
2167
2168         print_quota(mnt, &qctl, QC_GENERAL, rc1);
2169
2170         if (qctl.qc_valid == QC_GENERAL && qctl.qc_cmd != LUSTRE_Q_GETINFO && verbose) {
2171                 rc2 = print_obd_quota(mnt, &qctl, 1);
2172                 rc3 = print_obd_quota(mnt, &qctl, 0);
2173         }
2174
2175         if (rc1 || rc2 || rc3)
2176                 printf("Some errors happened when getting quota info. "
2177                        "Some devices may be not working or deactivated. "
2178                        "The data in \"[]\" is inaccurate.\n");
2179
2180 out:
2181         if (pass == 1)
2182                 goto ug_output;
2183
2184         return 0;
2185 }
2186 #endif /* HAVE_SYS_QUOTA_H! */
2187
2188 static int flushctx_ioctl(char *mp)
2189 {
2190         int fd, rc;
2191
2192         fd = open(mp, O_RDONLY);
2193         if (fd == -1) {
2194                 fprintf(stderr, "flushctx: error open %s: %s\n",
2195                         mp, strerror(errno));
2196                 return -1;
2197         }
2198
2199         rc = ioctl(fd, LL_IOC_FLUSHCTX);
2200         if (rc == -1)
2201                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
2202                         mp, strerror(errno));
2203
2204         close(fd);
2205         return rc;
2206 }
2207
2208 static int lfs_flushctx(int argc, char **argv)
2209 {
2210         int     kdestroy = 0, c;
2211         FILE   *proc;
2212         char    procline[PATH_MAX], *line;
2213         int     rc = 0;
2214
2215         optind = 0;
2216         while ((c = getopt(argc, argv, "k")) != -1) {
2217                 switch (c) {
2218                 case 'k':
2219                         kdestroy = 1;
2220                         break;
2221                 default:
2222                         fprintf(stderr, "error: %s: option '-%c' "
2223                                         "unrecognized\n", argv[0], c);
2224                         return CMD_HELP;
2225                 }
2226         }
2227
2228         if (kdestroy)
2229                 system("kdestroy > /dev/null");
2230
2231         if (optind >= argc) {
2232                 /* flush for all mounted lustre fs. */
2233                 proc = fopen("/proc/mounts", "r");
2234                 if (!proc) {
2235                         fprintf(stderr, "error: %s: can't open /proc/mounts\n",
2236                                 argv[0]);
2237                         return -1;
2238                 }
2239
2240                 while ((line = fgets(procline, PATH_MAX, proc)) != NULL) {
2241                         char dev[PATH_MAX];
2242                         char mp[PATH_MAX];
2243                         char fs[PATH_MAX];
2244
2245                         if (sscanf(line, "%s %s %s", dev, mp, fs) != 3) {
2246                                 fprintf(stderr, "%s: unexpected format in "
2247                                                 "/proc/mounts\n",
2248                                         argv[0]);
2249                                 return -1;
2250                         }
2251
2252                         if (strcmp(fs, "lustre") != 0)
2253                                 continue;
2254                         /* we use '@' to determine it's a client. are there
2255                          * any other better way?
2256                          */
2257                         if (strchr(dev, '@') == NULL)
2258                                 continue;
2259
2260                         if (flushctx_ioctl(mp))
2261                                 rc = -1;
2262                 }
2263         } else {
2264                 /* flush fs as specified */
2265                 while (optind < argc) {
2266                         if (flushctx_ioctl(argv[optind++]))
2267                                 rc = -1;
2268                 }
2269         }
2270
2271         return rc;
2272 }
2273
2274 static int lfs_lsetfacl(int argc, char **argv)
2275 {
2276         argv[0]++;
2277         return(llapi_lsetfacl(argc, argv));
2278 }
2279
2280 static int lfs_lgetfacl(int argc, char **argv)
2281 {
2282         argv[0]++;
2283         return(llapi_lgetfacl(argc, argv));
2284 }
2285
2286 static int lfs_rsetfacl(int argc, char **argv)
2287 {
2288         argv[0]++;
2289         return(llapi_rsetfacl(argc, argv));
2290 }
2291
2292 static int lfs_rgetfacl(int argc, char **argv)
2293 {
2294         argv[0]++;
2295         return(llapi_rgetfacl(argc, argv));
2296 }
2297
2298 static int lfs_cp(int argc, char **argv)
2299 {
2300         return(llapi_cp(argc, argv));
2301 }
2302
2303 static int lfs_ls(int argc, char **argv)
2304 {
2305         return(llapi_ls(argc, argv));
2306 }
2307
2308 static int lfs_changelog(int argc, char **argv)
2309 {
2310         void *changelog_priv;
2311         struct changelog_rec *rec;
2312         long long startrec = 0, endrec = 0;
2313         char *mdd;
2314         struct option long_opts[] = {
2315                 {"follow", no_argument, 0, 'f'},
2316                 {0, 0, 0, 0}
2317         };
2318         char short_opts[] = "f";
2319         int rc, follow = 0;
2320
2321         optind = 0;
2322         while ((rc = getopt_long(argc, argv, short_opts,
2323                                 long_opts, NULL)) != -1) {
2324                 switch (rc) {
2325                 case 'f':
2326                         follow++;
2327                         break;
2328                 case '?':
2329                         return CMD_HELP;
2330                 default:
2331                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
2332                                 argv[0], argv[optind - 1]);
2333                         return CMD_HELP;
2334                 }
2335         }
2336         if (optind >= argc)
2337                 return CMD_HELP;
2338
2339         mdd = argv[optind++];
2340         if (argc > optind)
2341                 startrec = strtoll(argv[optind++], NULL, 10);
2342         if (argc > optind)
2343                 endrec = strtoll(argv[optind++], NULL, 10);
2344
2345         rc = llapi_changelog_start(&changelog_priv,
2346                                    follow ? CHANGELOG_FLAG_FOLLOW : 0,
2347                                    mdd, startrec);
2348         if (rc < 0) {
2349                 fprintf(stderr, "Can't start changelog: %s\n",
2350                         strerror(errno = -rc));
2351                 return rc;
2352         }
2353
2354         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
2355                 if (endrec && rec->cr_index > endrec)
2356                         break;
2357                 if (rec->cr_index < startrec)
2358                         continue;
2359
2360                 printf(LPU64" %02d%-5s "LPU64" 0x%x t="DFID,
2361                        rec->cr_index, rec->cr_type,
2362                        changelog_type2str(rec->cr_type), rec->cr_time,
2363                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
2364                 if (rec->cr_namelen)
2365                         /* namespace rec includes parent and filename */
2366                         printf(" p="DFID" %.*s\n", PFID(&rec->cr_pfid),
2367                                rec->cr_namelen, rec->cr_name);
2368                 else
2369                         printf("\n");
2370                 llapi_changelog_free(&rec);
2371         }
2372
2373         llapi_changelog_fini(&changelog_priv);
2374
2375         return (rc == 1 ? 0 : rc);
2376 }
2377
2378 static int lfs_changelog_clear(int argc, char **argv)
2379 {
2380         long long endrec;
2381         int rc;
2382
2383         if (argc != 4)
2384                 return CMD_HELP;
2385
2386         endrec = strtoll(argv[3], NULL, 10);
2387
2388         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
2389         if (rc)
2390                 fprintf(stderr, "%s error: %s\n", argv[0],
2391                         strerror(errno = -rc));
2392         return rc;
2393 }
2394
2395 static int lfs_fid2path(int argc, char **argv)
2396 {
2397         struct option long_opts[] = {
2398                 {"cur", no_argument, 0, 'c'},
2399                 {"link", required_argument, 0, 'l'},
2400                 {"rec", required_argument, 0, 'r'},
2401                 {0, 0, 0, 0}
2402         };
2403         char  short_opts[] = "cl:r:";
2404         char *device, *fid, *path;
2405         long long recno = -1;
2406         int linkno = -1;
2407         int lnktmp;
2408         int printcur = 0;
2409         int rc;
2410
2411         optind = 0;
2412
2413         while ((rc = getopt_long(argc, argv, short_opts,
2414                                 long_opts, NULL)) != -1) {
2415                 switch (rc) {
2416                 case 'c':
2417                         printcur++;
2418                         break;
2419                 case 'l':
2420                         linkno = strtol(optarg, NULL, 10);
2421                         break;
2422                 case 'r':
2423                         recno = strtoll(optarg, NULL, 10);
2424                         break;
2425                 case '?':
2426                         return CMD_HELP;
2427                 default:
2428                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
2429                                 argv[0], argv[optind - 1]);
2430                         return CMD_HELP;
2431                 }
2432         }
2433         device = argv[optind++];
2434         fid = argv[optind++];
2435         if (optind != argc)
2436                 return CMD_HELP;
2437
2438         path = calloc(1, PATH_MAX);
2439
2440         lnktmp = (linkno >= 0) ? linkno : 0;
2441         while (1) {
2442                 int oldtmp = lnktmp;
2443                 long long rectmp = recno;
2444                 rc = llapi_fid2path(device, fid, path, PATH_MAX, &rectmp,
2445                                     &lnktmp);
2446                 if (rc < 0) {
2447                         fprintf(stderr, "%s error: %s\n", argv[0],
2448                                 strerror(errno = -rc));
2449                         break;
2450                 }
2451
2452                 if (printcur)
2453                         fprintf(stdout, "%lld %s\n", rectmp, path);
2454                 else
2455                         fprintf(stdout, "%s\n", path);
2456
2457                 if (linkno >= 0)
2458                         /* specified linkno */
2459                         break;
2460                 if (oldtmp == lnktmp)
2461                         /* no more links */
2462                         break;
2463         }
2464
2465         free(path);
2466         return rc;
2467 }
2468
2469 static int lfs_path2fid(int argc, char **argv)
2470 {
2471         char *path;
2472         lustre_fid fid;
2473         int rc;
2474
2475         if (argc != 2)
2476                 return CMD_HELP;
2477
2478         path = argv[1];
2479         rc = llapi_path2fid(path, &fid);
2480         if (rc) {
2481                 fprintf(stderr, "can't get fid for %s: %s\n", path,
2482                         strerror(errno = -rc));
2483                 return rc;
2484         }
2485
2486         printf(DFID"\n", PFID(&fid));
2487
2488         return 0;
2489 }
2490
2491 int main(int argc, char **argv)
2492 {
2493         int rc;
2494
2495         setlinebuf(stdout);
2496
2497         ptl_initialize(argc, argv);
2498         if (obd_initialize(argc, argv) < 0)
2499                 exit(2);
2500         if (dbg_initialize(argc, argv) < 0)
2501                 exit(3);
2502
2503         Parser_init("lfs > ", cmdlist);
2504
2505         if (argc > 1) {
2506                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
2507         } else {
2508                 rc = Parser_commands();
2509         }
2510
2511         obd_finalize(argc, argv);
2512         return rc < 0 ? -rc : rc;
2513 }
2514