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