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