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