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