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