Whamcloud - gitweb
aaba0b298e4024fbe6f4002a34b0d8eee5fb1901
[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  *  Copyright (C) 2002 Cluster File Systems, Inc.
5  *   Author: Peter J. Braam <braam@clusterfs.com>
6  *   Author: Phil Schwan <phil@clusterfs.com>
7  *   Author: Robert Read <rread@clusterfs.com>
8  *
9  *   This file is part of Lustre, http://www.lustre.org.
10  *
11  *   Lustre is free software; you can redistribute it and/or
12  *   modify it under the terms of version 2 of the GNU General Public
13  *   License as published by the Free Software Foundation.
14  *
15  *   Lustre is distributed in the hope that it will be useful,
16  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *   GNU General Public License for more details.
19  *
20  *   You should have received a copy of the GNU General Public License
21  *   along with Lustre; if not, write to the Free Software
22  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23  *
24  */
25
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <getopt.h>
29 #include <string.h>
30 #include <mntent.h>
31 #include <errno.h>
32 #include <pwd.h>
33 #include <grp.h>
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <fcntl.h>
37 #include <dirent.h>
38 #include <time.h>
39 #include <ctype.h>
40
41 #include <lnet/api-support.h>
42 #include <lnet/lnetctl.h>
43
44 #include <liblustre.h>
45 #include <lustre/lustre_idl.h>
46 #include <lustre/liblustreapi.h>
47 #include <lustre/lustre_user.h>
48
49 #include "parser.h"
50 #include "obdctl.h"
51
52 unsigned int libcfs_subsystem_debug = 0;
53
54 /* all functions */
55 static int lfs_setstripe(int argc, char **argv);
56 static int lfs_find(int argc, char **argv);
57 static int lfs_getstripe(int argc, char **argv);
58 static int lfs_osts(int argc, char **argv);
59 static int lfs_df(int argc, char **argv);
60 static int lfs_check(int argc, char **argv);
61 static int lfs_catinfo(int argc, char **argv);
62 #ifdef HAVE_QUOTA_SUPPORT
63 static int lfs_quotachown(int argc, char **argv);
64 static int lfs_quotacheck(int argc, char **argv);
65 static int lfs_quotaon(int argc, char **argv);
66 static int lfs_quotaoff(int argc, char **argv);
67 static int lfs_setquota(int argc, char **argv);
68 static int lfs_quota(int argc, char **argv);
69 static int lfs_quotainv(int argc, char **argv);
70 #endif
71 static int lfs_join(int argc, char **argv);
72
73 /* all avaialable commands */
74 command_t cmdlist[] = {
75         {"setstripe", lfs_setstripe, 0,
76          "Create a new file with a specific striping pattern or\n"
77          "set the default striping pattern on an existing directory or\n"
78          "delete the default striping pattern from an existing directory\n"
79          "usage: setstripe <filename|dirname> <stripe_size> <stripe_index> <stripe_count>\n"
80          "       or \n"
81          "       setstripe <filename|dirname> [--size|-s stripe_size]\n"
82          "                                    [--index|-i stripe_index]\n"
83          "                                    [--count|-c stripe_count]\n"
84          "       or \n"
85          "       setstripe -d <dirname>   (to delete default striping)\n"
86          "\tstripe_size:  Number of bytes on each OST (0 filesystem default)\n"
87          "\t              Can be specified with k, m or g (in KB, MB and GB respectively)\n"
88          "\tstripe_index: OST index of first stripe (-1 filesystem default)\n"
89          "\tstripe_count: Number of OSTs to stripe over (0 default, -1 all)"},
90         {"getstripe", lfs_getstripe, 0,
91          "To list the striping info for a given filename or files in a\n"
92          "directory or recursively for all files in a directory tree.\n"
93          "usage: getstripe [--obd|-O <uuid>] [--quiet | -q] [--verbose | -v]\n"
94          "                 [--recursive | -r] <dir|file> ..."},
95         {"find", lfs_find, 0,
96          "To find files that match given parameters recursively in a directory tree.\n"
97          "usage: find <dir/file> ... \n"
98          "     [[!] --atime|-A [+-]N] [[!] --mtime|-M [+-]N] [[!] --ctime|-C [+-]N]\n"
99          "     [--maxdepth|-D N] [[!] --name|-n <pattern>] [--print0|-P]\n"
100          "     [--print|-p] [--obd|-O <uuid>] [[!] --type|-t <filetype>]\n"
101          "\t !: used before an option indicates 'NOT' the requested attribute\n"
102          "\t -: used before an value indicates 'AT MOST' the requested value\n"
103          "\t +: used before an option indicates 'AT LEAST' the requested value\n"},
104         {"check", lfs_check, 0,
105          "Display the status of MDS or OSTs (as specified in the command)\n"
106          "or all the servers (MDS and OSTs).\n"
107          "usage: check <osts|mds|servers>"},
108         {"catinfo", lfs_catinfo, 0,
109          "Show information of specified type logs.\n"
110          "usage: catinfo {keyword} [node name]\n"
111          "\tkeywords are one of followings: config, deletions.\n"
112          "\tnode name must be provided when use keyword config."},
113         {"join", lfs_join, 0,
114          "join two lustre files into one - join A, B, will be like cat B >> A & del B\n"
115          "usage: join <filename_A> <filename_B>\n"},
116         {"osts", lfs_osts, 0, "osts"},
117         {"df", lfs_df, 0,
118          "report filesystem disk space usage or inodes usage"
119          "of each MDS/OSD.\n"
120          "Usage: df [-i] [-h] [path]"},
121 #ifdef HAVE_QUOTA_SUPPORT
122         {"quotachown",lfs_quotachown, 0,
123          "Change files' owner or group on the specified filesystem.\n"
124          "usage: quotachown [-i] <filesystem>\n"
125          "\t-i: ignore error if file is not exist\n"},
126         {"quotacheck", lfs_quotacheck, 0,
127          "Scan the specified filesystem for disk usage, and create,\n"
128          "or update quota files.\n"
129          "usage: quotacheck [ -ug ] <filesystem>"},
130         {"quotaon", lfs_quotaon, 0, "Turn filesystem quotas on.\n"
131          "usage: quotaon [ -ugf ] <filesystem>"},
132         {"quotaoff", lfs_quotaoff, 0, "Turn filesystem quotas off.\n"
133          "usage: quotaoff [ -ug ] <filesystem>"},
134         {"setquota", lfs_setquota, 0, "Set filesystem quotas.\n"
135          "usage: setquota [ -u | -g ] <name> <block-softlimit> <block-hardlimit> <inode-softlimit> <inode-hardlimit> <filesystem>\n"
136          "       setquota -t [ -u | -g ] <block-grace> <inode-grace> <filesystem>"},
137         {"quota", lfs_quota, 0, "Display disk usage and limits.\n"
138          "usage: quota [ -o obd_uuid ] [{-u|-g  <name>}|-t] <filesystem>"},
139         {"quotainv", lfs_quotainv, 0, "Invalidate quota data.\n"
140          "usage: quotainv [-u|-g] <filesystem>"},
141 #endif
142         {"help", Parser_help, 0, "help"},
143         {"exit", Parser_quit, 0, "quit"},
144         {"quit", Parser_quit, 0, "quit"},
145         { 0, 0, 0, NULL }
146 };
147
148 /* functions */
149 static int lfs_setstripe(int argc, char **argv)
150 {
151         char *fname;
152         int result;
153         unsigned long long st_size;
154         int  st_offset, st_count;
155         char *end;
156         int c;
157         int delete = 0;
158         char *stripe_size_arg = NULL;
159         char *stripe_off_arg = NULL;
160         char *stripe_count_arg = NULL;
161         unsigned long long size_units;
162
163         struct option long_opts[] = {
164                 {"size",        required_argument, 0, 's'},
165                 {"count",       required_argument, 0, 'c'},
166                 {"index",       required_argument, 0, 'i'},
167                 {"delete",      no_argument,       0, 'd'},
168                 {0, 0, 0, 0}
169         };
170
171         st_size = 0;
172         st_offset = -1;
173         st_count = 0;
174         if (argc == 3 && strcmp(argv[1], "-d") == 0) {
175                 /* for compatibility with the existing positional parameter
176                  * usage */
177                 fname = argv[2];
178                 optind = 2;
179         } else if (argc == 5  && 
180                    (argv[2][0] != '-' || isdigit(argv[2][1])) &&
181                    (argv[3][0] != '-' || isdigit(argv[3][1])) &&
182                    (argv[4][0] != '-' || isdigit(argv[4][1])) ) {
183                 /* for compatibility with the existing positional parameter
184                  * usage */
185                 fname = argv[1];
186                 stripe_size_arg = argv[2];
187                 stripe_off_arg = argv[3];
188                 stripe_count_arg = argv[4];
189                 optind = 4;
190         } else {
191                 optind = 0;
192                 while ((c = getopt_long(argc, argv, "c:di:s:",
193                                                 long_opts, NULL)) >= 0) {
194                         switch (c) {
195                         case 0:
196                                 /* Long options. */
197                                 break;
198                         case 'c':
199                                 stripe_count_arg = optarg;
200                                 break;
201                         case 'd':
202                                 /* delete the default striping pattern */
203                                 delete = 1;
204                                 break;
205                         case 'i':
206                                 stripe_off_arg = optarg;
207                                 break;
208                         case 's':
209                                 stripe_size_arg = optarg;
210                                 break;
211                         case '?':
212                                 return CMD_HELP;
213                         default:
214                                 fprintf(stderr, "error: %s: option '%s' "
215                                                 "unrecognized\n",
216                                                 argv[0], argv[optind - 1]);
217                                 return CMD_HELP;
218                         }
219                 }
220
221                 if (optind < argc)
222                         fname = argv[optind];
223                 else
224                         return CMD_HELP;
225
226                 if (delete && 
227                     (stripe_size_arg != NULL || stripe_off_arg != NULL || 
228                      stripe_count_arg != NULL)) {
229                         fprintf(stderr, "error: %s: cannot specify -d with "
230                                         "-s, -c or -i options\n",
231                                         argv[0]);
232                         return CMD_HELP;
233                 }
234         }
235
236         if (optind != argc - 1) {
237                 fprintf(stderr, "error: %s: only 1 filename|dirname can be "
238                                 "specified: '%s'\n",
239                                 argv[0], argv[argc-1]);
240                 return CMD_HELP;
241         }
242
243         /* get the stripe size */
244         if (stripe_size_arg != NULL) {
245                 result = parse_size(stripe_size_arg, &st_size, &size_units);
246                 if (result) {
247                         fprintf(stderr,"error: bad size '%s'\n",
248                                 stripe_size_arg);
249                         return result;
250                 }
251         }
252         /* get the stripe offset */
253         if (stripe_off_arg != NULL) {
254                 st_offset = strtoul(stripe_off_arg, &end, 0);
255                 if (*end != '\0') {
256                         fprintf(stderr, "error: %s: bad stripe offset '%s'\n",
257                                         argv[0], stripe_off_arg);
258                         return CMD_HELP;
259                 }
260         }
261         /* get the stripe count */
262         if (stripe_count_arg != NULL) {
263                 st_count = strtoul(stripe_count_arg, &end, 0);
264                 if (*end != '\0') {
265                         fprintf(stderr, "error: %s: bad stripe count '%s'\n",
266                                         argv[0], stripe_count_arg);
267                         return CMD_HELP;
268                 }
269         }
270
271         result = llapi_file_create(fname, st_size, st_offset, st_count, 0);
272         if (result)
273                 fprintf(stderr, "error: %s: create stripe file failed\n",
274                                 argv[0]);
275
276         return result;
277 }
278
279 static int set_time(time_t *time, time_t *set, char *str)
280 {
281         time_t t;
282         int res = 0;
283         
284         if (str[0] == '+')
285                 res = 1;
286         else if (str[0] == '-')
287                 res = -1;
288
289         if (res)
290                 str++;
291
292         t = strtol(str, NULL, 0);
293         if (*time < t * 24 * 60 * 60) {
294                 if (res)
295                         str--;
296                 fprintf(stderr, "Wrong time '%s' is specified.\n", str);
297                 return INT_MAX;
298         }
299
300         *set = *time - t * 24 * 60 * 60;
301         return res;
302 }
303
304 static int lfs_find(int argc, char **argv)
305 {
306         int new_fashion = 1;
307         int c, ret;
308         time_t t;
309         struct find_param param = { .maxdepth = -1 };
310         char str[1024];
311         struct option long_opts[] = {
312                 /* New find options. */
313                 {"atime",     required_argument, 0, 'A'},
314                 {"ctime",     required_argument, 0, 'C'},
315                 {"mtime",     required_argument, 0, 'M'},
316                 {"maxdepth",  required_argument, 0, 'D'},
317                 {"name",      required_argument, 0, 'n'},
318                 /* --obd is considered as a new option. */
319                 {"obd",       required_argument, 0, 'O'},
320                 {"ost",       required_argument, 0, 'O'},
321                 {"print",     no_argument,       0, 'P'},
322                 {"print0",    no_argument,       0, 'p'},
323                 /* Old find options. */
324                 {"quiet",     no_argument,       0, 'q'},
325                 {"recursive", no_argument,       0, 'r'},
326                 {"size",      required_argument, 0, 's'},
327                 {"type",      required_argument, 0, 't'},
328                 {"verbose",   no_argument,       0, 'v'},
329                 {0, 0, 0, 0}
330         };
331         int pathstart = -1;
332         int pathend = -1;
333         int neg_opt = 0;
334         time_t *xtime;
335         int *xsign;
336         int isoption;
337
338         time(&t);
339
340         optind = 0;
341         while ((c = getopt_long_only(argc, argv, "-A:C:D:M:n:PpO:qrs:t:v",
342                                      long_opts, NULL)) >= 0) {
343                 xtime = NULL;
344                 xsign = NULL;
345                 if (neg_opt)
346                         --neg_opt;
347                 /* '!' is part of option */
348                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
349                 if (!isoption && pathend != -1) {
350                         fprintf(stderr, "err: %s: filename|dirname must either "
351                                         "precede options or follow options\n",
352                                         argv[0]);
353                         return CMD_HELP;
354                 }
355                 if (!isoption && pathstart == -1)
356                         pathstart = optind - 1;
357                 if (isoption && pathstart != -1 && pathend == -1) {
358                         pathend = optind - 2;
359                         if ((c == 1 && strcmp(optarg, "!") == 0) ||
360                             c == 'P' || c == 'p' || c == 'O' ||
361                             c == 'q' || c == 'r' || c == 'v')
362                                 pathend = optind - 1;
363                 }
364                 switch (c) {
365                 case 0:
366                         /* Long options. */
367                         break;
368                 case 1:
369                         if (strcmp(optarg, "!") == 0)
370                                 neg_opt = 2;
371                       break;
372                 case 'A':
373                         xtime = &param.atime;
374                         xsign = &param.asign;
375                 case 'C':
376                         if (c == 'C') {
377                                 xtime = &param.ctime;
378                                 xsign = &param.csign;
379                         }
380                 case 'M':
381                         if (c == 'M') {
382                                 xtime = &param.mtime;
383                                 xsign = &param.msign;
384                         }
385                         new_fashion = 1;
386                         if (neg_opt) {
387                                 if (optarg[0] == '-')
388                                         optarg[0] = '+';
389                                 else if (optarg[0] == '+')
390                                         optarg[0] = '-';
391                                 else {
392                                         str[0] = '-';
393                                         str[1] = '\0';
394                                         strcat(str, optarg);
395                                         optarg = str;
396                                 }
397                         }
398                         ret = set_time(&t, xtime, optarg);
399                         if (ret == INT_MAX)
400                                 return -1;
401                         if (ret)
402                                 *xsign = ret;
403                         break;
404                 case 'D':
405                         new_fashion = 1;
406                         param.maxdepth = strtol(optarg, 0, 0);
407                         break;
408                 case 'n':
409                         new_fashion = 1;
410                         param.pattern = (char *)optarg;
411                         param.exclude_pattern = !!neg_opt;
412                         break;
413                 case 'O': {
414                         char *buf, *token, *next, *p;
415                         int len;
416
417                         len = strlen((char *)optarg);
418                         buf = malloc(len+1);
419                         if (buf == NULL)
420                                 return -ENOMEM;
421                         strcpy(buf, (char *)optarg);
422
423                         if (param.num_alloc_obds == 0) {
424                                 param.obduuid = (struct obd_uuid *)malloc(FIND_MAX_OSTS *
425                                                        sizeof(struct obd_uuid));
426                                 if (param.obduuid == NULL)
427                                         return -ENOMEM;
428                                 param.num_alloc_obds = INIT_ALLOC_NUM_OSTS;
429                         }
430
431                         for (token = buf; token && *token; token = next) {
432                                 p = strchr(token, ',');
433                                 next = 0;
434                                 if (p) {
435                                         *p = 0;
436                                         next = p+1;
437                                 }
438                                 strcpy((char *)&param.obduuid[param.num_obds++].uuid,
439                                        token);
440                         }
441
442                         if (buf)
443                                 free(buf);
444                         break;
445                 }
446                 case 'p':
447                         new_fashion = 1;
448                         param.zeroend = 1;
449                         break;
450                 case 'P':
451                         break;
452                 case 'q':
453                         new_fashion = 0;
454                         param.quiet++;
455                         param.verbose = 0;
456                         break;
457                 case 'r':
458                         new_fashion = 0;
459                         param.recursive = 1;
460                         break;
461                 case 't':
462                         param.exclude_type = !!neg_opt;
463                         switch(optarg[0]) {
464                         case 'b': param.type = S_IFBLK; break;
465                         case 'c': param.type = S_IFCHR; break;
466                         case 'd': param.type = S_IFDIR; break;
467                         case 'f': param.type = S_IFREG; break;
468                         case 'l': param.type = S_IFLNK; break;
469                         case 'p': param.type = S_IFIFO; break;
470                         case 's': param.type = S_IFSOCK; break;
471 #ifdef S_IFDOOR /* Solaris only */
472                         case 'D': param.type = S_IFDOOR; break;
473 #endif
474                         default: fprintf(stderr, "error: %s: bad type '%s'\n",
475                                          argv[0], optarg);
476                                  return CMD_HELP;
477                         };
478                         break;
479                 case 's':
480                         if (neg_opt) {
481                                 if (optarg[0] == '-')
482                                         optarg[0] = '+';
483                                 else if (optarg[0] == '+')
484                                         optarg[0] = '-';
485                                 else {
486                                         str[0] = '-';
487                                         str[1] = '\0';
488                                         strcat(str, optarg);
489                                         optarg = str;
490                                 }
491                         }
492                         if (optarg[0] == '+')
493                                 param.size_sign = -1;
494                         else if (optarg[0] == '-')
495                                 param.size_sign = +1;
496
497                         if (param.size_sign)
498                                 optarg++;
499                         ret = parse_size(optarg, &param.size,&param.size_units);
500                         if (ret) {
501                                 fprintf(stderr,"error: bad size '%s'\n",
502                                         optarg);
503                                 return ret;
504                         }
505                         param.size_check = 1;
506                         break;
507                 case 'v':
508                         new_fashion = 0;
509                         param.verbose++;
510                         param.quiet = 0;
511                         break;
512                 case '?':
513                         return CMD_HELP;
514                 default:
515                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
516                                 argv[0], argv[optind - 1]);
517                         return CMD_HELP;
518                 };
519         }
520
521         if (pathstart == -1) {
522                 fprintf(stderr, "error: %s: no filename|pathname\n",
523                                 argv[0]);
524                 return CMD_HELP;
525         } else if (pathend == -1) {
526                 /* no options */
527                 pathend = argc;
528         }
529
530         if (new_fashion) {
531                 param.quiet = 1;
532         } else {
533                 static int deprecated_warning;
534                 if (!deprecated_warning) {
535                         fprintf(stderr, "lfs find: -q, -r, -v options "
536                                 "deprecated.  Use 'lfs getstripe' instead.\n");
537                         deprecated_warning = 1;
538                 }
539                 if (!param.recursive && param.maxdepth == -1)
540                         param.maxdepth = 1;
541         }
542
543         do {
544                 if (new_fashion)
545                         ret = llapi_find(argv[pathstart], &param);
546                 else
547                         ret = llapi_getstripe(argv[pathstart], &param);
548         } while (++pathstart < pathend && !ret);
549
550         if (ret)
551                 fprintf(stderr, "error: %s failed for %s.\n",
552                         argv[0], argv[optind - 1]);
553
554         if (param.obduuid && param.num_alloc_obds)
555                 free(param.obduuid);
556
557         return ret;
558 }
559
560 static int lfs_getstripe(int argc, char **argv)
561 {
562         struct option long_opts[] = {
563                 {"obd", 1, 0, 'O'},
564                 {"quiet", 0, 0, 'q'},
565                 {"recursive", 0, 0, 'r'},
566                 {"verbose", 0, 0, 'v'},
567                 {0, 0, 0, 0}
568         };
569         char short_opts[] = "hO:qrv";
570         int c, rc;
571         struct find_param param = { 0 };
572
573         optind = 0;
574         while ((c = getopt_long(argc, argv, short_opts,
575                                 long_opts, NULL)) != -1) {
576                 switch (c) {
577                 case 'O':
578                         if (param.obduuid) {
579                                 fprintf(stderr,
580                                         "error: %s: only one obduuid allowed",
581                                         argv[0]);
582                                 return CMD_HELP;
583                         }
584                         param.obduuid = (struct obd_uuid *)optarg;
585                         break;
586                 case 'q':
587                         param.quiet++;
588                         param.verbose = 0;
589                         break;
590                 case 'r':
591                         param.recursive = 1;
592                         break;
593                 case 'v':
594                         param.verbose++;
595                         param.quiet = 0;
596                         break;
597                 case '?':
598                         return CMD_HELP;
599                 default:
600                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
601                                 argv[0], argv[optind - 1]);
602                         return CMD_HELP;
603                 }
604         }
605
606         if (optind >= argc)
607                 return CMD_HELP;
608
609         param.maxdepth = param.recursive ? -1 : 1;
610
611         do {
612                 rc = llapi_getstripe(argv[optind], &param);
613         } while (++optind < argc && !rc);
614
615         if (rc)
616                 fprintf(stderr, "error: %s failed for %s.\n", 
617                         argv[0], argv[optind - 1]);
618         return rc;
619 }
620
621 static int lfs_osts(int argc, char **argv)
622 {
623         FILE *fp;
624         struct mntent *mnt = NULL;
625         struct obd_uuid *obduuid = NULL;
626         struct find_param param;
627         int rc=0;
628
629         if (argc != 1)
630                 return CMD_HELP;
631
632         fp = setmntent(MOUNTED, "r");
633
634         if (fp == NULL) {
635                  fprintf(stderr, "%s: setmntent(%s): %s:", argv[0], MOUNTED,
636                         strerror (errno));
637         } else {
638                 mnt = getmntent(fp);
639                 memset(&param, 0, sizeof(param));
640                 param.obduuid = obduuid;
641                 while (feof(fp) == 0 && ferror(fp) ==0) {
642                         if (llapi_is_lustre_mnt(mnt)) {
643                                 rc = llapi_getstripe(mnt->mnt_dir, &param);
644                                 if (rc)
645                                         fprintf(stderr,
646                                                "error: %s: failed on %s\n",
647                                                argv[0], mnt->mnt_dir);
648                         }
649                         mnt = getmntent(fp);
650                 }
651                 endmntent(fp);
652         }
653
654         return rc;
655 }
656
657 #define COOK(value)                                                     \
658 ({                                                                      \
659         int radix = 0;                                                  \
660         while (value > 1024) {                                          \
661                 value /= 1024;                                          \
662                 radix++;                                                \
663         }                                                               \
664         radix;                                                          \
665 })
666 #define UUF     "%-20s"
667 #define CSF     "%9s"
668 #define CDF     "%9llu"
669 #define HSF     "%8s"
670 #define HDF     "%6.1f"
671 #define RSF     "%5s"
672 #define RDF     "%4d%%"
673
674 static int path2mnt(char *path, FILE *fp, char *mntdir, int dir_len)
675 {
676         char rpath[PATH_MAX] = {'\0'};
677         struct mntent *mnt;
678         int rc, len, out_len = 0;
679
680         if (!realpath(path, rpath)) {
681                 rc = -errno;
682                 fprintf(stderr, "error: lfs df: invalid path '%s': %s\n",
683                         path, strerror(-rc));
684                 return rc;
685         }
686
687         len = 0;
688         mnt = getmntent(fp);
689         while (feof(fp) == 0 && ferror(fp) == 0) {
690                 if (llapi_is_lustre_mnt(mnt)) {
691                         len = strlen(mnt->mnt_dir);
692                         if (len > out_len &&
693                             !strncmp(rpath, mnt->mnt_dir, len)) {
694                                 out_len = len;
695                                 memset(mntdir, 0, dir_len);
696                                 strncpy(mntdir, mnt->mnt_dir, dir_len);
697                         }
698                 }
699                 mnt = getmntent(fp);
700         }
701
702         if (out_len > 0)
703                 return 0;
704
705         fprintf(stderr, "error: lfs df: %s isn't mounted on lustre\n", path);
706         return -EINVAL;
707 }
708
709 static int showdf(char *mntdir, struct obd_statfs *stat,
710                   char *uuid, int ishow, int cooked,
711                   char *type, int index, int rc)
712 {
713         long long avail, used, total;
714         double ratio = 0;
715         char *suffix = "KMGTPEZY";
716         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
717         char tbuf[20], ubuf[20], abuf[20], rbuf[20];
718
719         if (!uuid || !stat)
720                 return -EINVAL;
721
722         switch (rc) {
723         case 0:
724                 if (ishow) {
725                         avail = stat->os_ffree;
726                         used = stat->os_files - stat->os_ffree;
727                         total = stat->os_files;
728                 } else {
729                         int shift = cooked ? 0 : 10;
730
731                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
732                         used  = ((stat->os_blocks - stat->os_bfree) *
733                                  stat->os_bsize) >> shift;
734                         total = (stat->os_blocks * stat->os_bsize) >> shift;
735                 }
736
737                 if (total > 0)
738                         ratio = (double)used / (double)total;
739
740                 if (cooked) {
741                         int i;
742                         double cook_val;
743
744                         cook_val = (double)total;
745                         i = COOK(cook_val);
746                         if (i > 0)
747                                 sprintf(tbuf, HDF"%c", cook_val, suffix[i - 1]);
748                         else
749                                 sprintf(tbuf, CDF, total);
750
751                         cook_val = (double)used;
752                         i = COOK(cook_val);
753                         if (i > 0)
754                                 sprintf(ubuf, HDF"%c", cook_val, suffix[i - 1]);
755                         else
756                                 sprintf(ubuf, CDF, used);
757
758                         cook_val = (double)avail;
759                         i = COOK(cook_val);
760                         if (i > 0)
761                                 sprintf(abuf, HDF"%c", cook_val, suffix[i - 1]);
762                         else
763                                 sprintf(abuf, CDF, avail);
764                 } else {
765                         sprintf(tbuf, CDF, total);
766                         sprintf(ubuf, CDF, used);
767                         sprintf(abuf, CDF, avail);
768                 }
769
770                 sprintf(rbuf, RDF, (int)(ratio * 100));
771                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
772                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
773                 if (type)
774                         printf("[%s:%d]\n", type, index);
775                 else
776                         printf("\n");
777
778                 break;
779         case -ENODATA:
780                 printf(UUF": inactive device\n", uuid);
781                 break;
782         default:
783                 printf(UUF": %s\n", uuid, strerror(-rc));
784                 break;
785         }
786
787         return 0;
788 }
789
790 static int mntdf(char *mntdir, int ishow, int cooked)
791 {
792         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
793         struct obd_uuid uuid_buf;
794         __u32 index;
795         int rc;
796
797         if (ishow)
798                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
799                        "UUID", "Inodes", "IUsed", "IFree",
800                        "IUse%", "Mounted on");
801         else
802                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
803                        "UUID", cooked ? "bytes" : "1K-blocks",
804                        "Used", "Available", "Use%", "Mounted on");
805
806         for (index = 0; ; index++) {
807                 memset(&stat_buf, 0, sizeof(struct obd_statfs));
808                 memset(&uuid_buf, 0, sizeof(struct obd_uuid));
809                 rc = llapi_obd_statfs(mntdir, LL_STATFS_MDC, index,
810                                       &stat_buf, &uuid_buf);
811                 if (rc == -ENODEV)
812                         break;
813
814                 if (rc == -EAGAIN)
815                         continue;
816
817                 if (rc == -ENOTCONN || rc == -ETIMEDOUT || rc == -EIO ||
818                     rc == -ENODATA || rc == 0) {
819                         showdf(mntdir, &stat_buf, obd_uuid2str(&uuid_buf),
820                                ishow, cooked, "MDT", index, rc);
821                 } else {
822                         fprintf(stderr,
823                                 "error: llapi_obd_statfs(%s): %s (%d)\n",
824                                 obd_uuid2str(&uuid_buf), strerror(-rc), rc);
825                         return rc;
826                 }
827                 if (rc == 0) {
828                         sum.os_ffree += stat_buf.os_ffree;
829                         sum.os_files += stat_buf.os_files;
830                 }
831         }
832
833         for (index = 0; ; index++) {
834                 memset(&stat_buf, 0, sizeof(struct obd_statfs));
835                 memset(&uuid_buf, 0, sizeof(struct obd_uuid));
836                 rc = llapi_obd_statfs(mntdir, LL_STATFS_LOV, index,
837                                       &stat_buf, &uuid_buf);
838                 if (rc == -ENODEV)
839                         break;
840
841                 if (rc == -EAGAIN)
842                         continue;
843
844                 if (rc == -ENOTCONN || rc == -ETIMEDOUT || rc == -EIO ||
845                     rc == -ENODATA || rc == 0) {
846                         showdf(mntdir, &stat_buf, obd_uuid2str(&uuid_buf),
847                                ishow, cooked, "OST", index, rc);
848                 } else {
849                         fprintf(stderr,
850                                 "error: llapi_obd_statfs failed: %s (%d)\n",
851                                 strerror(-rc), rc);
852                         return rc;
853                 }
854                 if (rc == 0) {
855                         sum.os_blocks += stat_buf.os_blocks * stat_buf.os_bsize;
856                         sum.os_bfree  += stat_buf.os_bfree * stat_buf.os_bsize;
857                         sum.os_bavail += stat_buf.os_bavail * stat_buf.os_bsize;
858                 }
859         }
860
861         printf("\n");
862         showdf(mntdir, &sum, "filesystem summary:", ishow, cooked, NULL, 0,0);
863
864         return 0;
865 }
866
867 static int lfs_df(int argc, char **argv)
868 {
869         FILE *fp;
870         char *path = NULL;
871         struct mntent *mnt = NULL;
872         char mntdir[PATH_MAX] = {'\0'};
873         int ishow = 0, cooked = 0;
874         int c, rc = 0;
875
876         optind = 0;
877         while ((c = getopt(argc, argv, "ih")) != -1) {
878                 switch (c) {
879                 case 'i':
880                         ishow = 1;
881                         break;
882                 case 'h':
883                         cooked = 1;
884                         break;
885                 default:
886                         return CMD_HELP;
887                 }
888         }
889         if (optind < argc )
890                 path = argv[optind];
891
892         fp = setmntent(MOUNTED, "r");
893         if (fp == NULL) {
894                 rc = -errno;
895                 fprintf(stderr, "error: %s: open %s failed( %s )\n",
896                         argv[0], MOUNTED, strerror(errno));
897                 return rc;
898         }
899         if (path) {
900                 rc = path2mnt(path, fp, mntdir, sizeof(mntdir));
901                 if (rc) {
902                         endmntent(fp);
903                         return rc;
904                 }
905
906                 rc = mntdf(mntdir, ishow, cooked);
907                 printf("\n");
908                 endmntent(fp);
909         } else {
910                 mnt = getmntent(fp);
911                 while (feof(fp) == 0 && ferror(fp) == 0) {
912                         if (llapi_is_lustre_mnt(mnt)) {
913                                 rc = mntdf(mnt->mnt_dir, ishow, cooked);
914                                 if (rc)
915                                         break;
916                                 printf("\n");
917                         }
918                         mnt = getmntent(fp);
919                 }
920                 endmntent(fp);
921         }
922
923         return rc;
924 }
925
926 static int lfs_check(int argc, char **argv)
927 {
928         int rc;
929         FILE *fp;
930         struct mntent *mnt = NULL;
931         int num_types = 1;
932         char *obd_types[2];
933         char obd_type1[4];
934         char obd_type2[4];
935
936         if (argc != 2)
937                 return CMD_HELP;
938
939         obd_types[0] = obd_type1;
940         obd_types[1] = obd_type2;
941
942         if (strcmp(argv[1], "osts") == 0) {
943                 strcpy(obd_types[0], "osc");
944         } else if (strcmp(argv[1], "mds") == 0) {
945                 strcpy(obd_types[0], "mdc");
946         } else if (strcmp(argv[1], "servers") == 0) {
947                 num_types = 2;
948                 strcpy(obd_types[0], "osc");
949                 strcpy(obd_types[1], "mdc");
950         } else {
951                 fprintf(stderr, "error: %s: option '%s' unrecognized\n",
952                                 argv[0], argv[1]);
953                         return CMD_HELP;
954         }
955
956         fp = setmntent(MOUNTED, "r");
957         if (fp == NULL) {
958                  fprintf(stderr, "setmntent(%s): %s:", MOUNTED,
959                         strerror (errno));
960         } else {
961                 mnt = getmntent(fp);
962                 while (feof(fp) == 0 && ferror(fp) ==0) {
963                         if (llapi_is_lustre_mnt(mnt))
964                                 break;
965                         mnt = getmntent(fp);
966                 }
967                 endmntent(fp);
968         }
969
970         if (!mnt) {
971                 fprintf(stderr, "No suitable Lustre mount found\n");
972                 return -1;
973         }
974
975         rc = llapi_target_check(num_types, obd_types, mnt->mnt_dir);
976
977         if (rc)
978                 fprintf(stderr, "error: %s: %s status failed\n",
979                                 argv[0],argv[1]);
980
981         return rc;
982
983 }
984
985 static int lfs_catinfo(int argc, char **argv)
986 {
987         FILE *fp;
988         struct mntent *mnt = NULL;
989         int rc;
990
991         if (argc < 2 || (!strcmp(argv[1],"config") && argc < 3))
992                 return CMD_HELP;
993
994         if (strcmp(argv[1], "config") && strcmp(argv[1], "deletions"))
995                 return CMD_HELP;
996
997         fp = setmntent(MOUNTED, "r");
998         if (fp == NULL) {
999                  fprintf(stderr, "setmntent(%s): %s:", MOUNTED,
1000                          strerror(errno));
1001         } else {
1002                 mnt = getmntent(fp);
1003                 while (feof(fp) == 0 && ferror(fp) == 0) {
1004                         if (llapi_is_lustre_mnt(mnt))
1005                                 break;
1006                         mnt = getmntent(fp);
1007                 }
1008                 endmntent(fp);
1009         }
1010
1011         if (mnt) {
1012                 if (argc == 3)
1013                         rc = llapi_catinfo(mnt->mnt_dir, argv[1], argv[2]);
1014                 else
1015                         rc = llapi_catinfo(mnt->mnt_dir, argv[1], NULL);
1016         } else {
1017                 fprintf(stderr, "no lustre_lite mounted.\n");
1018                 rc = -1;
1019         }
1020
1021         return rc;
1022 }
1023
1024 int lfs_join(int argc, char **argv)
1025 {
1026         char *name_head, *name_tail;
1027         int fd, rc;
1028         loff_t size;
1029
1030         if (argc != 3)
1031                 return CMD_HELP;
1032         name_head = argv[1];
1033         fd = open(name_head, O_WRONLY);
1034         if (fd < 0) {
1035                 fprintf(stderr, "Can not open name_head %s rc=%d\n",
1036                         name_head, fd);
1037                 return fd;
1038         }
1039         size = lseek(fd, 0, SEEK_END);
1040         if (size % JOIN_FILE_ALIGN) {
1041                 fprintf(stderr,"head file %s size %llu must be mutiple of %d\n",
1042                         name_head, (long long)size, JOIN_FILE_ALIGN);
1043                 rc = -EINVAL;
1044                 goto out;
1045         }
1046         name_tail = argv[2];
1047         rc = ioctl(fd, LL_IOC_JOIN, name_tail);
1048 out:
1049         close(fd);
1050         if (rc) {
1051                 fprintf(stderr, "Lustre joining files: %s, %s, failed\n",
1052                         argv[1], argv[2]);
1053         }
1054         return rc;
1055 }
1056
1057 #ifdef HAVE_QUOTA_SUPPORT
1058 static int lfs_quotachown(int argc, char **argv)
1059 {
1060
1061         int c,rc;
1062         int flag = 0;
1063
1064         optind = 0;
1065         while ((c = getopt(argc, argv, "i")) != -1) {
1066                 switch (c) {
1067                 case 'i':
1068                         flag++;
1069                         break;
1070                 default:
1071                         fprintf(stderr, "error: %s: option '-%c' "
1072                                         "unrecognized\n", argv[0], c);
1073                         return CMD_HELP;
1074                 }
1075         }
1076         if (optind == argc)
1077                 return CMD_HELP;
1078         rc = llapi_quotachown(argv[optind], flag);
1079         if(rc)
1080                 fprintf(stderr,"error: change file owner/group failed.\n");
1081         return rc;
1082 }
1083
1084
1085 static int lfs_quotacheck(int argc, char **argv)
1086 {
1087         int c, check_type = 0;
1088         char *mnt;
1089         struct if_quotacheck qchk;
1090         struct if_quotactl qctl;
1091         char *obd_type = (char *)qchk.obd_type;
1092         int rc;
1093
1094         memset(&qchk, 0, sizeof(qchk));
1095
1096         optind = 0;
1097         while ((c = getopt(argc, argv, "ug")) != -1) {
1098                 switch (c) {
1099                 case 'u':
1100                         check_type |= 0x01;
1101                         break;
1102                 case 'g':
1103                         check_type |= 0x02;
1104                         break;
1105                 default:
1106                         fprintf(stderr, "error: %s: option '-%c' "
1107                                         "unrecognized\n", argv[0], c);
1108                         return CMD_HELP;
1109                 }
1110         }
1111
1112         if (check_type)
1113                 check_type--;
1114         else    /* do quotacheck for both user & group quota by default */
1115                 check_type = 0x02;
1116
1117         if (argc == optind)
1118                 return CMD_HELP;
1119
1120         mnt = argv[optind];
1121
1122         memset(&qctl, 0, sizeof(qctl));
1123         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
1124         qctl.qc_id = QFMT_LDISKFS;
1125         qctl.qc_type = check_type;
1126         rc = llapi_quotactl(mnt, &qctl);
1127         if (rc) {
1128                 fprintf(stderr, "quota off failed: %s\n", strerror(errno));
1129                 return rc;
1130         }
1131
1132         rc = llapi_quotacheck(mnt, check_type);
1133         if (rc) {
1134                 fprintf(stderr, "quotacheck failed: %s\n", strerror(errno));
1135                 return rc;
1136         }
1137
1138         rc = llapi_poll_quotacheck(mnt, &qchk);
1139         if (rc) {
1140                 if (*obd_type)
1141                         fprintf(stderr, "%s %s ", obd_type,
1142                                 obd_uuid2str(&qchk.obd_uuid));
1143                 fprintf(stderr, "quota check failed: %s\n", strerror(errno));
1144                 return rc;
1145         }
1146
1147         memset(&qctl, 0, sizeof(qctl));
1148         qctl.qc_cmd = LUSTRE_Q_QUOTAON;
1149         qctl.qc_id = QFMT_LDISKFS;
1150         qctl.qc_type = check_type;
1151         rc = llapi_quotactl(mnt, &qctl);
1152         if (rc) {
1153                 if (*obd_type)
1154                         fprintf(stderr, "%s %s ", (char *)qctl.obd_type,
1155                                 obd_uuid2str(&qctl.obd_uuid));
1156                 fprintf(stderr, "%s turn on quota failed: %s\n",
1157                         argv[0], strerror(errno));
1158                 return rc;
1159         }
1160
1161         return 0;
1162 }
1163
1164 static int lfs_quotaon(int argc, char **argv)
1165 {
1166         int c;
1167         char *mnt;
1168         struct if_quotactl qctl;
1169         char *obd_type = (char *)qctl.obd_type;
1170         int rc;
1171
1172         memset(&qctl, 0, sizeof(qctl));
1173         qctl.qc_cmd = LUSTRE_Q_QUOTAON;
1174         qctl.qc_id = QFMT_LDISKFS;
1175
1176         optind = 0;
1177         while ((c = getopt(argc, argv, "ugf")) != -1) {
1178                 switch (c) {
1179                 case 'u':
1180                         qctl.qc_type |= 0x01;
1181                         break;
1182                 case 'g':
1183                         qctl.qc_type |= 0x02;
1184                         break;
1185                 case 'f':
1186                         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
1187                         break;
1188                 default:
1189                         fprintf(stderr, "error: %s: option '-%c' "
1190                                         "unrecognized\n", argv[0], c);
1191                         return CMD_HELP;
1192                 }
1193         }
1194
1195         if (qctl.qc_type)
1196                 qctl.qc_type--;
1197         else /* by default, enable quota for both user & group */
1198                 qctl.qc_type = 0x02;
1199
1200         if (argc == optind)
1201                 return CMD_HELP;
1202
1203         mnt = argv[optind];
1204
1205         rc = llapi_quotactl(mnt, &qctl);
1206         if (rc) {
1207                 if (*obd_type)
1208                         fprintf(stderr, "%s %s ", obd_type,
1209                                 obd_uuid2str(&qctl.obd_uuid));
1210                 fprintf(stderr, "%s failed: %s\n", argv[0], strerror(errno));
1211                 return rc;
1212         }
1213
1214         return 0;
1215 }
1216
1217 static int lfs_quotaoff(int argc, char **argv)
1218 {
1219         int c;
1220         char *mnt;
1221         struct if_quotactl qctl;
1222         char *obd_type = (char *)qctl.obd_type;
1223         int rc;
1224
1225         memset(&qctl, 0, sizeof(qctl));
1226         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
1227
1228         optind = 0;
1229         while ((c = getopt(argc, argv, "ug")) != -1) {
1230                 switch (c) {
1231                 case 'u':
1232                         qctl.qc_type |= 0x01;
1233                         break;
1234                 case 'g':
1235                         qctl.qc_type |= 0x02;
1236                         break;
1237                 default:
1238                         fprintf(stderr, "error: %s: option '-%c' "
1239                                         "unrecognized\n", argv[0], c);
1240                         return CMD_HELP;
1241                 }
1242         }
1243
1244         if (qctl.qc_type)
1245                 qctl.qc_type--;
1246         else /* by default, disable quota for both user & group */
1247                 qctl.qc_type = 0x02;
1248
1249         if (argc == optind)
1250                 return CMD_HELP;
1251
1252         mnt = argv[optind];
1253
1254         rc = llapi_quotactl(mnt, &qctl);
1255         if (rc == -1 && errno == ESRCH) {
1256                 fprintf(stderr, "\n%s quotas are not enabled.\n", 
1257                         qctl.qc_type == 0x00 ? "user" : "group");
1258                 return 0;
1259         }
1260         if (rc) {
1261                 if (*obd_type)
1262                         fprintf(stderr, "%s %s ", obd_type,
1263                                 obd_uuid2str(&qctl.obd_uuid));
1264                 fprintf(stderr, "quotaoff failed: %s\n", strerror(errno));
1265                 return rc;
1266         }
1267
1268         return 0;
1269 }
1270
1271 static int lfs_quotainv(int argc, char **argv)
1272 {
1273         int c;
1274         char *mnt;
1275         struct if_quotactl qctl;
1276         int rc;
1277
1278         memset(&qctl, 0, sizeof(qctl));
1279         qctl.qc_cmd = LUSTRE_Q_INVALIDATE;
1280
1281         optind = 0;
1282         while ((c = getopt(argc, argv, "ug")) != -1) {
1283                 switch (c) {
1284                 case 'u':
1285                         qctl.qc_type |= 0x01;
1286                         break;
1287                 case 'g':
1288                         qctl.qc_type |= 0x02;
1289                         break;
1290                 default:
1291                         fprintf(stderr, "error: %s: option '-%c' "
1292                                         "unrecognized\n", argv[0], c);
1293                         return CMD_HELP;
1294                 }
1295         }
1296
1297         if (qctl.qc_type)
1298                 qctl.qc_type--;
1299         else /* by default, invalidate quota for both user & group */
1300                 qctl.qc_type = 0x02;
1301
1302         if (argc == optind)
1303                 return CMD_HELP;
1304
1305         mnt = argv[optind];
1306
1307         rc = llapi_quotactl(mnt, &qctl);
1308         if (rc) {
1309                 fprintf(stderr, "quotainv failed: %s\n", strerror(errno));
1310                 return rc;
1311         }
1312
1313         return 0;
1314 }
1315
1316 static int name2id(unsigned int *id, char *name, int type)
1317 {
1318         if (type == USRQUOTA) {
1319                 struct passwd *entry;
1320
1321                 if (!(entry = getpwnam(name))) {
1322                         if (!errno)
1323                                 errno = ENOENT;
1324                         return -1;
1325                 }
1326
1327                 *id = entry->pw_uid;
1328         } else {
1329                 struct group *entry;
1330
1331                 if (!(entry = getgrnam(name))) {
1332                         if (!errno)
1333                                 errno = ENOENT;
1334                         return -1;
1335                 }
1336
1337                 *id = entry->gr_gid;
1338         }
1339
1340         return 0;
1341 }
1342
1343 static int id2name(char **name, unsigned int id, int type)
1344 {
1345         if (type == USRQUOTA) {
1346                 struct passwd *entry;
1347
1348                 if (!(entry = getpwuid(id))) {
1349                         if (!errno)
1350                                 errno = ENOENT;
1351                         return -1;
1352                 }
1353
1354                 *name = entry->pw_name;
1355         } else {
1356                 struct group *entry;
1357
1358                 if (!(entry = getgrgid(id))) {
1359                         if (!errno)
1360                                 errno = ENOENT;
1361                         return -1;
1362                 }
1363
1364                 *name = entry->gr_name;
1365         }
1366
1367         return 0;
1368 }
1369
1370 #define ARG2INT(nr, str, msg)                                           \
1371 do {                                                                    \
1372         char *endp;                                                     \
1373         nr = strtol(str, &endp, 0);                                     \
1374         if (*endp) {                                                    \
1375                 fprintf(stderr, "error: bad %s: %s\n", msg, str);       \
1376                 return CMD_HELP;                                        \
1377         }                                                               \
1378 } while (0)
1379
1380 #define ADD_OVERFLOW(a,b) ((a + b) < a) ? (a = ULONG_MAX) : (a = a + b)
1381
1382 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
1383  * returns the value or ULONG_MAX on integer overflow or incorrect format
1384  * Notes:
1385  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
1386  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
1387  *        3. empty integer value is interpreted as 0
1388  */
1389
1390 static unsigned long str2sec(const char* timestr) {
1391         const char spec[] = "smhdw";
1392         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
1393         unsigned long val = 0;
1394         char *tail;
1395
1396         if (strpbrk(timestr, spec) == NULL) {
1397                 /* no specifiers inside the time string,
1398                    should treat it as an integer value */
1399                 val = strtoul(timestr, &tail, 10);
1400                 return *tail ? ULONG_MAX : val;
1401         }
1402
1403         /* format string is XXwXXdXXhXXmXXs */
1404         while (*timestr) {
1405                 unsigned long v;
1406                 int ind;
1407                 char* ptr;
1408
1409                 v = strtoul(timestr, &tail, 10);
1410                 if (v == ULONG_MAX || *tail == '\0')
1411                         /* value too large (ULONG_MAX or more) 
1412                            or missing specifier */
1413                         goto error;
1414
1415                 ptr = strchr(spec, *tail);
1416                 if (ptr == NULL)
1417                         /* unknown specifier */
1418                         goto error;
1419
1420                 ind = ptr - spec;
1421
1422                 /* check if product will overflow the type */
1423                 if (!(v < ULONG_MAX / mult[ind]))
1424                         goto error;
1425
1426                 ADD_OVERFLOW(val, mult[ind] * v);
1427                 if (val == ULONG_MAX)
1428                         goto error;
1429
1430                 timestr = tail + 1;
1431         }
1432
1433         return val;
1434
1435 error:
1436         return ULONG_MAX;
1437 }
1438
1439 #define ARG2ULL(nr, str, msg)                                           \
1440 do {                                                                    \
1441         char *endp;                                                     \
1442         nr = strtoull(str, &endp, 0);                                   \
1443         if (*endp) {                                                    \
1444                 fprintf(stderr, "error: bad %s: %s\n", msg, str);       \
1445                 return CMD_HELP;                                        \
1446         }                                                               \
1447 } while (0)
1448
1449
1450 int lfs_setquota(int argc, char **argv)
1451 {
1452         int c;
1453         char *mnt;
1454         struct if_quotactl qctl;
1455         char *obd_type = (char *)qctl.obd_type;
1456         int rc;
1457
1458         memset(&qctl, 0, sizeof(qctl));
1459         qctl.qc_cmd = LUSTRE_Q_SETQUOTA;
1460
1461         optind = 0;
1462         while ((c = getopt(argc, argv, "ugt")) != -1) {
1463                 switch (c) {
1464                 case 'u':
1465                         qctl.qc_type |= 0x01;
1466                         break;
1467                 case 'g':
1468                         qctl.qc_type |= 0x02;
1469                         break;
1470                 case 't':
1471                         qctl.qc_cmd = LUSTRE_Q_SETINFO;
1472                         break;
1473                 default:
1474                         fprintf(stderr, "error: %s: option '-%c' "
1475                                         "unrecognized\n", argv[0], c);
1476                         return CMD_HELP;
1477                 }
1478         }
1479
1480         if (qctl.qc_type)
1481                 qctl.qc_type--;
1482
1483         if (qctl.qc_type == UGQUOTA) {
1484                 fprintf(stderr, "error: user and group quotas can't be set "
1485                                 "both\n");
1486                 return CMD_HELP;
1487         }
1488
1489         if (qctl.qc_cmd == LUSTRE_Q_SETQUOTA) {
1490                 struct obd_dqblk *dqb = &qctl.qc_dqblk;
1491
1492                 if (optind + 6 != argc)
1493                         return CMD_HELP;
1494
1495                 rc = name2id(&qctl.qc_id, argv[optind++], qctl.qc_type);
1496                 if (rc) {
1497                         fprintf(stderr, "error: find id for name %s failed: %s\n",
1498                                 argv[optind - 1], strerror(errno));
1499                         return CMD_HELP;
1500                 }
1501
1502                 ARG2ULL(dqb->dqb_bsoftlimit, argv[optind++], "block-softlimit");
1503                 ARG2ULL(dqb->dqb_bhardlimit, argv[optind++], "block-hardlimit");
1504                 ARG2ULL(dqb->dqb_isoftlimit, argv[optind++], "inode-softlimit");
1505                 ARG2ULL(dqb->dqb_ihardlimit, argv[optind++], "inode-hardlimit");
1506
1507                 dqb->dqb_valid = QIF_LIMITS;
1508         } else {
1509                 struct obd_dqinfo *dqi = &qctl.qc_dqinfo;
1510
1511                 if (optind + 3 != argc)
1512                         return CMD_HELP;
1513
1514                 if ((dqi->dqi_bgrace = str2sec(argv[optind++])) == ULONG_MAX) {
1515                         fprintf(stderr, "error: bad %s: %s\n", "block-grace", argv[optind - 1]);
1516                         return CMD_HELP;
1517                 }
1518                 if ((dqi->dqi_igrace = str2sec(argv[optind++])) == ULONG_MAX) {
1519                         fprintf(stderr, "error: bad %s: %s\n", "inode-grace", argv[optind - 1]);
1520                         return CMD_HELP;
1521                 }
1522         }
1523
1524         mnt = argv[optind];
1525
1526         rc = llapi_quotactl(mnt, &qctl);
1527         if (rc) {
1528                 if (*obd_type)
1529                         fprintf(stderr, "%s %s ", obd_type,
1530                                 obd_uuid2str(&qctl.obd_uuid));
1531                 fprintf(stderr, "setquota failed: %s\n", strerror(errno));
1532                 return rc;
1533         }
1534
1535         return 0;
1536 }
1537
1538 static inline char *type2name(int check_type)
1539 {
1540         if (check_type == USRQUOTA)
1541                 return "user";
1542         else if (check_type == GRPQUOTA)
1543                 return "group";
1544         else
1545                 return "unknown";
1546 }
1547
1548
1549 /* Converts seconds value into format string
1550  * result is returned in buf
1551  * Notes:
1552  *        1. result is in descenting order: 1w2d3h4m5s
1553  *        2. zero fields are not filled (except for p. 3): 5d1s
1554  *        3. zero seconds value is presented as "0s"
1555  */
1556 static void sec2str(time_t seconds, char *buf)
1557 {
1558         const char spec[] = "smhdw";
1559         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
1560         unsigned long c;
1561         char* tail = buf;
1562         int i;
1563
1564         for (i = sizeof(mult) / sizeof(mult[0]) - 1 ; i >= 0; i--) {
1565                 c = seconds / mult[i];
1566
1567                 if (c > 0 || (i == 0 && buf == tail))
1568                         tail += snprintf(tail, 40-(tail-buf), "%lu%c", c, spec[i]);
1569
1570                 seconds %= mult[i];
1571         }
1572 }
1573
1574
1575 static void diff2str(time_t seconds, char *buf, time_t now)
1576 {
1577
1578         buf[0] = 0;
1579         if (!seconds)
1580                 return;
1581         if (seconds <= now) {
1582                 strcpy(buf, "none");
1583                 return;
1584         }
1585         sec2str(seconds - now, buf);
1586 }
1587
1588 static void print_quota_title(char *name, struct if_quotactl *qctl)
1589 {
1590         printf("Disk quotas for %s %s (%cid %u):\n",
1591                type2name(qctl->qc_type), name,
1592                *type2name(qctl->qc_type), qctl->qc_id);
1593         printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
1594                "Filesystem",
1595                "kbytes", "quota", "limit", "grace",
1596                "files", "quota", "limit", "grace");
1597 }
1598
1599 #define GENERAL_QUOTA_INFO 1
1600 #define MDS_QUOTA_INFO     2
1601 #define OST_QUOTA_INFO     3
1602
1603 static void print_quota(char *mnt, struct if_quotactl *qctl, int type)
1604 {
1605         time_t now;
1606
1607         time(&now);
1608
1609         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA) {
1610                 int bover = 0, iover = 0;
1611                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
1612
1613                 if (dqb->dqb_bhardlimit &&
1614                     toqb(dqb->dqb_curspace) > dqb->dqb_bhardlimit) {
1615                         bover = 1;
1616                 } else if (dqb->dqb_bsoftlimit &&
1617                            toqb(dqb->dqb_curspace) > dqb->dqb_bsoftlimit) {
1618                         if (dqb->dqb_btime > now) {
1619                                 bover = 2;
1620                         } else {
1621                                 bover = 3;
1622                         }
1623                 }
1624
1625                 if (dqb->dqb_ihardlimit &&
1626                     dqb->dqb_curinodes > dqb->dqb_ihardlimit) {
1627                         iover = 1;
1628                 } else if (dqb->dqb_isoftlimit &&
1629                            dqb->dqb_curinodes > dqb->dqb_isoftlimit) {
1630                         if (dqb->dqb_btime > now) {
1631                                 iover = 2;
1632                         } else {
1633                                 iover = 3;
1634                         }
1635                 }
1636
1637 #if 0           /* XXX: always print quotas even when no usages */
1638                 if (dqb->dqb_curspace || dqb->dqb_curinodes)
1639 #endif
1640                 {
1641                         char numbuf[3][32];
1642                         char timebuf[40];
1643
1644                         if (strlen(mnt) > 15)
1645                                 printf("%s\n%15s", mnt, "");
1646                         else
1647                                 printf("%15s", mnt);
1648
1649                         if (bover)
1650                                 diff2str(dqb->dqb_btime, timebuf, now);
1651                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
1652                                 LPU64 : "["LPU64"]", toqb(dqb->dqb_curspace));
1653                         if (type == GENERAL_QUOTA_INFO)
1654                                 sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS)
1655                                         ? LPU64 : "["LPU64"]",
1656                                         dqb->dqb_bsoftlimit);
1657                         else
1658                                 sprintf(numbuf[1], "%s", "");
1659                         sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS)
1660                                 ? LPU64 : "["LPU64"]", dqb->dqb_bhardlimit);
1661                         printf(" %7s%c %6s %7s %7s",
1662                                numbuf[0], bover ? '*' : ' ', numbuf[1],
1663                                numbuf[2], bover > 1 ? timebuf : "");
1664
1665                         if (iover)
1666                                 diff2str(dqb->dqb_itime, timebuf, now);
1667
1668                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_INODES) ?
1669                                 LPU64 : "["LPU64"]", dqb->dqb_curinodes);
1670                        if (type == GENERAL_QUOTA_INFO)
1671                                 sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS)
1672                                         ? LPU64 : "["LPU64"]",
1673                                         dqb->dqb_isoftlimit);
1674                         else
1675                                 sprintf(numbuf[1], "%s", "");
1676                         sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
1677                                 LPU64 : "["LPU64"]", dqb->dqb_ihardlimit);
1678                         if (type != OST_QUOTA_INFO)
1679                                 printf(" %7s%c %6s %7s %7s",
1680                                        numbuf[0], iover ? '*' : ' ', numbuf[1],
1681                                        numbuf[2], iover > 1 ? timebuf : "");
1682                         printf("\n");
1683                 }
1684         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO ||
1685                    qctl->qc_cmd == Q_GETOINFO) {
1686                 char bgtimebuf[40];
1687                 char igtimebuf[40];
1688
1689                 sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf);
1690                 sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf);
1691                 printf("Block grace time: %s; Inode grace time: %s\n",
1692                        bgtimebuf, igtimebuf);
1693         }
1694 }
1695
1696 static int print_mds_quota(char *mnt, struct if_quotactl *qctl)
1697 {
1698         int rc;
1699
1700         /* XXX: this is a flag to mark that only mds quota is wanted */
1701         qctl->qc_dqblk.dqb_valid = 1;
1702         rc = llapi_quotactl(mnt, qctl);
1703         if (rc) {
1704                 fprintf(stderr, "quotactl failed: %s\n", strerror(errno));
1705                 return rc;
1706         }
1707
1708         print_quota(obd_uuid2str(&qctl->obd_uuid), qctl, MDS_QUOTA_INFO);
1709         return 0;
1710 }
1711
1712 static int print_lov_quota(char *mnt, struct if_quotactl *qctl)
1713 {
1714         DIR *dir;
1715         struct obd_uuid *uuids = NULL, *uuidp;
1716         int obdcount = 1024;
1717         int i, rc = 0, rc1 = 0;
1718
1719         dir = opendir(mnt);
1720         if (!dir) {
1721                 fprintf(stderr, "open %s failed: %s\n", mnt, strerror(errno));
1722                 return -ENOENT;
1723         }
1724
1725         uuids = (struct obd_uuid *)malloc(INIT_ALLOC_NUM_OSTS *
1726                                           sizeof(struct obd_uuid));
1727         if (uuids == NULL)
1728                 goto out;
1729
1730 retry_get_uuids:
1731         rc = llapi_lov_get_uuids(dirfd(dir), uuids, &obdcount);
1732         if (rc != 0) {
1733                 struct obd_uuid *uuids_temp;
1734
1735                 if (rc == -EOVERFLOW) {
1736                         uuids_temp = realloc(uuids, obdcount *
1737                                              sizeof(struct obd_uuid));
1738                         if (uuids_temp != NULL)
1739                                 goto retry_get_uuids;
1740                         else
1741                                 rc = -ENOMEM;
1742                 }
1743
1744                 fprintf(stderr, "get ost uuid failed: %s\n", strerror(rc));
1745                 goto out;
1746         }
1747
1748         for (i = 0, uuidp = uuids; i < obdcount; i++, uuidp++) {
1749                 memcpy(&qctl->obd_uuid, uuidp, sizeof(*uuidp));
1750
1751                 /* XXX clear this flag to get quota from osts */
1752                 qctl->qc_dqblk.dqb_valid = 0;
1753                 rc = llapi_quotactl(mnt, qctl);
1754                 if (rc) {
1755                         if (!rc1)
1756                                 rc1 = rc;
1757                         fprintf(stderr, "%s quotactl failed: %s\n",
1758                                 uuidp->uuid, strerror(errno));
1759                         continue;
1760                 }
1761
1762                 print_quota((char *)uuidp->uuid, qctl, OST_QUOTA_INFO);
1763         }
1764
1765 out:
1766         closedir(dir);
1767         if (!rc)
1768                 rc = rc1;
1769         return rc;
1770 }
1771
1772 static int lfs_quota(int argc, char **argv)
1773 {
1774         int c;
1775         char *name = NULL, *mnt;
1776         struct if_quotactl qctl = { .qc_cmd = LUSTRE_Q_GETQUOTA,
1777                                     .qc_type = 0x01 };
1778         char *obd_type = (char *)qctl.obd_type;
1779         char *obd_uuid = (char *)qctl.obd_uuid.uuid;
1780         int rc, rc1 = 0, rc2 = 0, rc3 = 0;
1781
1782         optind = 0;
1783         while ((c = getopt(argc, argv, "ugto:")) != -1) {
1784                 switch (c) {
1785                 case 'u':
1786                         qctl.qc_type = 0x01;
1787                         break;
1788                 case 'g':
1789                         qctl.qc_type = 0x02;
1790                         break;
1791                 case 't':
1792                         qctl.qc_cmd = LUSTRE_Q_GETINFO;
1793                         break;
1794                 case 'o':
1795                         strncpy(obd_uuid, optarg, sizeof(qctl.obd_uuid));
1796                         break;
1797                 default:
1798                         fprintf(stderr, "error: %s: option '-%c' "
1799                                         "unrecognized\n", argv[0], c);
1800                         return CMD_HELP;
1801                 }
1802         }
1803
1804         if (qctl.qc_type)
1805                 qctl.qc_type--;
1806
1807
1808         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) {
1809                 if (optind + 2 != argc) {
1810                         fprintf(stderr, "error: missing quota argument(s)\n");
1811                         return CMD_HELP;
1812                 }
1813
1814                 name = argv[optind++];
1815                 rc = name2id(&qctl.qc_id, name, qctl.qc_type);
1816                 if (rc) {
1817                         fprintf(stderr,"error: can't find id for name %s: %s\n",
1818                                 name, strerror(errno));
1819                         return CMD_HELP;
1820                 }
1821                 print_quota_title(name, &qctl);
1822         } else if (optind + 1 != argc) {
1823                 fprintf(stderr, "error: missing quota info argument(s)\n");
1824                 return CMD_HELP;
1825         }
1826
1827         mnt = argv[optind];
1828
1829         rc1 = llapi_quotactl(mnt, &qctl);
1830         if (rc1 == -1 && errno == ESRCH) {
1831                 fprintf(stderr, "\n%s quotas are not enabled.\n", 
1832                         qctl.qc_type == 0x00 ? "user" : "group");
1833                 return 0;
1834         }
1835         if (rc1 && *obd_type)
1836                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
1837
1838         if (!name)
1839                 rc = id2name(&name, getuid(), qctl.qc_type);
1840
1841         if (*obd_uuid) {
1842                 mnt = "";
1843                 name = obd_uuid;
1844         }
1845
1846         print_quota(mnt, &qctl, GENERAL_QUOTA_INFO);
1847
1848         if (!*obd_uuid && qctl.qc_cmd != LUSTRE_Q_GETINFO) {
1849                 rc2 = print_mds_quota(mnt, &qctl);
1850                 rc3 = print_lov_quota(mnt, &qctl);
1851         }
1852
1853         if (rc1 || rc2 || rc3)
1854                 printf("Some errors happened when getting quota info. "
1855                        "Some devices may be not working or deactivated. "
1856                        "The data in \"[]\" is inaccurate.\n");
1857         return 0;
1858 }
1859 #endif /* HAVE_QUOTA_SUPPORT */
1860
1861 int main(int argc, char **argv)
1862 {
1863         int rc;
1864
1865         setlinebuf(stdout);
1866
1867         ptl_initialize(argc, argv);
1868         if (obd_initialize(argc, argv) < 0)
1869                 exit(2);
1870         if (dbg_initialize(argc, argv) < 0)
1871                 exit(3);
1872
1873         Parser_init("lfs > ", cmdlist);
1874
1875         if (argc > 1) {
1876                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
1877         } else {
1878                 rc = Parser_commands();
1879         }
1880
1881         obd_finalize(argc, argv);
1882         return rc;
1883 }