Whamcloud - gitweb
Branch b1_6
[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                 while ((c = getopt_long(argc, argv, "c:di:s:",
192                                                 long_opts, NULL)) >= 0) 
193                 {
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         while ((c = getopt_long_only(argc, argv, "-A:C:D:M:n:PpO:qrs:t:v",
341                                      long_opts, NULL)) >= 0) {
342                 xtime = NULL;
343                 xsign = NULL;
344                 if (neg_opt)
345                         --neg_opt;
346                 /* '!' is part of option */
347                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
348                 if (!isoption && pathend != -1) {
349                         fprintf(stderr, "err: %s: filename|dirname must either "
350                                         "precede options or follow options\n",
351                                         argv[0]);
352                         return CMD_HELP;
353                 }
354                 if (!isoption && pathstart == -1)
355                         pathstart = optind - 1;
356                 if (isoption && pathstart != -1 && pathend == -1) {
357                         pathend = optind - 2;
358                         if ((c == 1 && strcmp(optarg, "!") == 0) ||
359                             c == 'P' || c == 'p' || c == 'O' ||
360                             c == 'q' || c == 'r' || c == 'v')
361                                 pathend = optind - 1;
362                 }
363                 switch (c) {
364                 case 0:
365                         /* Long options. */
366                         break;
367                 case 1:
368                         if (strcmp(optarg, "!") == 0)
369                                 neg_opt = 2;
370                       break;
371                 case 'A':
372                         xtime = &param.atime;
373                         xsign = &param.asign;
374                 case 'C':
375                         if (c == 'C') {
376                                 xtime = &param.ctime;
377                                 xsign = &param.csign;
378                         }
379                 case 'M':
380                         if (c == 'M') {
381                                 xtime = &param.mtime;
382                                 xsign = &param.msign;
383                         }
384                         new_fashion = 1;
385                         if (neg_opt) {
386                                 if (optarg[0] == '-')
387                                         optarg[0] = '+';
388                                 else if (optarg[0] == '+')
389                                         optarg[0] = '-';
390                                 else {
391                                         str[0] = '-';
392                                         str[1] = '\0';
393                                         strcat(str, optarg);
394                                         optarg = str;
395                                 }
396                         }
397                         ret = set_time(&t, xtime, optarg);
398                         if (ret == INT_MAX)
399                                 return -1;
400                         if (ret)
401                                 *xsign = ret;
402                         break;
403                 case 'D':
404                         new_fashion = 1;
405                         param.maxdepth = strtol(optarg, 0, 0);
406                         break;
407                 case 'n':
408                         new_fashion = 1;
409                         param.pattern = (char *)optarg;
410                         param.exclude_pattern = !!neg_opt;
411                         break;
412                 case 'O': {
413                         char *buf, *token, *next, *p;
414                         int len;
415
416                         len = strlen((char *)optarg);
417                         buf = malloc(len+1);
418                         if (buf == NULL)
419                                 return -ENOMEM;
420                         strcpy(buf, (char *)optarg);
421
422                         if (param.num_alloc_obds == 0) {
423                                 param.obduuid = (struct obd_uuid *)malloc(FIND_MAX_OSTS *
424                                                        sizeof(struct obd_uuid));
425                                 if (param.obduuid == NULL)
426                                         return -ENOMEM;
427                                 param.num_alloc_obds = INIT_ALLOC_NUM_OSTS;
428                         }
429
430                         for (token = buf; token && *token; token = next) {
431                                 p = strchr(token, ',');
432                                 next = 0;
433                                 if (p) {
434                                         *p = 0;
435                                         next = p+1;
436                                 }
437                                 strcpy((char *)&param.obduuid[param.num_obds++].uuid,
438                                        token);
439                         }
440
441                         if (buf)
442                                 free(buf);
443                         break;
444                 }
445                 case 'p':
446                         new_fashion = 1;
447                         param.zeroend = 1;
448                         break;
449                 case 'P':
450                         break;
451                 case 'q':
452                         new_fashion = 0;
453                         param.quiet++;
454                         param.verbose = 0;
455                         break;
456                 case 'r':
457                         new_fashion = 0;
458                         param.recursive = 1;
459                         break;
460                 case 't':
461                         param.exclude_type = !!neg_opt;
462                         switch(optarg[0]) {
463                         case 'b': param.type = S_IFBLK; break;
464                         case 'c': param.type = S_IFCHR; break;
465                         case 'd': param.type = S_IFDIR; break;
466                         case 'f': param.type = S_IFREG; break;
467                         case 'l': param.type = S_IFLNK; break;
468                         case 'p': param.type = S_IFIFO; break;
469                         case 's': param.type = S_IFSOCK; break;
470 #ifdef S_IFDOOR /* Solaris only */
471                         case 'D': param.type = S_IFDOOR; break;
472 #endif
473                         default: fprintf(stderr, "error: %s: bad type '%s'\n",
474                                          argv[0], optarg);
475                                  return CMD_HELP;
476                         };
477                         break;
478                 case 's':
479                         if (neg_opt) {
480                                 if (optarg[0] == '-')
481                                         optarg[0] = '+';
482                                 else if (optarg[0] == '+')
483                                         optarg[0] = '-';
484                                 else {
485                                         str[0] = '-';
486                                         str[1] = '\0';
487                                         strcat(str, optarg);
488                                         optarg = str;
489                                 }
490                         }
491                         if (optarg[0] == '+')
492                                 param.size_sign = -1;
493                         else if (optarg[0] == '-')
494                                 param.size_sign = +1;
495
496                         if (param.size_sign)
497                                 optarg++;
498                         ret = parse_size(optarg, &param.size,&param.size_units);
499                         if (ret) {
500                                 fprintf(stderr,"error: bad size '%s'\n",
501                                         optarg);
502                                 return ret;
503                         }
504                         param.size_check = 1;
505                         break;
506                 case 'v':
507                         new_fashion = 0;
508                         param.verbose++;
509                         param.quiet = 0;
510                         break;
511                 case '?':
512                         return CMD_HELP;
513                 default:
514                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
515                                 argv[0], argv[optind - 1]);
516                         return CMD_HELP;
517                 };
518         }
519
520         if (pathstart == -1) {
521                 fprintf(stderr, "error: %s: no filename|pathname\n",
522                                 argv[0]);
523                 return CMD_HELP;
524         } else if (pathend == -1) {
525                 /* no options */
526                 pathend = argc;
527         }
528
529         if (new_fashion) {
530                 param.quiet = 1;
531         } else {
532                 static int deprecated_warning;
533                 if (!deprecated_warning) {
534                         fprintf(stderr, "lfs find: -q, -r, -v options "
535                                 "deprecated.  Use 'lfs getstripe' instead.\n");
536                         deprecated_warning = 1;
537                 }
538                 if (!param.recursive && param.maxdepth == -1)
539                         param.maxdepth = 1;
540         }
541
542         do {
543                 if (new_fashion)
544                         ret = llapi_find(argv[pathstart], &param);
545                 else
546                         ret = llapi_getstripe(argv[pathstart], &param);
547         } while (++pathstart < pathend && !ret);
548
549         if (ret)
550                 fprintf(stderr, "error: %s failed for %s.\n",
551                         argv[0], argv[optind - 1]);
552
553         if (param.obduuid && param.num_alloc_obds)
554                 free(param.obduuid);
555
556         return ret;
557 }
558
559 static int lfs_getstripe(int argc, char **argv)
560 {
561         struct option long_opts[] = {
562                 {"obd", 1, 0, 'O'},
563                 {"quiet", 0, 0, 'q'},
564                 {"recursive", 0, 0, 'r'},
565                 {"verbose", 0, 0, 'v'},
566                 {0, 0, 0, 0}
567         };
568         char short_opts[] = "hO:qrv";
569         int c, rc;
570         struct find_param param = { 0 };
571
572         optind = 0;
573         while ((c = getopt_long(argc, argv, short_opts,
574                                 long_opts, NULL)) != -1) {
575                 switch (c) {
576                 case 'O':
577                         if (param.obduuid) {
578                                 fprintf(stderr,
579                                         "error: %s: only one obduuid allowed",
580                                         argv[0]);
581                                 return CMD_HELP;
582                         }
583                         param.obduuid = (struct obd_uuid *)optarg;
584                         break;
585                 case 'q':
586                         param.quiet++;
587                         param.verbose = 0;
588                         break;
589                 case 'r':
590                         param.recursive = 1;
591                         break;
592                 case 'v':
593                         param.verbose++;
594                         param.quiet = 0;
595                         break;
596                 case '?':
597                         return CMD_HELP;
598                 default:
599                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
600                                 argv[0], argv[optind - 1]);
601                         return CMD_HELP;
602                 }
603         }
604
605         if (optind >= argc)
606                 return CMD_HELP;
607
608         param.maxdepth = param.recursive ? -1 : 1;
609
610         do {
611                 rc = llapi_getstripe(argv[optind], &param);
612         } while (++optind < argc && !rc);
613
614         if (rc)
615                 fprintf(stderr, "error: %s failed for %s.\n", 
616                         argv[0], argv[optind - 1]);
617         return rc;
618 }
619
620 static int lfs_osts(int argc, char **argv)
621 {
622         FILE *fp;
623         struct mntent *mnt = NULL;
624         struct obd_uuid *obduuid = NULL;
625         struct find_param param;
626         int rc=0;
627
628         if (argc != 1)
629                 return CMD_HELP;
630
631         fp = setmntent(MOUNTED, "r");
632
633         if (fp == NULL) {
634                  fprintf(stderr, "%s: setmntent(%s): %s:", argv[0], MOUNTED,
635                         strerror (errno));
636         } else {
637                 mnt = getmntent(fp);
638                 memset(&param, 0, sizeof(param));
639                 param.obduuid = obduuid;
640                 while (feof(fp) == 0 && ferror(fp) ==0) {
641                         if (llapi_is_lustre_mnt(mnt)) {
642                                 rc = llapi_getstripe(mnt->mnt_dir, &param);
643                                 if (rc)
644                                         fprintf(stderr,
645                                                "error: %s: failed on %s\n",
646                                                argv[0], mnt->mnt_dir);
647                         }
648                         mnt = getmntent(fp);
649                 }
650                 endmntent(fp);
651         }
652
653         return rc;
654 }
655
656 #define COOK(value)                                                     \
657 ({                                                                      \
658         int radix = 0;                                                  \
659         while (value > 1024) {                                          \
660                 value /= 1024;                                          \
661                 radix++;                                                \
662         }                                                               \
663         radix;                                                          \
664 })
665 #define UUF     "%-20s"
666 #define CSF     "%9s"
667 #define CDF     "%9llu"
668 #define HSF     "%8s"
669 #define HDF     "%6.1f"
670 #define RSF     "%5s"
671 #define RDF     "%4d%%"
672
673 static int path2mnt(char *path, FILE *fp, char *mntdir, int dir_len)
674 {
675         char rpath[PATH_MAX] = {'\0'};
676         struct mntent *mnt;
677         int rc, len, out_len = 0;
678
679         if (!realpath(path, rpath)) {
680                 rc = -errno;
681                 fprintf(stderr, "error: lfs df: invalid path '%s': %s\n",
682                         path, strerror(-rc));
683                 return rc;
684         }
685
686         len = 0;
687         mnt = getmntent(fp);
688         while (feof(fp) == 0 && ferror(fp) == 0) {
689                 if (llapi_is_lustre_mnt(mnt)) {
690                         len = strlen(mnt->mnt_dir);
691                         if (len > out_len &&
692                             !strncmp(rpath, mnt->mnt_dir, len)) {
693                                 out_len = len;
694                                 memset(mntdir, 0, dir_len);
695                                 strncpy(mntdir, mnt->mnt_dir, dir_len);
696                         }
697                 }
698                 mnt = getmntent(fp);
699         }
700
701         if (out_len > 0)
702                 return 0;
703
704         fprintf(stderr, "error: lfs df: %s isn't mounted on lustre\n", path);
705         return -EINVAL;
706 }
707
708 static int showdf(char *mntdir, struct obd_statfs *stat,
709                   char *uuid, int ishow, int cooked,
710                   char *type, int index, int rc)
711 {
712         long long avail, used, total;
713         double ratio = 0;
714         char *suffix = "KMGTPEZY";
715         char tbuf[10], ubuf[10], abuf[10], rbuf[10];
716
717         if (!uuid || !stat)
718                 return -EINVAL;
719
720         switch (rc) {
721         case 0:
722                 if (ishow) {
723                         avail = stat->os_ffree;
724                         used = stat->os_files - stat->os_ffree;
725                         total = stat->os_files;
726                 } else {
727                         int shift = cooked ? 0 : 10;
728
729                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
730                         used  = ((stat->os_blocks - stat->os_bfree) *
731                                  stat->os_bsize) >> shift;
732                         total = (stat->os_blocks * stat->os_bsize) >> shift;
733                 }
734
735                 if (total > 0)
736                         ratio = (double)used / (double)total;
737
738                 if (cooked) {
739                         int i;
740                         double cook_val;
741
742                         cook_val = (double)total;
743                         i = COOK(cook_val);
744                         if (i > 0)
745                                 sprintf(tbuf, HDF"%c", cook_val, suffix[i - 1]);
746                         else
747                                 sprintf(tbuf, CDF, total);
748
749                         cook_val = (double)used;
750                         i = COOK(cook_val);
751                         if (i > 0)
752                                 sprintf(ubuf, HDF"%c", cook_val, suffix[i - 1]);
753                         else
754                                 sprintf(ubuf, CDF, used);
755
756                         cook_val = (double)avail;
757                         i = COOK(cook_val);
758                         if (i > 0)
759                                 sprintf(abuf, HDF"%c", cook_val, suffix[i - 1]);
760                         else
761                                 sprintf(abuf, CDF, avail);
762                 } else {
763                         sprintf(tbuf, CDF, total);
764                         sprintf(ubuf, CDF, used);
765                         sprintf(abuf, CDF, avail);
766                 }
767
768                 sprintf(rbuf, RDF, (int)(ratio * 100));
769                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
770                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
771                 if (type)
772                         printf("[%s:%d]\n", type, index);
773                 else
774                         printf("\n");
775
776                 break;
777         case -ENODATA:
778                 printf(UUF": inactive device\n", uuid);
779                 break;
780         default:
781                 printf(UUF": %s\n", uuid, strerror(-rc));
782                 break;
783         }
784
785         return 0;
786 }
787
788 static int mntdf(char *mntdir, int ishow, int cooked)
789 {
790         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
791         struct obd_uuid uuid_buf;
792         __u32 index;
793         int rc;
794
795         if (ishow)
796                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
797                        "UUID", "Inodes", "IUsed", "IFree",
798                        "IUse%", "Mounted on");
799         else
800                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
801                        "UUID", cooked ? "bytes" : "1K-blocks",
802                        "Used", "Available", "Use%", "Mounted on");
803
804         for (index = 0; ; index++) {
805                 memset(&stat_buf, 0, sizeof(struct obd_statfs));
806                 memset(&uuid_buf, 0, sizeof(struct obd_uuid));
807                 rc = llapi_obd_statfs(mntdir, LL_STATFS_MDC, index,
808                                       &stat_buf, &uuid_buf);
809                 if (rc == -ENODEV)
810                         break;
811
812                 if (rc == -EAGAIN)
813                         continue;
814
815                 if (rc == -ENOTCONN || rc == -ETIMEDOUT || rc == -EIO ||
816                     rc == -ENODATA || rc == 0) {
817                         showdf(mntdir, &stat_buf, obd_uuid2str(&uuid_buf),
818                                ishow, cooked, "MDT", index, rc);
819                 } else {
820                         fprintf(stderr,
821                                 "error: llapi_obd_statfs(%s): %s (%d)\n",
822                                 obd_uuid2str(&uuid_buf), strerror(-rc), rc);
823                         return rc;
824                 }
825                 if (rc == 0) {
826                         sum.os_ffree += stat_buf.os_ffree;
827                         sum.os_files += stat_buf.os_files;
828                 }
829         }
830
831         for (index = 0; ; index++) {
832                 memset(&stat_buf, 0, sizeof(struct obd_statfs));
833                 memset(&uuid_buf, 0, sizeof(struct obd_uuid));
834                 rc = llapi_obd_statfs(mntdir, LL_STATFS_LOV, index,
835                                       &stat_buf, &uuid_buf);
836                 if (rc == -ENODEV)
837                         break;
838
839                 if (rc == -EAGAIN)
840                         continue;
841
842                 if (rc == -ENOTCONN || rc == -ETIMEDOUT || rc == -EIO ||
843                     rc == -ENODATA || rc == 0) {
844                         showdf(mntdir, &stat_buf, obd_uuid2str(&uuid_buf),
845                                ishow, cooked, "OST", index, rc);
846                 } else {
847                         fprintf(stderr,
848                                 "error: llapi_obd_statfs failed: %s (%d)\n",
849                                 strerror(-rc), rc);
850                         return rc;
851                 }
852                 if (rc == 0) {
853                         sum.os_blocks += stat_buf.os_blocks * stat_buf.os_bsize;
854                         sum.os_bfree  += stat_buf.os_bfree * stat_buf.os_bsize;
855                         sum.os_bavail += stat_buf.os_bavail * stat_buf.os_bsize;
856                 }
857         }
858
859         printf("\n");
860         showdf(mntdir, &sum, "filesystem summary:", ishow, cooked, NULL, 0,0);
861
862         return 0;
863 }
864
865 static int lfs_df(int argc, char **argv)
866 {
867         FILE *fp;
868         char *path = NULL;
869         struct mntent *mnt = NULL;
870         char mntdir[PATH_MAX] = {'\0'};
871         int ishow = 0, cooked = 0;
872         int c, rc = 0;
873
874         optind = 0;
875         while ((c = getopt(argc, argv, "ih")) != -1) {
876                 switch (c) {
877                 case 'i':
878                         ishow = 1;
879                         break;
880                 case 'h':
881                         cooked = 1;
882                         break;
883                 default:
884                         return CMD_HELP;
885                 }
886         }
887         if (optind < argc )
888                 path = argv[optind];
889
890         fp = setmntent(MOUNTED, "r");
891         if (fp == NULL) {
892                 rc = -errno;
893                 fprintf(stderr, "error: %s: open %s failed( %s )\n",
894                         argv[0], MOUNTED, strerror(errno));
895                 return rc;
896         }
897         if (path) {
898                 rc = path2mnt(path, fp, mntdir, sizeof(mntdir));
899                 if (rc) {
900                         endmntent(fp);
901                         return rc;
902                 }
903
904                 rc = mntdf(mntdir, ishow, cooked);
905                 printf("\n");
906                 endmntent(fp);
907         } else {
908                 mnt = getmntent(fp);
909                 while (feof(fp) == 0 && ferror(fp) == 0) {
910                         if (llapi_is_lustre_mnt(mnt)) {
911                                 rc = mntdf(mnt->mnt_dir, ishow, cooked);
912                                 if (rc)
913                                         break;
914                                 printf("\n");
915                         }
916                         mnt = getmntent(fp);
917                 }
918                 endmntent(fp);
919         }
920
921         return rc;
922 }
923
924 static int lfs_check(int argc, char **argv)
925 {
926         int rc;
927         FILE *fp;
928         struct mntent *mnt = NULL;
929         int num_types = 1;
930         char *obd_types[2];
931         char obd_type1[4];
932         char obd_type2[4];
933
934         if (argc != 2)
935                 return CMD_HELP;
936
937         obd_types[0] = obd_type1;
938         obd_types[1] = obd_type2;
939
940         if (strcmp(argv[1], "osts") == 0) {
941                 strcpy(obd_types[0], "osc");
942         } else if (strcmp(argv[1], "mds") == 0) {
943                 strcpy(obd_types[0], "mdc");
944         } else if (strcmp(argv[1], "servers") == 0) {
945                 num_types = 2;
946                 strcpy(obd_types[0], "osc");
947                 strcpy(obd_types[1], "mdc");
948         } else {
949                 fprintf(stderr, "error: %s: option '%s' unrecognized\n",
950                                 argv[0], argv[1]);
951                         return CMD_HELP;
952         }
953
954         fp = setmntent(MOUNTED, "r");
955         if (fp == NULL) {
956                  fprintf(stderr, "setmntent(%s): %s:", MOUNTED,
957                         strerror (errno));
958         } else {
959                 mnt = getmntent(fp);
960                 while (feof(fp) == 0 && ferror(fp) ==0) {
961                         if (llapi_is_lustre_mnt(mnt))
962                                 break;
963                         mnt = getmntent(fp);
964                 }
965                 endmntent(fp);
966         }
967
968         if (!mnt) {
969                 fprintf(stderr, "No suitable Lustre mount found\n");
970                 return -1;
971         }
972
973         rc = llapi_target_check(num_types, obd_types, mnt->mnt_dir);
974
975         if (rc)
976                 fprintf(stderr, "error: %s: %s status failed\n",
977                                 argv[0],argv[1]);
978
979         return rc;
980
981 }
982
983 static int lfs_catinfo(int argc, char **argv)
984 {
985         FILE *fp;
986         struct mntent *mnt = NULL;
987         int rc;
988
989         if (argc < 2 || (!strcmp(argv[1],"config") && argc < 3))
990                 return CMD_HELP;
991
992         if (strcmp(argv[1], "config") && strcmp(argv[1], "deletions"))
993                 return CMD_HELP;
994
995         fp = setmntent(MOUNTED, "r");
996         if (fp == NULL) {
997                  fprintf(stderr, "setmntent(%s): %s:", MOUNTED,
998                          strerror(errno));
999         } else {
1000                 mnt = getmntent(fp);
1001                 while (feof(fp) == 0 && ferror(fp) == 0) {
1002                         if (llapi_is_lustre_mnt(mnt))
1003                                 break;
1004                         mnt = getmntent(fp);
1005                 }
1006                 endmntent(fp);
1007         }
1008
1009         if (mnt) {
1010                 if (argc == 3)
1011                         rc = llapi_catinfo(mnt->mnt_dir, argv[1], argv[2]);
1012                 else
1013                         rc = llapi_catinfo(mnt->mnt_dir, argv[1], NULL);
1014         } else {
1015                 fprintf(stderr, "no lustre_lite mounted.\n");
1016                 rc = -1;
1017         }
1018
1019         return rc;
1020 }
1021
1022 int lfs_join(int argc, char **argv)
1023 {
1024         char *name_head, *name_tail;
1025         int fd, rc;
1026         loff_t size;
1027
1028         if (argc != 3)
1029                 return CMD_HELP;
1030         name_head = argv[1];
1031         fd = open(name_head, O_WRONLY);
1032         if (fd < 0) {
1033                 fprintf(stderr, "Can not open name_head %s rc=%d\n",
1034                         name_head, fd);
1035                 return fd;
1036         }
1037         size = lseek(fd, 0, SEEK_END);
1038         if (size % JOIN_FILE_ALIGN) {
1039                 fprintf(stderr,"head file %s size %llu must be mutiple of %d\n",
1040                         name_head, (long long)size, JOIN_FILE_ALIGN);
1041                 rc = -EINVAL;
1042                 goto out;
1043         }
1044         name_tail = argv[2];
1045         rc = ioctl(fd, LL_IOC_JOIN, name_tail);
1046 out:
1047         close(fd);
1048         if (rc) {
1049                 fprintf(stderr, "Lustre joining files: %s, %s, failed\n",
1050                         argv[1], argv[2]);
1051         }
1052         return rc;
1053 }
1054
1055 #ifdef HAVE_QUOTA_SUPPORT
1056 static int lfs_quotachown(int argc, char **argv)
1057 {
1058
1059         int c,rc;
1060         int flag = 0;
1061
1062         while ((c = getopt(argc, argv, "i")) != -1) {
1063                 switch (c) {
1064                 case 'i':
1065                         flag++;
1066                         break;
1067                 default:
1068                         fprintf(stderr, "error: %s: option '-%c' "
1069                                         "unrecognized\n", argv[0], c);
1070                         return CMD_HELP;
1071                 }
1072         }
1073         if (optind == argc)
1074                 return CMD_HELP;
1075         rc = llapi_quotachown(argv[optind], flag);
1076         if(rc)
1077                 fprintf(stderr,"error: change file owner/group failed.\n");
1078         return rc;
1079 }
1080
1081
1082 static int lfs_quotacheck(int argc, char **argv)
1083 {
1084         int c, check_type = 0;
1085         char *mnt;
1086         struct if_quotacheck qchk;
1087         struct if_quotactl qctl;
1088         char *obd_type = (char *)qchk.obd_type;
1089         int rc;
1090
1091         memset(&qchk, 0, sizeof(qchk));
1092
1093         optind = 0;
1094         while ((c = getopt(argc, argv, "ug")) != -1) {
1095                 switch (c) {
1096                 case 'u':
1097                         check_type |= 0x01;
1098                         break;
1099                 case 'g':
1100                         check_type |= 0x02;
1101                         break;
1102                 default:
1103                         fprintf(stderr, "error: %s: option '-%c' "
1104                                         "unrecognized\n", argv[0], c);
1105                         return CMD_HELP;
1106                 }
1107         }
1108
1109         if (check_type)
1110                 check_type--;
1111         else    /* do quotacheck for both user & group quota by default */
1112                 check_type = 0x02;
1113
1114         if (argc == optind)
1115                 return CMD_HELP;
1116
1117         mnt = argv[optind];
1118
1119         memset(&qctl, 0, sizeof(qctl));
1120         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
1121         qctl.qc_id = QFMT_LDISKFS;
1122         qctl.qc_type = check_type;
1123         rc = llapi_quotactl(mnt, &qctl);
1124         if (rc) {
1125                 fprintf(stderr, "quota off failed: %s\n", strerror(errno));
1126                 return rc;
1127         }
1128
1129         rc = llapi_quotacheck(mnt, check_type);
1130         if (rc) {
1131                 fprintf(stderr, "quotacheck failed: %s\n", strerror(errno));
1132                 return rc;
1133         }
1134
1135         rc = llapi_poll_quotacheck(mnt, &qchk);
1136         if (rc) {
1137                 if (*obd_type)
1138                         fprintf(stderr, "%s %s ", obd_type,
1139                                 obd_uuid2str(&qchk.obd_uuid));
1140                 fprintf(stderr, "quota check failed: %s\n", strerror(errno));
1141                 return rc;
1142         }
1143
1144         memset(&qctl, 0, sizeof(qctl));
1145         qctl.qc_cmd = LUSTRE_Q_QUOTAON;
1146         qctl.qc_id = QFMT_LDISKFS;
1147         qctl.qc_type = check_type;
1148         rc = llapi_quotactl(mnt, &qctl);
1149         if (rc) {
1150                 if (*obd_type)
1151                         fprintf(stderr, "%s %s ", (char *)qctl.obd_type,
1152                                 obd_uuid2str(&qctl.obd_uuid));
1153                 fprintf(stderr, "%s turn on quota failed: %s\n",
1154                         argv[0], strerror(errno));
1155                 return rc;
1156         }
1157
1158         return 0;
1159 }
1160
1161 static int lfs_quotaon(int argc, char **argv)
1162 {
1163         int c;
1164         char *mnt;
1165         struct if_quotactl qctl;
1166         char *obd_type = (char *)qctl.obd_type;
1167         int rc;
1168
1169         memset(&qctl, 0, sizeof(qctl));
1170         qctl.qc_cmd = LUSTRE_Q_QUOTAON;
1171         qctl.qc_id = QFMT_LDISKFS;
1172
1173         optind = 0;
1174         while ((c = getopt(argc, argv, "ugf")) != -1) {
1175                 switch (c) {
1176                 case 'u':
1177                         qctl.qc_type |= 0x01;
1178                         break;
1179                 case 'g':
1180                         qctl.qc_type |= 0x02;
1181                         break;
1182                 case 'f':
1183                         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
1184                         break;
1185                 default:
1186                         fprintf(stderr, "error: %s: option '-%c' "
1187                                         "unrecognized\n", argv[0], c);
1188                         return CMD_HELP;
1189                 }
1190         }
1191
1192         if (qctl.qc_type)
1193                 qctl.qc_type--;
1194         else /* by default, enable quota for both user & group */
1195                 qctl.qc_type = 0x02;
1196
1197         if (argc == optind)
1198                 return CMD_HELP;
1199
1200         mnt = argv[optind];
1201
1202         rc = llapi_quotactl(mnt, &qctl);
1203         if (rc) {
1204                 if (*obd_type)
1205                         fprintf(stderr, "%s %s ", obd_type,
1206                                 obd_uuid2str(&qctl.obd_uuid));
1207                 fprintf(stderr, "%s failed: %s\n", argv[0], strerror(errno));
1208                 return rc;
1209         }
1210
1211         return 0;
1212 }
1213
1214 static int lfs_quotaoff(int argc, char **argv)
1215 {
1216         int c;
1217         char *mnt;
1218         struct if_quotactl qctl;
1219         char *obd_type = (char *)qctl.obd_type;
1220         int rc;
1221
1222         memset(&qctl, 0, sizeof(qctl));
1223         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
1224
1225         optind = 0;
1226         while ((c = getopt(argc, argv, "ug")) != -1) {
1227                 switch (c) {
1228                 case 'u':
1229                         qctl.qc_type |= 0x01;
1230                         break;
1231                 case 'g':
1232                         qctl.qc_type |= 0x02;
1233                         break;
1234                 default:
1235                         fprintf(stderr, "error: %s: option '-%c' "
1236                                         "unrecognized\n", argv[0], c);
1237                         return CMD_HELP;
1238                 }
1239         }
1240
1241         if (qctl.qc_type)
1242                 qctl.qc_type--;
1243         else /* by default, disable quota for both user & group */
1244                 qctl.qc_type = 0x02;
1245
1246         if (argc == optind)
1247                 return CMD_HELP;
1248
1249         mnt = argv[optind];
1250
1251         rc = llapi_quotactl(mnt, &qctl);
1252         if (rc) {
1253                 if (*obd_type)
1254                         fprintf(stderr, "%s %s ", obd_type,
1255                                 obd_uuid2str(&qctl.obd_uuid));
1256                 fprintf(stderr, "quotaoff failed: %s\n", strerror(errno));
1257                 return rc;
1258         }
1259
1260         return 0;
1261 }
1262
1263 static int lfs_quotainv(int argc, char **argv)
1264 {
1265         int c;
1266         char *mnt;
1267         struct if_quotactl qctl;
1268         char *obd_type = (char *)qctl.obd_type;
1269         int rc;
1270
1271         memset(&qctl, 0, sizeof(qctl));
1272         qctl.qc_cmd = LUSTRE_Q_INVALIDATE;
1273
1274         optind = 0;
1275         while ((c = getopt(argc, argv, "ug")) != -1) {
1276                 switch (c) {
1277                 case 'u':
1278                         qctl.qc_type |= 0x01;
1279                         break;
1280                 case 'g':
1281                         qctl.qc_type |= 0x02;
1282                         break;
1283                 default:
1284                         fprintf(stderr, "error: %s: option '-%c' "
1285                                         "unrecognized\n", argv[0], c);
1286                         return CMD_HELP;
1287                 }
1288         }
1289
1290         if (qctl.qc_type)
1291                 qctl.qc_type--;
1292         else /* by default, invalidate quota for both user & group */
1293                 qctl.qc_type = 0x02;
1294
1295         if (argc == optind)
1296                 return CMD_HELP;
1297
1298         mnt = argv[optind];
1299
1300         rc = llapi_quotactl(mnt, &qctl);
1301         if (rc) {
1302                 fprintf(stderr, "quotainv failed: %s\n", strerror(errno));
1303                 return rc;
1304         }
1305
1306         return 0;
1307 }
1308
1309 static int name2id(unsigned int *id, char *name, int type)
1310 {
1311         if (type == USRQUOTA) {
1312                 struct passwd *entry;
1313
1314                 if (!(entry = getpwnam(name))) {
1315                         if (!errno)
1316                                 errno = ENOENT;
1317                         return -1;
1318                 }
1319
1320                 *id = entry->pw_uid;
1321         } else {
1322                 struct group *entry;
1323
1324                 if (!(entry = getgrnam(name))) {
1325                         if (!errno)
1326                                 errno = ENOENT;
1327                         return -1;
1328                 }
1329
1330                 *id = entry->gr_gid;
1331         }
1332
1333         return 0;
1334 }
1335
1336 static int id2name(char **name, unsigned int id, int type)
1337 {
1338         if (type == USRQUOTA) {
1339                 struct passwd *entry;
1340
1341                 if (!(entry = getpwuid(id))) {
1342                         if (!errno)
1343                                 errno = ENOENT;
1344                         return -1;
1345                 }
1346
1347                 *name = entry->pw_name;
1348         } else {
1349                 struct group *entry;
1350
1351                 if (!(entry = getgrgid(id))) {
1352                         if (!errno)
1353                                 errno = ENOENT;
1354                         return -1;
1355                 }
1356
1357                 *name = entry->gr_name;
1358         }
1359
1360         return 0;
1361 }
1362
1363 #define ARG2INT(nr, str, msg)                                           \
1364 do {                                                                    \
1365         char *endp;                                                     \
1366         nr = strtol(str, &endp, 0);                                     \
1367         if (*endp) {                                                    \
1368                 fprintf(stderr, "error: bad %s: %s\n", msg, str);       \
1369                 return CMD_HELP;                                        \
1370         }                                                               \
1371 } while (0)
1372
1373 #define ADD_OVERFLOW(a,b) ((a + b) < a) ? (a = ULONG_MAX) : (a = a + b)
1374
1375 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
1376  * returns the value or ULONG_MAX on integer overflow or incorrect format
1377  * Notes:
1378  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
1379  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
1380  *        3. empty integer value is interpreted as 0
1381  */
1382
1383 static unsigned long str2sec(const char* timestr) {
1384         const char spec[] = "smhdw";
1385         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
1386         unsigned long val = 0;
1387         char *tail;
1388
1389         if (strpbrk(timestr, spec) == NULL) {
1390                 /* no specifiers inside the time string,
1391                    should treat it as an integer value */
1392                 val = strtoul(timestr, &tail, 10);
1393                 return *tail ? ULONG_MAX : val;
1394         }
1395
1396         /* format string is XXwXXdXXhXXmXXs */
1397         while (*timestr) {
1398                 unsigned long v;
1399                 int ind;
1400                 char* ptr;
1401
1402                 v = strtoul(timestr, &tail, 10);
1403                 if (v == ULONG_MAX || *tail == '\0')
1404                         /* value too large (ULONG_MAX or more) 
1405                            or missing specifier */
1406                         goto error;
1407
1408                 ptr = strchr(spec, *tail);
1409                 if (ptr == NULL)
1410                         /* unknown specifier */
1411                         goto error;
1412
1413                 ind = ptr - spec;
1414
1415                 /* check if product will overflow the type */
1416                 if (!(v < ULONG_MAX / mult[ind]))
1417                         goto error;
1418
1419                 ADD_OVERFLOW(val, mult[ind] * v);
1420                 if (val == ULONG_MAX)
1421                         goto error;
1422
1423                 timestr = tail + 1;
1424         }
1425
1426         return val;
1427
1428 error:
1429         return ULONG_MAX;
1430 }
1431
1432 #define ARG2ULL(nr, str, msg)                                           \
1433 do {                                                                    \
1434         char *endp;                                                     \
1435         nr = strtoull(str, &endp, 0);                                   \
1436         if (*endp) {                                                    \
1437                 fprintf(stderr, "error: bad %s: %s\n", msg, str);       \
1438                 return CMD_HELP;                                        \
1439         }                                                               \
1440 } while (0)
1441
1442
1443 int lfs_setquota(int argc, char **argv)
1444 {
1445         int c;
1446         char *mnt;
1447         struct if_quotactl qctl;
1448         char *obd_type = (char *)qctl.obd_type;
1449         int rc;
1450
1451         memset(&qctl, 0, sizeof(qctl));
1452         qctl.qc_cmd = LUSTRE_Q_SETQUOTA;
1453
1454         optind = 0;
1455         while ((c = getopt(argc, argv, "ugt")) != -1) {
1456                 switch (c) {
1457                 case 'u':
1458                         qctl.qc_type |= 0x01;
1459                         break;
1460                 case 'g':
1461                         qctl.qc_type |= 0x02;
1462                         break;
1463                 case 't':
1464                         qctl.qc_cmd = LUSTRE_Q_SETINFO;
1465                         break;
1466                 default:
1467                         fprintf(stderr, "error: %s: option '-%c' "
1468                                         "unrecognized\n", argv[0], c);
1469                         return CMD_HELP;
1470                 }
1471         }
1472
1473         if (qctl.qc_type)
1474                 qctl.qc_type--;
1475
1476         if (qctl.qc_type == UGQUOTA) {
1477                 fprintf(stderr, "error: user and group quotas can't be set "
1478                                 "both\n");
1479                 return CMD_HELP;
1480         }
1481
1482         if (qctl.qc_cmd == LUSTRE_Q_SETQUOTA) {
1483                 struct obd_dqblk *dqb = &qctl.qc_dqblk;
1484
1485                 if (optind + 6 != argc)
1486                         return CMD_HELP;
1487
1488                 rc = name2id(&qctl.qc_id, argv[optind++], qctl.qc_type);
1489                 if (rc) {
1490                         fprintf(stderr, "error: find id for name %s failed: %s\n",
1491                                 argv[optind - 1], strerror(errno));
1492                         return CMD_HELP;
1493                 }
1494
1495                 ARG2ULL(dqb->dqb_bsoftlimit, argv[optind++], "block-softlimit");
1496                 ARG2ULL(dqb->dqb_bhardlimit, argv[optind++], "block-hardlimit");
1497                 ARG2ULL(dqb->dqb_isoftlimit, argv[optind++], "inode-softlimit");
1498                 ARG2ULL(dqb->dqb_ihardlimit, argv[optind++], "inode-hardlimit");
1499
1500                 dqb->dqb_valid = QIF_LIMITS;
1501         } else {
1502                 struct obd_dqinfo *dqi = &qctl.qc_dqinfo;
1503
1504                 if (optind + 3 != argc)
1505                         return CMD_HELP;
1506
1507                 if ((dqi->dqi_bgrace = str2sec(argv[optind++])) == ULONG_MAX) {
1508                         fprintf(stderr, "error: bad %s: %s\n", "block-grace", argv[optind - 1]);
1509                         return CMD_HELP;
1510                 }
1511                 if ((dqi->dqi_igrace = str2sec(argv[optind++])) == ULONG_MAX) {
1512                         fprintf(stderr, "error: bad %s: %s\n", "inode-grace", argv[optind - 1]);
1513                         return CMD_HELP;
1514                 }
1515         }
1516
1517         mnt = argv[optind];
1518
1519         rc = llapi_quotactl(mnt, &qctl);
1520         if (rc) {
1521                 if (*obd_type)
1522                         fprintf(stderr, "%s %s ", obd_type,
1523                                 obd_uuid2str(&qctl.obd_uuid));
1524                 fprintf(stderr, "setquota failed: %s\n", strerror(errno));
1525                 return rc;
1526         }
1527
1528         return 0;
1529 }
1530
1531 static inline char *type2name(int check_type)
1532 {
1533         if (check_type == USRQUOTA)
1534                 return "user";
1535         else if (check_type == GRPQUOTA)
1536                 return "group";
1537         else
1538                 return "unknown";
1539 }
1540
1541
1542 /* Converts seconds value into format string
1543  * result is returned in buf
1544  * Notes:
1545  *        1. result is in descenting order: 1w2d3h4m5s
1546  *        2. zero fields are not filled (except for p. 3): 5d1s
1547  *        3. zero seconds value is presented as "0s"
1548  */
1549 static void sec2str(time_t seconds, char *buf)
1550 {
1551         const char spec[] = "smhdw";
1552         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
1553         unsigned long c;
1554         char* tail = buf;
1555         int i;
1556
1557         for (i = sizeof(mult) / sizeof(mult[0]) - 1 ; i >= 0; i--) {
1558                 c = seconds / mult[i];
1559
1560                 if (c > 0 || (i == 0 && buf == tail))
1561                         tail += snprintf(tail, 40-(tail-buf), "%lu%c", c, spec[i]);
1562
1563                 seconds %= mult[i];
1564         }
1565 }
1566
1567
1568 static void diff2str(time_t seconds, char *buf, time_t now)
1569 {
1570
1571         buf[0] = 0;
1572         if (!seconds)
1573                 return;
1574         if (seconds <= now) {
1575                 strcpy(buf, "none");
1576                 return;
1577         }
1578         sec2str(seconds - now, buf);
1579 }
1580
1581 static void print_quota_title(char *name, struct if_quotactl *qctl)
1582 {
1583         printf("Disk quotas for %s %s (%cid %u):\n",
1584                type2name(qctl->qc_type), name,
1585                *type2name(qctl->qc_type), qctl->qc_id);
1586         printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
1587                "Filesystem",
1588                "kbytes", "quota", "limit", "grace",
1589                "files", "quota", "limit", "grace");
1590 }
1591
1592 #define GENERAL_QUOTA_INFO 1
1593 #define MDS_QUOTA_INFO     2
1594 #define OST_QUOTA_INFO     3
1595
1596 static void print_quota(char *mnt, struct if_quotactl *qctl, int type)
1597 {
1598         time_t now;
1599
1600         time(&now);
1601
1602         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA) {
1603                 int bover = 0, iover = 0;
1604                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
1605
1606                 if (dqb->dqb_bhardlimit &&
1607                     toqb(dqb->dqb_curspace) > dqb->dqb_bhardlimit) {
1608                         bover = 1;
1609                 } else if (dqb->dqb_bsoftlimit &&
1610                            toqb(dqb->dqb_curspace) > dqb->dqb_bsoftlimit) {
1611                         if (dqb->dqb_btime > now) {
1612                                 bover = 2;
1613                         } else {
1614                                 bover = 3;
1615                         }
1616                 }
1617
1618                 if (dqb->dqb_ihardlimit &&
1619                     dqb->dqb_curinodes > dqb->dqb_ihardlimit) {
1620                         iover = 1;
1621                 } else if (dqb->dqb_isoftlimit &&
1622                            dqb->dqb_curinodes > dqb->dqb_isoftlimit) {
1623                         if (dqb->dqb_btime > now) {
1624                                 iover = 2;
1625                         } else {
1626                                 iover = 3;
1627                         }
1628                 }
1629
1630 #if 0           /* XXX: always print quotas even when no usages */
1631                 if (dqb->dqb_curspace || dqb->dqb_curinodes)
1632 #endif
1633                 {
1634                         char numbuf[3][32];
1635                         char timebuf[40];
1636
1637                         if (strlen(mnt) > 15)
1638                                 printf("%s\n%15s", mnt, "");
1639                         else
1640                                 printf("%15s", mnt);
1641
1642                         if (bover)
1643                                 diff2str(dqb->dqb_btime, timebuf, now);
1644                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
1645                                 LPU64 : "["LPU64"]", toqb(dqb->dqb_curspace));
1646                         if (type == GENERAL_QUOTA_INFO)
1647                                 sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS)
1648                                         ? LPU64 : "["LPU64"]",
1649                                         dqb->dqb_bsoftlimit);
1650                         else
1651                                 sprintf(numbuf[1], "%s", "");
1652                         sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS)
1653                                 ? LPU64 : "["LPU64"]", dqb->dqb_bhardlimit);
1654                         printf(" %7s%c %6s %7s %7s",
1655                                numbuf[0], bover ? '*' : ' ', numbuf[1],
1656                                numbuf[2], bover > 1 ? timebuf : "");
1657
1658                         if (iover)
1659                                 diff2str(dqb->dqb_itime, timebuf, now);
1660
1661                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_INODES) ?
1662                                 LPU64 : "["LPU64"]", dqb->dqb_curinodes);
1663                        if (type == GENERAL_QUOTA_INFO)
1664                                 sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS)
1665                                         ? LPU64 : "["LPU64"]",
1666                                         dqb->dqb_isoftlimit);
1667                         else
1668                                 sprintf(numbuf[1], "%s", "");
1669                         sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
1670                                 LPU64 : "["LPU64"]", dqb->dqb_ihardlimit);
1671                         if (type != OST_QUOTA_INFO)
1672                                 printf(" %7s%c %6s %7s %7s",
1673                                        numbuf[0], iover ? '*' : ' ', numbuf[1],
1674                                        numbuf[2], iover > 1 ? timebuf : "");
1675                         printf("\n");
1676                 }
1677         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO ||
1678                    qctl->qc_cmd == Q_GETOINFO) {
1679                 char bgtimebuf[40];
1680                 char igtimebuf[40];
1681
1682                 sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf);
1683                 sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf);
1684                 printf("Block grace time: %s; Inode grace time: %s\n",
1685                        bgtimebuf, igtimebuf);
1686         }
1687 }
1688
1689 static int print_mds_quota(char *mnt, struct if_quotactl *qctl)
1690 {
1691         int rc;
1692
1693         /* XXX: this is a flag to mark that only mds quota is wanted */
1694         qctl->qc_dqblk.dqb_valid = 1;
1695         rc = llapi_quotactl(mnt, qctl);
1696         if (rc) {
1697                 fprintf(stderr, "quotactl failed: %s\n", strerror(errno));
1698                 return rc;
1699         }
1700
1701         print_quota(obd_uuid2str(&qctl->obd_uuid), qctl, MDS_QUOTA_INFO);
1702         return 0;
1703 }
1704
1705 static int print_lov_quota(char *mnt, struct if_quotactl *qctl)
1706 {
1707         DIR *dir;
1708         struct obd_uuid *uuids = NULL, *uuidp;
1709         int obdcount = 1024;
1710         int i, rc = 0, rc1 = 0;
1711
1712         dir = opendir(mnt);
1713         if (!dir) {
1714                 fprintf(stderr, "open %s failed: %s\n", mnt, strerror(errno));
1715                 return -ENOENT;
1716         }
1717
1718         uuids = (struct obd_uuid *)malloc(INIT_ALLOC_NUM_OSTS *
1719                                           sizeof(struct obd_uuid));
1720         if (uuids == NULL)
1721                 goto out;
1722
1723 retry_get_uuids:
1724         rc = llapi_lov_get_uuids(dirfd(dir), uuids, &obdcount);
1725         if (rc != 0) {
1726                 struct obd_uuid *uuids_temp;
1727
1728                 if (rc == -EOVERFLOW) {
1729                         uuids_temp = realloc(uuids, obdcount *
1730                                              sizeof(struct obd_uuid));
1731                         if (uuids_temp != NULL)
1732                                 goto retry_get_uuids;
1733                         else
1734                                 rc = -ENOMEM;
1735                 }
1736
1737                 fprintf(stderr, "get ost uuid failed: %s\n", strerror(rc));
1738                 goto out;
1739         }
1740
1741         for (i = 0, uuidp = uuids; i < obdcount; i++, uuidp++) {
1742                 memcpy(&qctl->obd_uuid, uuidp, sizeof(*uuidp));
1743
1744                 /* XXX clear this flag to get quota from osts */
1745                 qctl->qc_dqblk.dqb_valid = 0;
1746                 rc = llapi_quotactl(mnt, qctl);
1747                 if (rc) {
1748                         if (!rc1)
1749                                 rc1 = rc;
1750                         fprintf(stderr, "%s quotactl failed: %s\n",
1751                                 uuidp->uuid, strerror(errno));
1752                         continue;
1753                 }
1754
1755                 print_quota((char *)uuidp->uuid, qctl, OST_QUOTA_INFO);
1756         }
1757
1758 out:
1759         closedir(dir);
1760         if (!rc)
1761                 rc = rc1;
1762         return rc;
1763 }
1764
1765 static int lfs_quota(int argc, char **argv)
1766 {
1767         int c;
1768         char *name = NULL, *mnt;
1769         struct if_quotactl qctl = { .qc_cmd = LUSTRE_Q_GETQUOTA,
1770                                     .qc_type = 0x01 };
1771         char *obd_type = (char *)qctl.obd_type;
1772         char *obd_uuid = (char *)qctl.obd_uuid.uuid;
1773         int rc, rc1 = 0, rc2 = 0, rc3 = 0;
1774
1775         optind = 0;
1776         while ((c = getopt(argc, argv, "ugto:")) != -1) {
1777                 switch (c) {
1778                 case 'u':
1779                         qctl.qc_type = 0x01;
1780                         break;
1781                 case 'g':
1782                         qctl.qc_type = 0x02;
1783                         break;
1784                 case 't':
1785                         qctl.qc_cmd = LUSTRE_Q_GETINFO;
1786                         break;
1787                 case 'o':
1788                         strncpy(obd_uuid, optarg, sizeof(qctl.obd_uuid));
1789                         break;
1790                 default:
1791                         fprintf(stderr, "error: %s: option '-%c' "
1792                                         "unrecognized\n", argv[0], c);
1793                         return CMD_HELP;
1794                 }
1795         }
1796
1797         if (qctl.qc_type)
1798                 qctl.qc_type--;
1799
1800
1801         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) {
1802                 if (optind + 2 != argc) {
1803                         fprintf(stderr, "error: missing quota argument(s)\n");
1804                         return CMD_HELP;
1805                 }
1806
1807                 name = argv[optind++];
1808                 rc = name2id(&qctl.qc_id, name, qctl.qc_type);
1809                 if (rc) {
1810                         fprintf(stderr,"error: can't find id for name %s: %s\n",
1811                                 name, strerror(errno));
1812                         return CMD_HELP;
1813                 }
1814                 print_quota_title(name, &qctl);
1815         } else if (optind + 1 != argc) {
1816                 fprintf(stderr, "error: missing quota info argument(s)\n");
1817                 return CMD_HELP;
1818         }
1819
1820         mnt = argv[optind];
1821
1822         rc1 = llapi_quotactl(mnt, &qctl);
1823         if (rc1 && *obd_type)
1824                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
1825
1826         if (!name)
1827                 rc = id2name(&name, getuid(), qctl.qc_type);
1828
1829         if (*obd_uuid) {
1830                 mnt = "";
1831                 name = obd_uuid;
1832         }
1833
1834         print_quota(mnt, &qctl, GENERAL_QUOTA_INFO);
1835
1836         if (!*obd_uuid && qctl.qc_cmd != LUSTRE_Q_GETINFO) {
1837                 rc2 = print_mds_quota(mnt, &qctl);
1838                 rc3 = print_lov_quota(mnt, &qctl);
1839         }
1840
1841         if (rc1 || rc2 || rc3)
1842                 printf("Some errors happened when getting quota info. "
1843                        "Some devices may be not working or deactivated. "
1844                        "The data in \"[]\" is inaccurate.\n");
1845         return 0;
1846 }
1847 #endif /* HAVE_QUOTA_SUPPORT */
1848
1849 int main(int argc, char **argv)
1850 {
1851         int rc;
1852
1853         setlinebuf(stdout);
1854
1855         ptl_initialize(argc, argv);
1856         if (obd_initialize(argc, argv) < 0)
1857                 exit(2);
1858         if (dbg_initialize(argc, argv) < 0)
1859                 exit(3);
1860
1861         Parser_init("lfs > ", cmdlist);
1862
1863         if (argc > 1) {
1864                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
1865         } else {
1866                 rc = Parser_commands();
1867         }
1868
1869         obd_finalize(argc, argv);
1870         return rc;
1871 }