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