Whamcloud - gitweb
845da41262da09ca5753e0e357466884aef3abc9
[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 obd_uuid *obduuid = NULL;
751         struct find_param param;
752         int rc=0;
753
754         if (argc != 1)
755                 return CMD_HELP;
756
757         fp = setmntent(MOUNTED, "r");
758
759         if (fp == NULL) {
760                  fprintf(stderr, "%s: setmntent(%s): %s:", argv[0], MOUNTED,
761                         strerror (errno));
762         } else {
763                 mnt = getmntent(fp);
764                 memset(&param, 0, sizeof(param));
765                 param.obduuid = obduuid;
766                 while (feof(fp) == 0 && ferror(fp) ==0) {
767                         if (llapi_is_lustre_mnt(mnt)) {
768                                 rc = llapi_getstripe(mnt->mnt_dir, &param);
769                                 if (rc)
770                                         fprintf(stderr,
771                                                "error: %s: failed on %s\n",
772                                                argv[0], mnt->mnt_dir);
773                         }
774                         mnt = getmntent(fp);
775                 }
776                 endmntent(fp);
777         }
778
779         return rc;
780 }
781
782 #define COOK(value)                                                     \
783 ({                                                                      \
784         int radix = 0;                                                  \
785         while (value > 1024) {                                          \
786                 value /= 1024;                                          \
787                 radix++;                                                \
788         }                                                               \
789         radix;                                                          \
790 })
791 #define UUF     "%-20s"
792 #define CSF     "%9s"
793 #define CDF     "%9llu"
794 #define HSF     "%8s"
795 #define HDF     "%6.1f"
796 #define RSF     "%5s"
797 #define RDF     "%4d%%"
798
799 static int path2mnt(char *path, FILE *fp, char *mntdir, int dir_len)
800 {
801         char rpath[PATH_MAX] = {'\0'};
802         struct mntent *mnt;
803         int rc, len, out_len = 0;
804
805         if (!realpath(path, rpath)) {
806                 rc = -errno;
807                 fprintf(stderr, "error: lfs df: invalid path '%s': %s\n",
808                         path, strerror(-rc));
809                 return rc;
810         }
811
812         len = 0;
813         mnt = getmntent(fp);
814         while (feof(fp) == 0 && ferror(fp) == 0) {
815                 if (llapi_is_lustre_mnt(mnt)) {
816                         len = strlen(mnt->mnt_dir);
817                         if (len > out_len &&
818                             !strncmp(rpath, mnt->mnt_dir, len)) {
819                                 out_len = len;
820                                 memset(mntdir, 0, dir_len);
821                                 strncpy(mntdir, mnt->mnt_dir, dir_len);
822                         }
823                 }
824                 mnt = getmntent(fp);
825         }
826
827         if (out_len > 0)
828                 return 0;
829
830         fprintf(stderr, "error: lfs df: %s isn't mounted on lustre\n", path);
831         return -EINVAL;
832 }
833
834 static int showdf(char *mntdir, struct obd_statfs *stat,
835                   char *uuid, int ishow, int cooked,
836                   char *type, int index, int rc)
837 {
838         long long avail, used, total;
839         double ratio = 0;
840         char *suffix = "KMGTPEZY";
841         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
842         char tbuf[20], ubuf[20], abuf[20], rbuf[20];
843
844         if (!uuid || !stat)
845                 return -EINVAL;
846
847         switch (rc) {
848         case 0:
849                 if (ishow) {
850                         avail = stat->os_ffree;
851                         used = stat->os_files - stat->os_ffree;
852                         total = stat->os_files;
853                 } else {
854                         int shift = cooked ? 0 : 10;
855
856                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
857                         used  = ((stat->os_blocks - stat->os_bfree) *
858                                  stat->os_bsize) >> shift;
859                         total = (stat->os_blocks * stat->os_bsize) >> shift;
860                 }
861
862                 if (total > 0)
863                         ratio = (double)used / (double)total;
864
865                 if (cooked) {
866                         int i;
867                         double cook_val;
868
869                         cook_val = (double)total;
870                         i = COOK(cook_val);
871                         if (i > 0)
872                                 sprintf(tbuf, HDF"%c", cook_val, suffix[i - 1]);
873                         else
874                                 sprintf(tbuf, CDF, total);
875
876                         cook_val = (double)used;
877                         i = COOK(cook_val);
878                         if (i > 0)
879                                 sprintf(ubuf, HDF"%c", cook_val, suffix[i - 1]);
880                         else
881                                 sprintf(ubuf, CDF, used);
882
883                         cook_val = (double)avail;
884                         i = COOK(cook_val);
885                         if (i > 0)
886                                 sprintf(abuf, HDF"%c", cook_val, suffix[i - 1]);
887                         else
888                                 sprintf(abuf, CDF, avail);
889                 } else {
890                         sprintf(tbuf, CDF, total);
891                         sprintf(ubuf, CDF, used);
892                         sprintf(abuf, CDF, avail);
893                 }
894
895                 sprintf(rbuf, RDF, (int)(ratio * 100));
896                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
897                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
898                 if (type)
899                         printf("[%s:%d]\n", type, index);
900                 else
901                         printf("\n");
902
903                 break;
904         case -ENODATA:
905                 printf(UUF": inactive device\n", uuid);
906                 break;
907         default:
908                 printf(UUF": %s\n", uuid, strerror(-rc));
909                 break;
910         }
911
912         return 0;
913 }
914
915 static int mntdf(char *mntdir, int ishow, int cooked)
916 {
917         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
918         struct obd_uuid uuid_buf;
919         __u32 index;
920         int rc;
921
922         if (ishow)
923                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
924                        "UUID", "Inodes", "IUsed", "IFree",
925                        "IUse%", "Mounted on");
926         else
927                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
928                        "UUID", cooked ? "bytes" : "1K-blocks",
929                        "Used", "Available", "Use%", "Mounted on");
930
931         for (index = 0; ; index++) {
932                 memset(&stat_buf, 0, sizeof(struct obd_statfs));
933                 memset(&uuid_buf, 0, sizeof(struct obd_uuid));
934                 rc = llapi_obd_statfs(mntdir, LL_STATFS_MDC, index,
935                                       &stat_buf, &uuid_buf);
936                 if (rc == -ENODEV)
937                         break;
938
939                 if (rc == -EAGAIN)
940                         continue;
941
942                 if (rc == -ENOTCONN || rc == -ETIMEDOUT || rc == -EIO ||
943                     rc == -ENODATA || rc == 0) {
944                         showdf(mntdir, &stat_buf, uuid_buf.uuid, ishow, cooked,
945                                "MDT", index, rc);
946                 } else {
947                         fprintf(stderr,
948                                 "error: llapi_obd_statfs(%s): %s (%d)\n",
949                                 uuid_buf.uuid, strerror(-rc), rc);
950                         return rc;
951                 }
952                 if (rc == 0) {
953                         sum.os_ffree += stat_buf.os_ffree;
954                         sum.os_files += stat_buf.os_files;
955                 }
956         }
957
958         for (index = 0; ; index++) {
959                 memset(&stat_buf, 0, sizeof(struct obd_statfs));
960                 memset(&uuid_buf, 0, sizeof(struct obd_uuid));
961                 rc = llapi_obd_statfs(mntdir, LL_STATFS_LOV, index,
962                                       &stat_buf, &uuid_buf);
963                 if (rc == -ENODEV)
964                         break;
965
966                 if (rc == -EAGAIN)
967                         continue;
968
969                 if (rc == -ENOTCONN || rc == -ETIMEDOUT || rc == -EIO ||
970                     rc == -ENODATA || rc == 0) {
971                         showdf(mntdir, &stat_buf, uuid_buf.uuid, ishow, cooked,
972                                "OST", index, rc);
973                 } else {
974                         fprintf(stderr,
975                                 "error: llapi_obd_statfs failed: %s (%d)\n",
976                                 strerror(-rc), rc);
977                         return rc;
978                 }
979                 if (rc == 0) {
980                         sum.os_blocks += stat_buf.os_blocks * stat_buf.os_bsize;
981                         sum.os_bfree  += stat_buf.os_bfree * stat_buf.os_bsize;
982                         sum.os_bavail += stat_buf.os_bavail * stat_buf.os_bsize;
983                 }
984         }
985
986         printf("\n");
987         showdf(mntdir, &sum, "filesystem summary:", ishow, cooked, NULL, 0,0);
988
989         return 0;
990 }
991
992 static int lfs_df(int argc, char **argv)
993 {
994         FILE *fp;
995         char *path = NULL;
996         struct mntent *mnt = NULL;
997         char *mntdir = NULL;
998         int ishow = 0, cooked = 0;
999         int c, rc = 0;
1000
1001         optind = 0;
1002         while ((c = getopt(argc, argv, "ih")) != -1) {
1003                 switch (c) {
1004                 case 'i':
1005                         ishow = 1;
1006                         break;
1007                 case 'h':
1008                         cooked = 1;
1009                         break;
1010                 default:
1011                         return CMD_HELP;
1012                 }
1013         }
1014         if (optind < argc )
1015                 path = argv[optind];
1016
1017         fp = setmntent(MOUNTED, "r");
1018         if (fp == NULL) {
1019                 rc = -errno;
1020                 fprintf(stderr, "error: %s: open %s failed( %s )\n",
1021                         argv[0], MOUNTED, strerror(errno));
1022                 return rc;
1023         }
1024
1025         if ((mntdir = malloc(PATH_MAX)) == NULL) {
1026                 fprintf(stderr, "error: cannot allocate %d bytes\n",
1027                         PATH_MAX);
1028                 return -ENOMEM;
1029         }
1030         memset(mntdir, 0, PATH_MAX);
1031
1032         if (path) {
1033                 rc = path2mnt(path, fp, mntdir, PATH_MAX);
1034                 if (rc) {
1035                         endmntent(fp);
1036                         free(mntdir);
1037                         return rc;
1038                 }
1039
1040                 rc = mntdf(mntdir, ishow, cooked);
1041                 printf("\n");
1042                 endmntent(fp);
1043         } else {
1044                 mnt = getmntent(fp);
1045                 while (feof(fp) == 0 && ferror(fp) == 0) {
1046                         if (llapi_is_lustre_mnt(mnt)) {
1047                                 rc = mntdf(mnt->mnt_dir, ishow, cooked);
1048                                 if (rc)
1049                                         break;
1050                                 printf("\n");
1051                         }
1052                         mnt = getmntent(fp);
1053                 }
1054                 endmntent(fp);
1055         }
1056
1057         free(mntdir);
1058         return rc;
1059 }
1060
1061 static int lfs_check(int argc, char **argv)
1062 {
1063         int rc;
1064         FILE *fp;
1065         struct mntent *mnt = NULL;
1066         int num_types = 1;
1067         char *obd_types[2];
1068         char obd_type1[4];
1069         char obd_type2[4];
1070
1071         if (argc != 2)
1072                 return CMD_HELP;
1073
1074         obd_types[0] = obd_type1;
1075         obd_types[1] = obd_type2;
1076
1077         if (strcmp(argv[1], "osts") == 0) {
1078                 strcpy(obd_types[0], "osc");
1079         } else if (strcmp(argv[1], "mds") == 0) {
1080                 strcpy(obd_types[0], "mdc");
1081         } else if (strcmp(argv[1], "servers") == 0) {
1082                 num_types = 2;
1083                 strcpy(obd_types[0], "osc");
1084                 strcpy(obd_types[1], "mdc");
1085         } else {
1086                 fprintf(stderr, "error: %s: option '%s' unrecognized\n",
1087                                 argv[0], argv[1]);
1088                         return CMD_HELP;
1089         }
1090
1091         fp = setmntent(MOUNTED, "r");
1092         if (fp == NULL) {
1093                  fprintf(stderr, "setmntent(%s): %s:", MOUNTED,
1094                         strerror (errno));
1095         } else {
1096                 mnt = getmntent(fp);
1097                 while (feof(fp) == 0 && ferror(fp) ==0) {
1098                         if (llapi_is_lustre_mnt(mnt))
1099                                 break;
1100                         mnt = getmntent(fp);
1101                 }
1102                 endmntent(fp);
1103         }
1104
1105         if (!mnt) {
1106                 fprintf(stderr, "No suitable Lustre mount found\n");
1107                 return -1;
1108         }
1109
1110         rc = llapi_target_check(num_types, obd_types, mnt->mnt_dir);
1111
1112         if (rc)
1113                 fprintf(stderr, "error: %s: %s status failed\n",
1114                                 argv[0],argv[1]);
1115
1116         return rc;
1117
1118 }
1119
1120 static int lfs_catinfo(int argc, char **argv)
1121 {
1122         FILE *fp;
1123         struct mntent *mnt = NULL;
1124         int rc;
1125
1126         if (argc < 2 || (!strcmp(argv[1],"config") && argc < 3))
1127                 return CMD_HELP;
1128
1129         if (strcmp(argv[1], "config") && strcmp(argv[1], "deletions"))
1130                 return CMD_HELP;
1131
1132         fp = setmntent(MOUNTED, "r");
1133         if (fp == NULL) {
1134                  fprintf(stderr, "setmntent(%s): %s:", MOUNTED,
1135                          strerror(errno));
1136         } else {
1137                 mnt = getmntent(fp);
1138                 while (feof(fp) == 0 && ferror(fp) == 0) {
1139                         if (llapi_is_lustre_mnt(mnt))
1140                                 break;
1141                         mnt = getmntent(fp);
1142                 }
1143                 endmntent(fp);
1144         }
1145
1146         if (mnt) {
1147                 if (argc == 3)
1148                         rc = llapi_catinfo(mnt->mnt_dir, argv[1], argv[2]);
1149                 else
1150                         rc = llapi_catinfo(mnt->mnt_dir, argv[1], NULL);
1151         } else {
1152                 fprintf(stderr, "no lustre_lite mounted.\n");
1153                 rc = -1;
1154         }
1155
1156         return rc;
1157 }
1158
1159 int lfs_join(int argc, char **argv)
1160 {
1161         char *name_head, *name_tail;
1162         int fd, rc;
1163         loff_t size;
1164
1165         if (argc != 3)
1166                 return CMD_HELP;
1167         name_head = argv[1];
1168         fd = open(name_head, O_WRONLY);
1169         if (fd < 0) {
1170                 fprintf(stderr, "Can not open name_head %s rc=%d\n",
1171                         name_head, fd);
1172                 return fd;
1173         }
1174         size = lseek(fd, 0, SEEK_END);
1175         if (size % JOIN_FILE_ALIGN) {
1176                 fprintf(stderr,"head file %s size %llu must be mutiple of %d\n",
1177                         name_head, (long long)size, JOIN_FILE_ALIGN);
1178                 rc = -EINVAL;
1179                 goto out;
1180         }
1181         name_tail = argv[2];
1182         rc = ioctl(fd, LL_IOC_JOIN, name_tail);
1183 out:
1184         close(fd);
1185         if (rc) {
1186                 fprintf(stderr, "Lustre joining files: %s, %s, failed\n",
1187                         argv[1], argv[2]);
1188         }
1189         return rc;
1190 }
1191
1192 #ifdef HAVE_QUOTA_SUPPORT
1193 static int lfs_quotachown(int argc, char **argv)
1194 {
1195
1196         int c,rc;
1197         int flag = 0;
1198
1199         optind = 0;
1200         while ((c = getopt(argc, argv, "i")) != -1) {
1201                 switch (c) {
1202                 case 'i':
1203                         flag++;
1204                         break;
1205                 default:
1206                         fprintf(stderr, "error: %s: option '-%c' "
1207                                         "unrecognized\n", argv[0], c);
1208                         return CMD_HELP;
1209                 }
1210         }
1211         if (optind == argc)
1212                 return CMD_HELP;
1213         rc = llapi_quotachown(argv[optind], flag);
1214         if(rc)
1215                 fprintf(stderr,"error: change file owner/group failed.\n");
1216         return rc;
1217 }
1218
1219
1220 static int lfs_quotacheck(int argc, char **argv)
1221 {
1222         int c, check_type = 0;
1223         char *mnt;
1224         struct if_quotacheck qchk;
1225         struct if_quotactl qctl;
1226         char *obd_type = qchk.obd_type;
1227         char *obd_uuid = qchk.obd_uuid.uuid;
1228         int rc;
1229
1230         memset(&qchk, 0, sizeof(qchk));
1231
1232         optind = 0;
1233         while ((c = getopt(argc, argv, "ug")) != -1) {
1234                 switch (c) {
1235                 case 'u':
1236                         check_type |= 0x01;
1237                         break;
1238                 case 'g':
1239                         check_type |= 0x02;
1240                         break;
1241                 default:
1242                         fprintf(stderr, "error: %s: option '-%c' "
1243                                         "unrecognized\n", argv[0], c);
1244                         return CMD_HELP;
1245                 }
1246         }
1247
1248         if (check_type)
1249                 check_type--;
1250         else    /* do quotacheck for both user & group quota by default */
1251                 check_type = 0x02;
1252
1253         if (argc == optind)
1254                 return CMD_HELP;
1255
1256         mnt = argv[optind];
1257
1258         memset(&qctl, 0, sizeof(qctl));
1259         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
1260         qctl.qc_id = QFMT_LDISKFS;
1261         qctl.qc_type = check_type;
1262         rc = llapi_quotactl(mnt, &qctl);
1263         if (rc) {
1264                 fprintf(stderr, "quota off failed: %s\n", strerror(errno));
1265                 return rc;
1266         }
1267
1268         rc = llapi_quotacheck(mnt, check_type);
1269         if (rc) {
1270                 fprintf(stderr, "quotacheck failed: %s\n", strerror(errno));
1271                 return rc;
1272         }
1273
1274         rc = llapi_poll_quotacheck(mnt, &qchk);
1275         if (rc) {
1276                 if (*obd_type)
1277                         fprintf(stderr, "%s %s ", obd_type, obd_uuid);
1278                 fprintf(stderr, "quota check failed: %s\n", strerror(errno));
1279                 return rc;
1280         }
1281
1282         memset(&qctl, 0, sizeof(qctl));
1283         qctl.qc_cmd = LUSTRE_Q_QUOTAON;
1284         qctl.qc_id = QFMT_LDISKFS;
1285         qctl.qc_type = check_type;
1286         rc = llapi_quotactl(mnt, &qctl);
1287         if (rc) {
1288                 if (*obd_type)
1289                         fprintf(stderr, "%s %s ",
1290                                 qctl.obd_type, qctl.obd_uuid.uuid);
1291                 fprintf(stderr, "%s turn on quota failed: %s\n",
1292                         argv[0], strerror(errno));
1293                 return rc;
1294         }
1295
1296         return 0;
1297 }
1298
1299 static int lfs_quotaon(int argc, char **argv)
1300 {
1301         int c;
1302         char *mnt;
1303         struct if_quotactl qctl;
1304         char *obd_type = qctl.obd_type;
1305         char *obd_uuid = qctl.obd_uuid.uuid;
1306         int rc;
1307
1308         memset(&qctl, 0, sizeof(qctl));
1309         qctl.qc_cmd = LUSTRE_Q_QUOTAON;
1310         qctl.qc_id = QFMT_LDISKFS;
1311
1312         optind = 0;
1313         while ((c = getopt(argc, argv, "ugf")) != -1) {
1314                 switch (c) {
1315                 case 'u':
1316                         qctl.qc_type |= 0x01;
1317                         break;
1318                 case 'g':
1319                         qctl.qc_type |= 0x02;
1320                         break;
1321                 case 'f':
1322                         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
1323                         break;
1324                 default:
1325                         fprintf(stderr, "error: %s: option '-%c' "
1326                                         "unrecognized\n", argv[0], c);
1327                         return CMD_HELP;
1328                 }
1329         }
1330
1331         if (qctl.qc_type)
1332                 qctl.qc_type--;
1333         else /* by default, enable quota for both user & group */
1334                 qctl.qc_type = 0x02;
1335
1336         if (argc == optind)
1337                 return CMD_HELP;
1338
1339         mnt = argv[optind];
1340
1341         rc = llapi_quotactl(mnt, &qctl);
1342         if (rc) {
1343                 if (*obd_type)
1344                         fprintf(stderr, "%s %s ", obd_type, obd_uuid);
1345                 fprintf(stderr, "%s failed: %s\n", argv[0], strerror(errno));
1346                 return rc;
1347         }
1348
1349         return 0;
1350 }
1351
1352 static int lfs_quotaoff(int argc, char **argv)
1353 {
1354         int c;
1355         char *mnt;
1356         struct if_quotactl qctl;
1357         char *obd_type = qctl.obd_type;
1358         char *obd_uuid = qctl.obd_uuid.uuid;
1359         int rc;
1360
1361         memset(&qctl, 0, sizeof(qctl));
1362         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
1363
1364         optind = 0;
1365         while ((c = getopt(argc, argv, "ug")) != -1) {
1366                 switch (c) {
1367                 case 'u':
1368                         qctl.qc_type |= 0x01;
1369                         break;
1370                 case 'g':
1371                         qctl.qc_type |= 0x02;
1372                         break;
1373                 default:
1374                         fprintf(stderr, "error: %s: option '-%c' "
1375                                         "unrecognized\n", argv[0], c);
1376                         return CMD_HELP;
1377                 }
1378         }
1379
1380         if (qctl.qc_type)
1381                 qctl.qc_type--;
1382         else /* by default, disable quota for both user & group */
1383                 qctl.qc_type = 0x02;
1384
1385         if (argc == optind)
1386                 return CMD_HELP;
1387
1388         mnt = argv[optind];
1389
1390         rc = llapi_quotactl(mnt, &qctl);
1391         if (rc) {
1392                 if (*obd_type)
1393                         fprintf(stderr, "%s %s ", obd_type, obd_uuid);
1394                 fprintf(stderr, "quotaoff failed: %s\n", strerror(errno));
1395                 return rc;
1396         }
1397
1398         return 0;
1399 }
1400
1401 #define ARG2INT(nr, str, msg)                                           \
1402 do {                                                                    \
1403         char *endp;                                                     \
1404         nr = strtol(str, &endp, 0);                                     \
1405         if (*endp) {                                                    \
1406                 fprintf(stderr, "error: bad %s: %s\n", msg, str);       \
1407                 return CMD_HELP;                                        \
1408         }                                                               \
1409 } while (0)
1410
1411 #define ADD_OVERFLOW(a,b) ((a + b) < a) ? (a = ULONG_MAX) : (a = a + b)
1412
1413 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
1414  * returns the value or ULONG_MAX on integer overflow or incorrect format
1415  * Notes:
1416  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
1417  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
1418  *        3. empty integer value is interpreted as 0
1419  */
1420  
1421 static unsigned long str2sec(const char* timestr) {
1422         const char spec[] = "smhdw";
1423         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
1424         unsigned long val = 0;
1425         char *tail;
1426
1427         if (strpbrk(timestr, spec) == NULL) {
1428                 /* no specifiers inside the time string,
1429                    should treat it as an integer value */
1430                 val = strtoul(timestr, &tail, 10);
1431                 return *tail ? ULONG_MAX : val;
1432         }
1433
1434         /* format string is XXwXXdXXhXXmXXs */
1435         while (*timestr) {
1436                 unsigned long v;
1437                 int ind;
1438                 char* ptr;
1439
1440                 v = strtoul(timestr, &tail, 10);
1441                 if (v == ULONG_MAX || *tail == '\0')
1442                         /* value too large (ULONG_MAX or more) 
1443                            or missing specifier */
1444                         goto error;
1445
1446                 ptr = strchr(spec, *tail);
1447                 if (ptr == NULL)
1448                         /* unknown specifier */
1449                         goto error;
1450
1451                 ind = ptr - spec;
1452
1453                 /* check if product will overflow the type */
1454                 if (!(v < ULONG_MAX / mult[ind]))
1455                         goto error;
1456
1457                 ADD_OVERFLOW(val, mult[ind] * v);
1458                 if (val == ULONG_MAX)
1459                         goto error;
1460
1461                 timestr = tail + 1;
1462         }
1463
1464         return val;
1465
1466 error:
1467         return ULONG_MAX;
1468 }
1469
1470 int lfs_setquota(int argc, char **argv)
1471 {
1472         int c;
1473         char *mnt;
1474         struct if_quotactl qctl;
1475         char *obd_type = qctl.obd_type;
1476         char *obd_uuid = qctl.obd_uuid.uuid;
1477         int rc;
1478
1479         memset(&qctl, 0, sizeof(qctl));
1480         qctl.qc_cmd = LUSTRE_Q_SETQUOTA;
1481
1482         optind = 0;
1483         while ((c = getopt(argc, argv, "ugt")) != -1) {
1484                 switch (c) {
1485                 case 'u':
1486                         qctl.qc_type |= 0x01;
1487                         break;
1488                 case 'g':
1489                         qctl.qc_type |= 0x02;
1490                         break;
1491                 case 't':
1492                         qctl.qc_cmd = LUSTRE_Q_SETINFO;
1493                         break;
1494                 default:
1495                         fprintf(stderr, "error: %s: option '-%c' "
1496                                         "unrecognized\n", argv[0], c);
1497                         return CMD_HELP;
1498                 }
1499         }
1500
1501         if (qctl.qc_type)
1502                 qctl.qc_type--;
1503
1504         if (qctl.qc_type == UGQUOTA) {
1505                 fprintf(stderr, "error: user and group quotas can't be set "
1506                                 "both\n");
1507                 return CMD_HELP;
1508         }
1509
1510         if (qctl.qc_cmd == LUSTRE_Q_SETQUOTA) {
1511                 struct obd_dqblk *dqb = &qctl.qc_dqblk;
1512
1513                 if (optind + 6 != argc)
1514                         return CMD_HELP;
1515
1516                 rc = name2id(&qctl.qc_id, argv[optind++], qctl.qc_type);
1517                 if (rc) {
1518                         fprintf(stderr, "error: find id for name %s failed: %s\n",
1519                                 argv[optind - 1], strerror(errno));
1520                         return CMD_HELP;
1521                 }
1522
1523                 ARG2INT(dqb->dqb_bsoftlimit, argv[optind++], "block-softlimit");
1524                 ARG2INT(dqb->dqb_bhardlimit, argv[optind++], "block-hardlimit");
1525                 ARG2INT(dqb->dqb_isoftlimit, argv[optind++], "inode-softlimit");
1526                 ARG2INT(dqb->dqb_ihardlimit, argv[optind++], "inode-hardlimit");
1527
1528                 dqb->dqb_valid = QIF_LIMITS;
1529         } else {
1530                 struct obd_dqinfo *dqi = &qctl.qc_dqinfo;
1531
1532                 if (optind + 3 != argc)
1533                         return CMD_HELP;
1534
1535                 if ((dqi->dqi_bgrace = str2sec(argv[optind++])) == ULONG_MAX) {
1536                         fprintf(stderr, "error: bad %s: %s\n", "block-grace", argv[optind - 1]);
1537                         return CMD_HELP;
1538                 }
1539                 if ((dqi->dqi_igrace = str2sec(argv[optind++])) == ULONG_MAX) {
1540                         fprintf(stderr, "error: bad %s: %s\n", "inode-grace", argv[optind - 1]);
1541                         return CMD_HELP;
1542                 }
1543         }
1544
1545         mnt = argv[optind];
1546
1547         rc = llapi_quotactl(mnt, &qctl);
1548         if (rc) {
1549                 if (*obd_type)
1550                         fprintf(stderr, "%s %s ", obd_type, obd_uuid);
1551                 fprintf(stderr, "setquota failed: %s\n", strerror(errno));
1552                 return rc;
1553         }
1554
1555         return 0;
1556 }
1557
1558 static inline char *type2name(int check_type)
1559 {
1560         if (check_type == USRQUOTA)
1561                 return "user";
1562         else if (check_type == GRPQUOTA)
1563                 return "group";
1564         else
1565                 return "unknown";
1566 }
1567
1568
1569 /* Converts seconds value into format string
1570  * result is returned in buf
1571  * Notes:
1572  *        1. result is in descenting order: 1w2d3h4m5s
1573  *        2. zero fields are not filled (except for p. 3): 5d1s
1574  *        3. zero seconds value is presented as "0s"
1575  */
1576 static void sec2str(time_t seconds, char *buf)
1577 {
1578         const char spec[] = "smhdw";
1579         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
1580         unsigned long c;
1581         char* tail = buf;
1582         int i;
1583
1584         for (i = sizeof(mult) / sizeof(mult[0]) - 1 ; i >= 0; i--) {
1585                 c = seconds / mult[i];
1586
1587                 if (c > 0 || (i == 0 && buf == tail))
1588                         tail += snprintf(tail, 40-(tail-buf), "%lu%c", c, spec[i]);
1589
1590                 seconds %= mult[i];
1591         }
1592 }
1593
1594
1595 static void diff2str(time_t seconds, char *buf, time_t now)
1596 {
1597
1598         buf[0] = 0;
1599         if (!seconds)
1600                 return;
1601         if (seconds <= now) {
1602                 strcpy(buf, "none");
1603                 return;
1604         }
1605         sec2str(seconds - now, buf);
1606 }
1607
1608 static void print_quota_title(char *name, struct if_quotactl *qctl)
1609 {
1610         printf("Disk quotas for %s %s (%cid %u):\n",
1611                type2name(qctl->qc_type), name,
1612                *type2name(qctl->qc_type), qctl->qc_id);
1613         printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
1614                "Filesystem",
1615                "kbytes", "quota", "limit", "grace",
1616                "files", "quota", "limit", "grace");
1617 }
1618
1619 static void print_quota(char *mnt, struct if_quotactl *qctl, int ost_only)
1620 {
1621         time_t now;
1622
1623         time(&now);
1624
1625         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA) {
1626                 int bover = 0, iover = 0;
1627                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
1628
1629                 if (dqb->dqb_bhardlimit &&
1630                     toqb(dqb->dqb_curspace) > dqb->dqb_bhardlimit) {
1631                         bover = 1;
1632                 } else if (dqb->dqb_bsoftlimit &&
1633                            toqb(dqb->dqb_curspace) > dqb->dqb_bsoftlimit) {
1634                         if (dqb->dqb_btime > now) {
1635                                 bover = 2;
1636                         } else {
1637                                 bover = 3;
1638                         }
1639                 }
1640
1641                 if (dqb->dqb_ihardlimit &&
1642                     dqb->dqb_curinodes > dqb->dqb_ihardlimit) {
1643                         iover = 1;
1644                 } else if (dqb->dqb_isoftlimit &&
1645                            dqb->dqb_curinodes > dqb->dqb_isoftlimit) {
1646                         if (dqb->dqb_btime > now) {
1647                                 iover = 2;
1648                         } else {
1649                                 iover = 3;
1650                         }
1651                 }
1652
1653 #if 0           /* XXX: always print quotas even when no usages */
1654                 if (dqb->dqb_curspace || dqb->dqb_curinodes)
1655 #endif
1656                 {
1657                         char numbuf[3][32];
1658                         char timebuf[40];
1659
1660                         if (strlen(mnt) > 15)
1661                                 printf("%s\n%15s", mnt, "");
1662                         else
1663                                 printf("%15s", mnt);
1664
1665                         if (bover)
1666                                 diff2str(dqb->dqb_btime, timebuf, now);
1667
1668                         sprintf(numbuf[0], LPU64, toqb(dqb->dqb_curspace));
1669                         sprintf(numbuf[1], LPU64, dqb->dqb_bsoftlimit);
1670                         sprintf(numbuf[2], LPU64, dqb->dqb_bhardlimit);
1671                         printf(" %7s%c %6s %7s %7s",
1672                                numbuf[0], bover ? '*' : ' ', numbuf[1],
1673                                numbuf[2], bover > 1 ? timebuf : "");
1674
1675                         if (iover)
1676                                 diff2str(dqb->dqb_itime, timebuf, now);
1677
1678                         sprintf(numbuf[0], LPU64, dqb->dqb_curinodes);
1679                         sprintf(numbuf[1], LPU64, dqb->dqb_isoftlimit);
1680                         sprintf(numbuf[2], LPU64, dqb->dqb_ihardlimit);
1681                         if (!ost_only)
1682                                 printf(" %7s%c %6s %7s %7s",
1683                                        numbuf[0], iover ? '*' : ' ', numbuf[1],
1684                                        numbuf[2], iover > 1 ? timebuf : "");
1685                         printf("\n");
1686                 }
1687         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO ||
1688                    qctl->qc_cmd == Q_GETOINFO) {
1689                 char bgtimebuf[40];
1690                 char igtimebuf[40];
1691
1692                 sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf);
1693                 sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf);
1694                 printf("Block grace time: %s; Inode grace time: %s\n",
1695                        bgtimebuf, igtimebuf);
1696         }
1697 }
1698
1699 static void print_mds_quota(char *mnt, struct if_quotactl *qctl)
1700 {
1701         int rc;
1702
1703         /* XXX: this is a flag to mark that only mds quota is wanted */
1704         qctl->qc_dqblk.dqb_valid = 1;
1705         rc = llapi_quotactl(mnt, qctl);
1706         if (rc) {
1707                 fprintf(stderr, "quotactl failed: %s\n", strerror(errno));
1708                 return;
1709         }
1710         qctl->qc_dqblk.dqb_valid = 0;
1711
1712         print_quota(qctl->obd_uuid.uuid, qctl, 0);
1713 }
1714
1715 static void print_lov_quota(char *mnt, struct if_quotactl *qctl)
1716 {
1717         DIR *dir;
1718         struct obd_uuid *uuids = NULL, *uuidp;
1719         int obdcount = 1024;
1720         int i, rc;
1721
1722         dir = opendir(mnt);
1723         if (!dir) {
1724                 fprintf(stderr, "open %s failed: %s\n", mnt, strerror(errno));
1725                 return;
1726         }
1727
1728         uuids = (struct obd_uuid *)malloc(INIT_ALLOC_NUM_OSTS *
1729                                           sizeof(struct obd_uuid));
1730         if (uuids == NULL)
1731                 goto out;
1732
1733 retry_get_uuids:
1734         rc = llapi_lov_get_uuids(dirfd(dir), uuids, &obdcount);
1735         if (rc != 0) {
1736                 struct obd_uuid *uuids_temp;
1737
1738                 if (rc == -EOVERFLOW) {
1739                         uuids_temp = realloc(uuids, obdcount *
1740                                              sizeof(struct obd_uuid));
1741                         if (uuids_temp != NULL)
1742                                 goto retry_get_uuids;
1743                         else
1744                                 rc = -ENOMEM;
1745                 }
1746
1747                 fprintf(stderr, "get ost uuid failed: %s\n", strerror(rc));
1748                 goto out;
1749         }
1750
1751         for (i = 0, uuidp = uuids; i < obdcount; i++, uuidp++) {
1752                 memcpy(&qctl->obd_uuid, uuidp, sizeof(*uuidp));
1753
1754                 /* XXX clear this flag to get quota from osts */
1755                 qctl->qc_dqblk.dqb_valid = 0;
1756                 rc = llapi_quotactl(mnt, qctl);
1757                 if (rc) {
1758                         fprintf(stderr, "%s quotactl failed: %s\n",
1759                                 uuidp->uuid, strerror(errno));
1760                         continue;
1761                 }
1762
1763                 print_quota(uuidp->uuid, qctl, 1);
1764         }
1765
1766 out:
1767         closedir(dir);
1768         return;
1769 }
1770
1771 static int lfs_quota(int argc, char **argv)
1772 {
1773         int c;
1774         char *name = NULL, *mnt;
1775         struct if_quotactl qctl = { .qc_cmd = LUSTRE_Q_GETQUOTA,
1776                                     .qc_type = 0x01 };
1777         char *obd_type = qctl.obd_type;
1778         char *obd_uuid = qctl.obd_uuid.uuid;
1779         int rc;
1780
1781         optind = 0;
1782         while ((c = getopt(argc, argv, "ugto:")) != -1) {
1783                 switch (c) {
1784                 case 'u':
1785                         qctl.qc_type = 0x01;
1786                         break;
1787                 case 'g':
1788                         qctl.qc_type = 0x02;
1789                         break;
1790                 case 't':
1791                         qctl.qc_cmd = LUSTRE_Q_GETINFO;
1792                         break;
1793                 case 'o':
1794                         strncpy(obd_uuid, optarg, sizeof(qctl.obd_uuid));
1795                         break;
1796                 default:
1797                         fprintf(stderr, "error: %s: option '-%c' "
1798                                         "unrecognized\n", argv[0], c);
1799                         return CMD_HELP;
1800                 }
1801         }
1802
1803         if (qctl.qc_type)
1804                 qctl.qc_type--;
1805
1806
1807         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) {
1808                 if (optind + 2 != argc) {
1809                         fprintf(stderr, "error: missing quota argument(s)\n");
1810                         return CMD_HELP;
1811                 }
1812
1813                 name = argv[optind++];
1814                 rc = name2id(&qctl.qc_id, name, qctl.qc_type);
1815                 if (rc) {
1816                         fprintf(stderr,"error: can't find id for name %s: %s\n",
1817                                 name, strerror(errno));
1818                         return CMD_HELP;
1819                 }
1820                 print_quota_title(name, &qctl);
1821         } else if (optind + 1 != argc) {
1822                 fprintf(stderr, "error: missing quota info argument(s)\n");
1823                 return CMD_HELP;
1824         }
1825
1826         mnt = argv[optind];
1827
1828         rc = llapi_quotactl(mnt, &qctl);
1829         if (rc) {
1830                 if (*obd_type)
1831                         fprintf(stderr, "%s %s ", obd_type, obd_uuid);
1832                 fprintf(stderr, "quota failed: %s\n", strerror(errno));
1833                 return rc;
1834         }
1835
1836         if (!name)
1837                 rc = id2name(&name, getuid(), qctl.qc_type);
1838
1839         if (*obd_uuid) {
1840                 mnt = "";
1841                 name = obd_uuid;
1842         }
1843
1844         print_quota(mnt, &qctl, 0);
1845
1846         if (!*obd_uuid && qctl.qc_cmd != LUSTRE_Q_GETINFO) {
1847                 print_mds_quota(mnt, &qctl);
1848                 print_lov_quota(mnt, &qctl);
1849         }
1850
1851         return 0;
1852 }
1853 #endif /* HAVE_QUOTA_SUPPORT */
1854
1855 static int flushctx_ioctl(char *mp)
1856 {
1857         int fd, rc;
1858
1859         fd = open(mp, O_RDONLY);
1860         if (fd == -1) {
1861                 fprintf(stderr, "flushctx: error open %s: %s\n",
1862                         mp, strerror(errno));
1863                 return -1;
1864         }
1865
1866         rc = ioctl(fd, LL_IOC_FLUSHCTX);
1867         if (rc == -1)
1868                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
1869                         mp, strerror(errno));
1870
1871         close(fd);
1872         return rc;
1873 }
1874
1875 static int lfs_flushctx(int argc, char **argv)
1876 {
1877         int     kdestroy = 0, c;
1878         FILE   *proc;
1879         char    procline[PATH_MAX], *line;
1880         int     rc = 0;
1881
1882         optind = 0;
1883         while ((c = getopt(argc, argv, "k")) != -1) {
1884                 switch (c) {
1885                 case 'k':
1886                         kdestroy = 1;
1887                         break;
1888                 default:
1889                         fprintf(stderr, "error: %s: option '-%c' "
1890                                         "unrecognized\n", argv[0], c);
1891                         return CMD_HELP;
1892                 }
1893         }
1894
1895         if (kdestroy)
1896                 system("kdestroy > /dev/null");
1897
1898         if (optind >= argc) {
1899                 /* flush for all mounted lustre fs. */
1900                 proc = fopen("/proc/mounts", "r");
1901                 if (!proc) {
1902                         fprintf(stderr, "error: %s: can't open /proc/mounts\n",
1903                                 argv[0]);
1904                         return -1;
1905                 }
1906
1907                 while ((line = fgets(procline, PATH_MAX, proc)) != NULL) {
1908                         char dev[PATH_MAX];
1909                         char mp[PATH_MAX];
1910                         char fs[PATH_MAX];
1911
1912                         if (sscanf(line, "%s %s %s", dev, mp, fs) != 3) {
1913                                 fprintf(stderr, "%s: unexpected format in "
1914                                                 "/proc/mounts\n",
1915                                         argv[0]);
1916                                 return -1;
1917                         }
1918
1919                         if (strcmp(fs, "lustre") != 0)
1920                                 continue;
1921                         /* we use '@' to determine it's a client. are there
1922                          * any other better way?
1923                          */
1924                         if (strchr(dev, '@') == NULL)
1925                                 continue;
1926
1927                         if (flushctx_ioctl(mp))
1928                                 rc = -1;
1929                 }
1930         } else {
1931                 /* flush fs as specified */
1932                 while (optind < argc) {
1933                         if (flushctx_ioctl(argv[optind++]))
1934                                 rc = -1;
1935                 }
1936         }
1937
1938         return rc;
1939 }
1940
1941 static int lfs_lsetfacl(int argc, char **argv)
1942 {
1943         argv[0]++;
1944         return(llapi_lsetfacl(argc, argv));
1945 }
1946
1947 static int lfs_lgetfacl(int argc, char **argv)
1948 {
1949         argv[0]++;
1950         return(llapi_lgetfacl(argc, argv));
1951 }
1952
1953 static int lfs_rsetfacl(int argc, char **argv)
1954 {
1955         argv[0]++;
1956         return(llapi_rsetfacl(argc, argv));
1957 }
1958
1959 static int lfs_rgetfacl(int argc, char **argv)
1960 {
1961         argv[0]++;
1962         return(llapi_rgetfacl(argc, argv));
1963 }
1964
1965 static int lfs_cp(int argc, char **argv)
1966 {
1967         return(llapi_cp(argc, argv));
1968 }
1969
1970 static int lfs_ls(int argc, char **argv)
1971 {
1972         return(llapi_ls(argc, argv));
1973 }
1974
1975 int main(int argc, char **argv)
1976 {
1977         int rc;
1978
1979         setlinebuf(stdout);
1980
1981         ptl_initialize(argc, argv);
1982         if (obd_initialize(argc, argv) < 0)
1983                 exit(2);
1984         if (dbg_initialize(argc, argv) < 0)
1985                 exit(3);
1986
1987         Parser_init("lfs > ", cmdlist);
1988
1989         if (argc > 1) {
1990                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
1991         } else {
1992                 rc = Parser_commands();
1993         }
1994
1995         obd_finalize(argc, argv);
1996         return rc;
1997 }