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