Whamcloud - gitweb
b=19720
[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  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright  2008 Sun Microsystems, Inc. All rights reserved
30  * Use is subject to license terms.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/utils/lfs.c
37  *
38  * Author: Peter J. Braam <braam@clusterfs.com>
39  * Author: Phil Schwan <phil@clusterfs.com>
40  * Author: Robert Read <rread@clusterfs.com>
41  */
42
43 /* for O_DIRECTORY */
44 #ifndef _GNU_SOURCE
45 #define _GNU_SOURCE
46 #endif
47
48 #include <stdlib.h>
49 #include <stdio.h>
50 #include <getopt.h>
51 #include <string.h>
52 #include <mntent.h>
53 #include <errno.h>
54 #include <pwd.h>
55 #include <grp.h>
56 #include <sys/types.h>
57 #include <sys/stat.h>
58 #include <fcntl.h>
59 #include <dirent.h>
60 #include <time.h>
61 #include <ctype.h>
62 #ifdef HAVE_SYS_QUOTA_H
63 # include <sys/quota.h>
64 #endif
65
66 /* For dirname() */
67 #include <libgen.h>
68
69 #include <lnet/api-support.h>
70 #include <lnet/lnetctl.h>
71
72 #include <liblustre.h>
73 #include <lustre/lustre_idl.h>
74 #include <lustre/liblustreapi.h>
75 #include <lustre/lustre_user.h>
76
77 #include <libcfs/libcfsutil.h>
78 #include "obdctl.h"
79
80 unsigned int libcfs_subsystem_debug = 0;
81
82 /* all functions */
83 static int lfs_setstripe(int argc, char **argv);
84 static int lfs_find(int argc, char **argv);
85 static int lfs_getstripe(int argc, char **argv);
86 static int lfs_osts(int argc, char **argv);
87 static int lfs_df(int argc, char **argv);
88 static int lfs_check(int argc, char **argv);
89 static int lfs_catinfo(int argc, char **argv);
90 #ifdef HAVE_SYS_QUOTA_H
91 static int lfs_quotachown(int argc, char **argv);
92 static int lfs_quotacheck(int argc, char **argv);
93 static int lfs_quotaon(int argc, char **argv);
94 static int lfs_quotaoff(int argc, char **argv);
95 static int lfs_setquota(int argc, char **argv);
96 static int lfs_quota(int argc, char **argv);
97 static int lfs_quotainv(int argc, char **argv);
98 #endif
99 static int lfs_flushctx(int argc, char **argv);
100 static int lfs_join(int argc, char **argv);
101 static int lfs_lsetfacl(int argc, char **argv);
102 static int lfs_lgetfacl(int argc, char **argv);
103 static int lfs_rsetfacl(int argc, char **argv);
104 static int lfs_rgetfacl(int argc, char **argv);
105 static int lfs_cp(int argc, char **argv);
106 static int lfs_ls(int argc, char **argv);
107 static int lfs_poollist(int argc, char **argv);
108 static int lfs_changelog(int argc, char **argv);
109 static int lfs_changelog_clear(int argc, char **argv);
110 static int lfs_fid2path(int argc, char **argv);
111 static int lfs_path2fid(int argc, char **argv);
112
113 /* all avaialable commands */
114 command_t cmdlist[] = {
115         {"setstripe", lfs_setstripe, 0,
116          "Create a new file with a specific striping pattern or\n"
117          "set the default striping pattern on an existing directory or\n"
118          "delete the default striping pattern from an existing directory\n"
119          "usage: setstripe [--size|-s stripe_size] [--offset|-o start_ost]\n"
120          "                 [--count|-c stripe_count] [--pool|-p <pool>]\n"
121          "                 <dir|filename>\n"
122          "       or \n"
123          "       setstripe -d <dir>   (to delete default striping)\n"
124          "\tstripe_size:  Number of bytes on each OST (0 filesystem default)\n"
125          "\t              Can be specified with k, m or g (in KB, MB and GB\n"
126          "\t              respectively)\n"
127          "\tstart_ost:    OST index of first stripe (-1 filesystem default)\n"
128          "\tstripe_count: Number of OSTs to stripe over (0 default, -1 all)\n"
129          "\tpool:         Name of OST pool"},
130         {"getstripe", lfs_getstripe, 0,
131          "To list the striping info for a given file or files in a\n"
132          "directory or recursively for all files in a directory tree.\n"
133          "usage: getstripe [--obd|-O <uuid>] [--quiet | -q] [--verbose | -v]\n"
134          "                 [--count | -c ] [--size | -s ] [--index | -i ]\n"
135          "                 [--offset | -o ] [--pool | -p ]\n"
136          "                 [--recursive | -r] <dir|file> ..."},
137         {"pool_list", lfs_poollist, 0,
138          "List pools or pool OSTs\n"
139          "usage: pool_list <fsname>[.<pool>] | <pathname>\n"},
140         {"find", lfs_find, 0,
141          "To find files that match given parameters recursively in a directory tree.\n"
142          "usage: find <dir|file> ... \n"
143          "     [[!] --atime|-A [+-]N] [[!] --mtime|-M [+-]N] [[!] --ctime|-C [+-]N]\n"
144          "     [--maxdepth|-D N] [[!] --name|-n <pattern>] [--print0|-P]\n"
145          "     [--print|-p] [--obd|-O <uuid[s]>] [[!] --size|-s [+-]N[bkMGTP]]\n"
146          "     [[!] --type|-t <filetype>] [[!] --gid|-g|--group|-G <gid>|<gname>]\n"
147          "     [[!] --uid|-u|--user|-U <uid>|<uname>]\n"
148          "     [[!] --pool <pool>]\n"
149          "\t !: used before an option indicates 'NOT' the requested attribute\n"
150          "\t -: used before an value indicates 'AT MOST' the requested value\n"
151          "\t +: used before an option indicates 'AT LEAST' the requested value\n"},
152         {"check", lfs_check, 0,
153          "Display the status of MDS or OSTs (as specified in the command)\n"
154          "or all the servers (MDS and OSTs).\n"
155          "usage: check <osts|mds|servers>"},
156         {"catinfo", lfs_catinfo, 0,
157          "Show information of specified type logs.\n"
158          "usage: catinfo {keyword} [node name]\n"
159          "\tkeywords are one of followings: config, deletions.\n"
160          "\tnode name must be provided when use keyword config."},
161         {"join", lfs_join, 0,
162          "join two lustre files into one - join A, B, will be like cat B >> A & del B\n"
163          "usage: join <filename_A> <filename_B>\n"},
164         {"osts", lfs_osts, 0, "osts"},
165         {"df", lfs_df, 0,
166          "report filesystem disk space usage or inodes usage"
167          "of each MDS and all OSDs or a batch belonging to a specific pool .\n"
168          "Usage: df [-i] [-h] [--pool|-p <fsname>[.<pool>] [path]"},
169 #ifdef HAVE_SYS_QUOTA_H
170         {"quotachown",lfs_quotachown, 0,
171          "Change files' owner or group on the specified filesystem.\n"
172          "usage: quotachown [-i] <filesystem>\n"
173          "\t-i: ignore error if file is not exist\n"},
174         {"quotacheck", lfs_quotacheck, 0,
175          "Scan the specified filesystem for disk usage, and create,\n"
176          "or update quota files.\n"
177          "usage: quotacheck [ -ug ] <filesystem>"},
178         {"quotaon", lfs_quotaon, 0, "Turn filesystem quotas on.\n"
179          "usage: quotaon [ -ugf ] <filesystem>"},
180         {"quotaoff", lfs_quotaoff, 0, "Turn filesystem quotas off.\n"
181          "usage: quotaoff [ -ug ] <filesystem>"},
182         {"setquota", lfs_setquota, 0, "Set filesystem quotas.\n"
183          "usage: setquota <-u|-g> <uname>|<uid>|<gname>|<gid>\n"
184          "                -b <block-softlimit> -B <block-hardlimit>\n"
185          "                -i <inode-softlimit> -I <inode-hardlimit> <filesystem>\n"
186          "       setquota -t <-u|-g> <block-grace> <inode-grace> <filesystem>\n"
187          "       setquota <-u|--user|-g|--group> <uname>|<uid>|<gname>|<gid>\n"
188          "                [--block-softlimit <block-softlimit>]\n"
189          "                [--block-hardlimit <block-hardlimit>]\n"
190          "                [--inode-softlimit <inode-softlimit>]\n"
191          "                [--inode-hardlimit <inode-hardlimit>] <filesystem>\n"
192          "       setquota [-t] <-u|--user|-g|--group>\n"
193          "                [--block-grace <block-grace>]\n"
194          "                [--inode-grace <inode-grace>] <filesystem>\n"
195          "       -b can be used instead of --block-softlimit/--block-grace\n"
196          "       -B can be used instead of --block-hardlimit\n"
197          "       -i can be used instead of --inode-softlimit/--inode-grace\n"
198          "       -I can be used instead of --inode-hardlimit"},
199         {"quota", lfs_quota, 0, "Display disk usage and limits.\n"
200          "usage: quota [-v] [-o obd_uuid|-i mdt_idx|-I ost_idx]\n" 
201          "             [<-u|-g> <uname>|<uid>|<gname>|<gid>] <filesystem>\n"
202          "       quota [-o obd_uuid|-i mdt_idx|-I ost_idx] -t <-u|-g> <filesystem>"},
203         {"quotainv", lfs_quotainv, 0, "Invalidate quota data.\n"
204          "usage: quotainv [-u|-g] <filesystem>"},
205 #endif
206         {"flushctx", lfs_flushctx, 0, "Flush security context for current user.\n"
207          "usage: flushctx [-k] [mountpoint...]"},
208         {"lsetfacl", lfs_lsetfacl, 0,
209          "Remote user setfacl for user/group on the same remote client.\n"
210          "usage: lsetfacl [-bkndRLPvh] [{-m|-x} acl_spec] [{-M|-X} acl_file] file ..."},
211         {"lgetfacl", lfs_lgetfacl, 0,
212          "Remote user getfacl for user/group on the same remote client.\n"
213          "usage: lgetfacl [-dRLPvh] file ..."},
214         {"rsetfacl", lfs_rsetfacl, 0,
215          "Remote user setfacl for user/group on other clients.\n"
216          "usage: rsetfacl [-bkndRLPvh] [{-m|-x} acl_spec] [{-M|-X} acl_file] file ..."},
217         {"rgetfacl", lfs_rgetfacl, 0,
218          "Remote user getfacl for user/group on other clients.\n"
219          "usage: rgetfacl [-dRLPvh] file ..."},
220         {"cp", lfs_cp, 0,
221          "Remote user copy files and directories.\n"
222          "usage: cp [OPTION]... [-T] SOURCE DEST\n\tcp [OPTION]... SOURCE... DIRECTORY\n\tcp [OPTION]... -t DIRECTORY SOURCE..."},
223         {"ls", lfs_ls, 0,
224          "Remote user list directory contents.\n"
225          "usage: ls [OPTION]... [FILE]..."},
226         {"changelog", lfs_changelog, 0,
227          "Show the metadata changes on an MDT."
228          "\nusage: changelog <mdtname> [startrec [endrec]]"},
229         {"changelog_clear", lfs_changelog_clear, 0,
230          "Indicate that old changelog records up to <endrec> are no longer of "
231          "interest to consumer <id>, allowing the system to free up space.\n"
232          "An <endrec> of 0 means all records.\n"
233          "usage: changelog_clear <mdtname> <id> <endrec>"},
234         {"fid2path", lfs_fid2path, 0,
235          "Resolve the full path to a given FID. For a specific hardlink "
236          "specify link number <linkno>.\n"
237          /* "For a historical name, specify changelog record <recno>.\n" */
238          "usage: fid2path <fsname|rootpath> <fid> [--link <linkno>]"
239                 /*[--rec <recno>]*/},
240         {"path2fid", lfs_path2fid, 0, "Display the fid for a given path.\n"
241          "usage: path2fid <path>"},
242         {"help", Parser_help, 0, "help"},
243         {"exit", Parser_quit, 0, "quit"},
244         {"quit", Parser_quit, 0, "quit"},
245         { 0, 0, 0, NULL }
246 };
247
248 static int isnumber(const char *str)
249 {
250         const char *ptr;
251
252         if (str[0] != '-' && !isdigit(str[0]))
253                 return 0;
254
255         for (ptr = str + 1; *ptr != '\0'; ptr++) {
256                 if (!isdigit(*ptr))
257                         return 0;
258         }
259
260         return 1;
261 }
262
263 /* functions */
264 static int lfs_setstripe(int argc, char **argv)
265 {
266         char *fname;
267         int result;
268         unsigned long long st_size;
269         int  st_offset, st_count;
270         char *end;
271         int c;
272         int delete = 0;
273         char *stripe_size_arg = NULL;
274         char *stripe_off_arg = NULL;
275         char *stripe_count_arg = NULL;
276         char *pool_name_arg = NULL;
277         unsigned long long size_units;
278
279         struct option long_opts[] = {
280                 {"size",        required_argument, 0, 's'},
281                 {"count",       required_argument, 0, 'c'},
282                 {"index",       required_argument, 0, 'i'},
283                 {"offset",      required_argument, 0, 'o'},
284                 {"pool",        required_argument, 0, 'p'},
285                 {"delete",      no_argument,       0, 'd'},
286                 {0, 0, 0, 0}
287         };
288
289         st_size = 0;
290         st_offset = -1;
291         st_count = 0;
292
293 #if LUSTRE_VERSION < OBD_OCD_VERSION(2,1,0,0)
294         if (argc == 5 && argv[1][0] != '-' &&
295             isnumber(argv[2]) && isnumber(argv[3]) && isnumber(argv[4])) {
296                 fprintf(stderr, "warning: deprecated usage of setstripe "
297                         "positional parameters.  Use -c, -i, -s instead.\n");
298                 /* for compatibility with the existing positional parameter
299                  * usage */
300                 fname = argv[1];
301                 stripe_size_arg = argv[2];
302                 stripe_off_arg = argv[3];
303                 stripe_count_arg = argv[4];
304                 optind = 4;
305         } else
306 #else
307 #warning "remove obsolete positional parameter code"
308 #endif
309         {
310                 optind = 0;
311                 while ((c = getopt_long(argc, argv, "c:di:o:s:p:",
312                                         long_opts, NULL)) >= 0) {
313                         switch (c) {
314                         case 0:
315                                 /* Long options. */
316                                 break;
317                         case 'c':
318                                 stripe_count_arg = optarg;
319                                 break;
320                         case 'd':
321                                 /* delete the default striping pattern */
322                                 delete = 1;
323                                 break;
324                         case 'i':
325                         case 'o':
326                                 stripe_off_arg = optarg;
327                                 break;
328                         case 's':
329                                 stripe_size_arg = optarg;
330                                 break;
331                         case 'p':
332                                 pool_name_arg = optarg;
333                                 break;
334                         case '?':
335                                 return CMD_HELP;
336                         default:
337                                 fprintf(stderr, "error: %s: option '%s' "
338                                                 "unrecognized\n",
339                                                 argv[0], argv[optind - 1]);
340                                 return CMD_HELP;
341                         }
342                 }
343
344                 fname = argv[optind];
345
346                 if (delete &&
347                     (stripe_size_arg != NULL || stripe_off_arg != NULL ||
348                      stripe_count_arg != NULL || pool_name_arg != NULL)) {
349                         fprintf(stderr, "error: %s: cannot specify -d with "
350                                         "-s, -c -o or -p options\n",
351                                         argv[0]);
352                         return CMD_HELP;
353                 }
354         }
355
356         if (optind == argc) {
357                 fprintf(stderr, "error: %s: missing filename|dirname\n",
358                         argv[0]);
359                 return CMD_HELP;
360         }
361
362         /* get the stripe size */
363         if (stripe_size_arg != NULL) {
364                 result = parse_size(stripe_size_arg, &st_size, &size_units, 0);
365                 if (result) {
366                         fprintf(stderr, "error: %s: bad size '%s'\n",
367                                 argv[0], stripe_size_arg);
368                         return result;
369                 }
370         }
371         /* get the stripe offset */
372         if (stripe_off_arg != NULL) {
373                 st_offset = strtoul(stripe_off_arg, &end, 0);
374                 if (*end != '\0') {
375                         fprintf(stderr, "error: %s: bad stripe offset '%s'\n",
376                                 argv[0], stripe_off_arg);
377                         return CMD_HELP;
378                 }
379         }
380         /* get the stripe count */
381         if (stripe_count_arg != NULL) {
382                 st_count = strtoul(stripe_count_arg, &end, 0);
383                 if (*end != '\0') {
384                         fprintf(stderr, "error: %s: bad stripe count '%s'\n",
385                                 argv[0], stripe_count_arg);
386                         return CMD_HELP;
387                 }
388         }
389
390         do {
391                 result = llapi_file_create_pool(fname, st_size, st_offset,
392                                                 st_count, 0, pool_name_arg);
393                 if (result) {
394                         fprintf(stderr,"error: %s: create stripe file '%s' "
395                                 "failed\n", argv[0], fname);
396                         break;
397                 }
398                 fname = argv[++optind];
399         } while (fname != NULL);
400
401         return result;
402 }
403
404 static int lfs_poollist(int argc, char **argv)
405 {
406         if (argc != 2)
407                 return CMD_HELP;
408
409         return llapi_poollist(argv[1]);
410 }
411
412 static int set_time(time_t *time, time_t *set, char *str)
413 {
414         time_t t;
415         int res = 0;
416
417         if (str[0] == '+')
418                 res = 1;
419         else if (str[0] == '-')
420                 res = -1;
421
422         if (res)
423                 str++;
424
425         t = strtol(str, NULL, 0);
426         if (*time < t * 24 * 60 * 60) {
427                 if (res)
428                         str--;
429                 fprintf(stderr, "Wrong time '%s' is specified.\n", str);
430                 return INT_MAX;
431         }
432
433         *set = *time - t * 24 * 60 * 60;
434         return res;
435 }
436
437 #define USER 0
438 #define GROUP 1
439
440 static int name2id(unsigned int *id, char *name, int type)
441 {
442         if (type == USER) {
443                 struct passwd *entry;
444
445                 if (!(entry = getpwnam(name))) {
446                         if (!errno)
447                                 errno = ENOENT;
448                         return -1;
449                 }
450
451                 *id = entry->pw_uid;
452         } else {
453                 struct group *entry;
454
455                 if (!(entry = getgrnam(name))) {
456                         if (!errno)
457                                 errno = ENOENT;
458                         return -1;
459                 }
460
461                 *id = entry->gr_gid;
462         }
463
464         return 0;
465 }
466
467 static int id2name(char **name, unsigned int id, int type)
468 {
469         if (type == USER) {
470                 struct passwd *entry;
471
472                 if (!(entry = getpwuid(id))) {
473                         if (!errno)
474                                 errno = ENOENT;
475                         return -1;
476                 }
477
478                 *name = entry->pw_name;
479         } else {
480                 struct group *entry;
481
482                 if (!(entry = getgrgid(id))) {
483                         if (!errno)
484                                 errno = ENOENT;
485                         return -1;
486                 }
487
488                 *name = entry->gr_name;
489         }
490
491         return 0;
492 }
493
494 #define FIND_POOL_OPT 3
495 static int lfs_find(int argc, char **argv)
496 {
497         int new_fashion = 1;
498         int c, ret;
499         time_t t;
500         struct find_param param = { .maxdepth = -1 };
501         char str[1024];
502         struct option long_opts[] = {
503                 /* New find options. */
504                 {"atime",     required_argument, 0, 'A'},
505                 {"ctime",     required_argument, 0, 'C'},
506                 {"mtime",     required_argument, 0, 'M'},
507                 {"maxdepth",  required_argument, 0, 'D'},
508                 {"gid",       required_argument, 0, 'g'},
509                 {"group",     required_argument, 0, 'G'},
510                 {"uid",       required_argument, 0, 'u'},
511                 {"user",      required_argument, 0, 'U'},
512                 {"name",      required_argument, 0, 'n'},
513                 /* no short option for pool, p/P already used */
514                 {"pool",      required_argument, 0, FIND_POOL_OPT},
515                 /* --obd is considered as a new option. */
516                 {"obd",       required_argument, 0, 'O'},
517                 {"ost",       required_argument, 0, 'O'},
518                 {"print",     no_argument,       0, 'P'},
519                 {"print0",    no_argument,       0, 'p'},
520                 /* Old find options. */
521                 {"quiet",     no_argument,       0, 'q'},
522                 {"recursive", no_argument,       0, 'r'},
523                 {"size",      required_argument, 0, 's'},
524                 {"type",      required_argument, 0, 't'},
525                 {"verbose",   no_argument,       0, 'v'},
526                 {0, 0, 0, 0}
527         };
528         int pathstart = -1;
529         int pathend = -1;
530         int neg_opt = 0;
531         time_t *xtime;
532         int *xsign;
533         int isoption;
534         char *endptr;
535
536         time(&t);
537
538         optind = 0;
539         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
540         while ((c = getopt_long_only(argc,argv,"-A:C:D:g:G:M:n:PpO:qrs:t:u:U:v",
541                                      long_opts, NULL)) >= 0) {
542                 xtime = NULL;
543                 xsign = NULL;
544                 if (neg_opt)
545                         --neg_opt;
546                 /* '!' is part of option */
547                 /* when getopt_long_only() finds a string which is not
548                  * an option nor a known option argument it returns 1
549                  * in that case if we already have found pathstart and pathend
550                  * (i.e. we have the list of pathnames),
551                  * the only supported value is "!"
552                  */
553                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
554                 if (!isoption && pathend != -1) {
555                         fprintf(stderr, "err: %s: filename|dirname must either "
556                                         "precede options or follow options\n",
557                                         argv[0]);
558                         return CMD_HELP;
559                 }
560                 if (!isoption && pathstart == -1)
561                         pathstart = optind - 1;
562                 if (isoption && pathstart != -1 && pathend == -1) {
563                         pathend = optind - 2;
564                         if ((c == 1 && strcmp(optarg, "!") == 0) ||
565                             c == 'P' || c == 'p' || c == 'O' ||
566                             c == 'q' || c == 'r' || c == 'v')
567                                 pathend = optind - 1;
568                 }
569                 switch (c) {
570                 case 0:
571                         /* Long options. */
572                         break;
573                 case 1:
574                         /* unknown; opt is "!" or path component,
575                          * checking done above.
576                          */
577                         if (strcmp(optarg, "!") == 0)
578                                 neg_opt = 2;
579                         break;
580                 case 'A':
581                         xtime = &param.atime;
582                         xsign = &param.asign;
583                 case 'C':
584                         if (c == 'C') {
585                                 xtime = &param.ctime;
586                                 xsign = &param.csign;
587                         }
588                 case 'M':
589                         if (c == 'M') {
590                                 xtime = &param.mtime;
591                                 xsign = &param.msign;
592                         }
593                         new_fashion = 1;
594                         if (neg_opt) {
595                                 if (optarg[0] == '-')
596                                         optarg[0] = '+';
597                                 else if (optarg[0] == '+')
598                                         optarg[0] = '-';
599                                 else {
600                                         str[0] = '-';
601                                         str[1] = '\0';
602                                         strcat(str, optarg);
603                                         optarg = str;
604                                 }
605                         }
606                         ret = set_time(&t, xtime, optarg);
607                         if (ret == INT_MAX)
608                                 return -1;
609                         if (ret)
610                                 *xsign = ret;
611                         break;
612                 case 'D':
613                         new_fashion = 1;
614                         param.maxdepth = strtol(optarg, 0, 0);
615                         break;
616                 case 'g':
617                 case 'G':
618                         new_fashion = 1;
619                         ret = name2id(&param.gid, optarg, GROUP);
620                         if (ret) {
621                                 param.gid = strtoul(optarg, &endptr, 10);
622                                 if (*endptr != '\0') {
623                                         fprintf(stderr, "Group/GID: %s cannot "
624                                                 "be found.\n", optarg);
625                                         return -1;
626                                 }
627                         }           
628                         param.exclude_gid = !!neg_opt;
629                         param.check_gid = 1;
630                         break;
631                 case 'u':
632                 case 'U':
633                         new_fashion = 1;
634                         ret = name2id(&param.uid, optarg, USER);
635                         if (ret) {
636                                 param.uid = strtoul(optarg, &endptr, 10);
637                                 if (*endptr != '\0') {
638                                         fprintf(stderr, "User/UID: %s cannot "
639                                                 "be found.\n", optarg);
640                                         return -1;
641                                 }
642                         }
643                         param.exclude_uid = !!neg_opt;
644                         param.check_uid = 1;
645                         break;
646                 case FIND_POOL_OPT:
647                         new_fashion = 1;
648                         if (strlen(optarg) > LOV_MAXPOOLNAME) {
649                                 fprintf(stderr,
650                                         "Pool name %s is too long"
651                                         " (max is %d)\n", optarg,
652                                         LOV_MAXPOOLNAME);
653                                 return -1;
654                         }
655                         /* we do check for empty pool because empty pool
656                          * is used to find V1 lov attributes */
657                         strncpy(param.poolname, optarg, LOV_MAXPOOLNAME);
658                         param.poolname[LOV_MAXPOOLNAME] = '\0';
659                         param.exclude_pool = !!neg_opt;
660                         param.check_pool = 1;
661                         break;
662                 case 'n':
663                         new_fashion = 1;
664                         param.pattern = (char *)optarg;
665                         param.exclude_pattern = !!neg_opt;
666                         break;
667                 case 'O': {
668                         char *buf, *token, *next, *p;
669                         int len;
670
671                         len = strlen((char *)optarg);
672                         buf = malloc(len+1);
673                         if (buf == NULL)
674                                 return -ENOMEM;
675                         strcpy(buf, (char *)optarg);
676
677                         if (param.num_alloc_obds == 0) {
678                                 param.obduuid = malloc(FIND_MAX_OSTS *
679                                                        sizeof(struct obd_uuid));
680                                 if (param.obduuid == NULL)
681                                         return -ENOMEM;
682                                 param.num_alloc_obds = INIT_ALLOC_NUM_OSTS;
683                         }
684
685                         for (token = buf; token && *token; token = next) {
686                                 p = strchr(token, ',');
687                                 next = 0;
688                                 if (p) {
689                                         *p = 0;
690                                         next = p+1;
691                                 }
692                                 strcpy((char *)&param.obduuid[param.num_obds++].uuid,
693                                        token);
694                         }
695
696                         if (buf)
697                                 free(buf);
698                         break;
699                 }
700                 case 'p':
701                         new_fashion = 1;
702                         param.zeroend = 1;
703                         break;
704                 case 'P':
705                         break;
706                 case 'q':
707                         new_fashion = 0;
708                         param.quiet++;
709                         param.verbose = 0;
710                         break;
711                 case 'r':
712                         new_fashion = 0;
713                         param.recursive = 1;
714                         break;
715                 case 't':
716                         param.exclude_type = !!neg_opt;
717                         switch(optarg[0]) {
718                         case 'b': param.type = S_IFBLK; break;
719                         case 'c': param.type = S_IFCHR; break;
720                         case 'd': param.type = S_IFDIR; break;
721                         case 'f': param.type = S_IFREG; break;
722                         case 'l': param.type = S_IFLNK; break;
723                         case 'p': param.type = S_IFIFO; break;
724                         case 's': param.type = S_IFSOCK; break;
725 #ifdef S_IFDOOR /* Solaris only */
726                         case 'D': param.type = S_IFDOOR; break;
727 #endif
728                         default: fprintf(stderr, "error: %s: bad type '%s'\n",
729                                          argv[0], optarg);
730                                  return CMD_HELP;
731                         };
732                         break;
733                 case 's':
734                         if (neg_opt) {
735                                 if (optarg[0] == '-')
736                                         optarg[0] = '+';
737                                 else if (optarg[0] == '+')
738                                         optarg[0] = '-';
739                                 else {
740                                         str[0] = '-';
741                                         str[1] = '\0';
742                                         strcat(str, optarg);
743                                         optarg = str;
744                                 }
745                         }
746                         if (optarg[0] == '+')
747                                 param.size_sign = -1;
748                         else if (optarg[0] == '-')
749                                 param.size_sign = +1;
750
751                         if (param.size_sign)
752                                 optarg++;
753                         ret = parse_size(optarg, &param.size,
754                                          &param.size_units, 0);
755                         if (ret) {
756                                 fprintf(stderr,"error: bad size '%s'\n",
757                                         optarg);
758                                 return ret;
759                         }
760                         break;
761                 case 'v':
762                         new_fashion = 0;
763                         param.verbose++;
764                         param.quiet = 0;
765                         break;
766                 case '?':
767                         return CMD_HELP;
768                 default:
769                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
770                                 argv[0], argv[optind - 1]);
771                         return CMD_HELP;
772                 };
773         }
774
775         if (pathstart == -1) {
776                 fprintf(stderr, "error: %s: no filename|pathname\n",
777                         argv[0]);
778                 return CMD_HELP;
779         } else if (pathend == -1) {
780                 /* no options */
781                 pathend = argc;
782         }
783
784         if (new_fashion) {
785                 param.quiet = 1;
786         } else {
787                 static int deprecated_warning;
788                 if (!deprecated_warning) {
789                         fprintf(stderr, "lfs find: -q, -r, -v options "
790                                 "deprecated.  Use 'lfs getstripe' instead.\n");
791                         deprecated_warning = 1;
792                 }
793                 if (!param.recursive && param.maxdepth == -1)
794                         param.maxdepth = 1;
795         }
796
797         do {
798                 if (new_fashion)
799                         ret = llapi_find(argv[pathstart], &param);
800                 else
801                         ret = llapi_getstripe(argv[pathstart], &param);
802         } while (++pathstart < pathend && !ret);
803
804         if (ret)
805                 fprintf(stderr, "error: %s failed for %s.\n",
806                         argv[0], argv[optind - 1]);
807
808         if (param.obduuid && param.num_alloc_obds)
809                 free(param.obduuid);
810
811         return ret;
812 }
813
814 static int lfs_getstripe(int argc, char **argv)
815 {
816         struct option long_opts[] = {
817                 {"obd", 1, 0, 'O'},
818                 {"quiet", 0, 0, 'q'},
819                 {"recursive", 0, 0, 'r'},
820                 {"count", 0, 0, 'c'},
821                 {"size", 0, 0, 's'},
822                 {"index", 0, 0, 'i'},
823                 {"offset", 0, 0, 'o'},
824                 {"pool", 0, 0, 'p'},
825                 {"verbose", 0, 0, 'v'},
826                 {0, 0, 0, 0}
827         };
828         char short_opts[] = "hO:qrvcsiop";
829         int c, rc;
830         struct find_param param = { 0 };
831
832         optind = 0;
833         while ((c = getopt_long(argc, argv, short_opts,
834                                 long_opts, NULL)) != -1) {
835                 switch (c) {
836                 case 'O':
837                         if (param.obduuid) {
838                                 fprintf(stderr,
839                                         "error: %s: only one obduuid allowed",
840                                         argv[0]);
841                                 return CMD_HELP;
842                         }
843                         param.obduuid = (struct obd_uuid *)optarg;
844                         break;
845                 case 'q':
846                         param.quiet++;
847                         break;
848                 case 'r':
849                         param.recursive = 1;
850                         break;
851                 case 'v':
852                         param.verbose = VERBOSE_ALL | VERBOSE_DETAIL;
853                         param.quiet = 0;
854                         break;
855                 case 'c':
856                         param.verbose |= VERBOSE_COUNT;
857                         break;
858                 case 's':
859                         param.verbose |= VERBOSE_SIZE;
860                         break;
861                 case 'i':
862                 case 'o':
863                         param.verbose |= VERBOSE_OFFSET;
864                         break;
865                 case 'p':
866                         param.verbose |= VERBOSE_POOL;
867                         break;
868                 case '?':
869                         return CMD_HELP;
870                 default:
871                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
872                                 argv[0], argv[optind - 1]);
873                         return CMD_HELP;
874                 }
875         }
876
877         if (optind >= argc)
878                 return CMD_HELP;
879
880         param.maxdepth = param.recursive ? -1 : 1;
881
882         do {
883                 rc = llapi_getstripe(argv[optind], &param);
884         } while (++optind < argc && !rc);
885
886         if (rc)
887                 fprintf(stderr, "error: %s failed for %s.\n",
888                         argv[0], argv[optind - 1]);
889         return rc;
890 }
891
892 static int lfs_osts(int argc, char **argv)
893 {
894         char mntdir[PATH_MAX] = {'\0'};
895         struct find_param param;
896         int index = 0, rc=0;
897
898         if (argc != 1)
899                 return CMD_HELP;
900
901         while (llapi_search_mounts(NULL, index++, mntdir, NULL) == 0) {
902                 memset(&param, 0, sizeof(param));
903                 rc = llapi_getstripe(mntdir, &param);
904                 if (rc) {
905                         fprintf(stderr, "error: %s: failed on %s\n",
906                                 argv[0], mntdir);
907                 }
908                 memset(mntdir, 0, PATH_MAX);
909         }
910
911         return rc;
912 }
913
914 #define COOK(value)                                                     \
915 ({                                                                      \
916         int radix = 0;                                                  \
917         while (value > 1024) {                                          \
918                 value /= 1024;                                          \
919                 radix++;                                                \
920         }                                                               \
921         radix;                                                          \
922 })
923 #define UUF     "%-20s"
924 #define CSF     "%9s"
925 #define CDF     "%9llu"
926 #define HSF     "%8s"
927 #define HDF     "%6.1f"
928 #define RSF     "%5s"
929 #define RDF     "%4d%%"
930
931 static int showdf(char *mntdir, struct obd_statfs *stat,
932                   char *uuid, int ishow, int cooked,
933                   char *type, int index, int rc)
934 {
935         long long avail, used, total;
936         double ratio = 0;
937         char *suffix = "KMGTPEZY";
938         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
939         char tbuf[20], ubuf[20], abuf[20], rbuf[20];
940
941         if (!uuid || !stat)
942                 return -EINVAL;
943
944         switch (rc) {
945         case 0:
946                 if (ishow) {
947                         avail = stat->os_ffree;
948                         used = stat->os_files - stat->os_ffree;
949                         total = stat->os_files;
950                 } else {
951                         int shift = cooked ? 0 : 10;
952
953                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
954                         used  = ((stat->os_blocks - stat->os_bfree) *
955                                  stat->os_bsize) >> shift;
956                         total = (stat->os_blocks * stat->os_bsize) >> shift;
957                 }
958
959                 if (total > 0)
960                         ratio = (double)used / (double)total;
961
962                 if (cooked) {
963                         int i;
964                         double cook_val;
965
966                         cook_val = (double)total;
967                         i = COOK(cook_val);
968                         if (i > 0)
969                                 sprintf(tbuf, HDF"%c", cook_val, suffix[i - 1]);
970                         else
971                                 sprintf(tbuf, CDF, total);
972
973                         cook_val = (double)used;
974                         i = COOK(cook_val);
975                         if (i > 0)
976                                 sprintf(ubuf, HDF"%c", cook_val, suffix[i - 1]);
977                         else
978                                 sprintf(ubuf, CDF, used);
979
980                         cook_val = (double)avail;
981                         i = COOK(cook_val);
982                         if (i > 0)
983                                 sprintf(abuf, HDF"%c", cook_val, suffix[i - 1]);
984                         else
985                                 sprintf(abuf, CDF, avail);
986                 } else {
987                         sprintf(tbuf, CDF, total);
988                         sprintf(ubuf, CDF, used);
989                         sprintf(abuf, CDF, avail);
990                 }
991
992                 sprintf(rbuf, RDF, (int)(ratio * 100));
993                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
994                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
995                 if (type)
996                         printf("[%s:%d]\n", type, index);
997                 else
998                         printf("\n");
999
1000                 break;
1001         case -ENODATA:
1002                 printf(UUF": inactive device\n", uuid);
1003                 break;
1004         default:
1005                 printf(UUF": %s\n", uuid, strerror(-rc));
1006                 break;
1007         }
1008
1009         return 0;
1010 }
1011
1012 static int mntdf(char *mntdir, char *fsname, char *pool, int ishow, int cooked)
1013 {
1014         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
1015         struct obd_uuid uuid_buf;
1016         char *poolname = NULL;
1017         __u32 index;
1018         int rc;
1019
1020         if (pool) {
1021                 poolname = strchr(pool, '.');
1022                 if (poolname != NULL) {
1023                         if (strncmp(fsname, pool, strlen(fsname))) {
1024                                 fprintf(stderr, "filesystem name incorrect\n");
1025                                 return -ENODEV;
1026                         }
1027                         poolname++;
1028                 } else
1029                         poolname = pool;
1030         }
1031
1032         if (ishow)
1033                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
1034                        "UUID", "Inodes", "IUsed", "IFree",
1035                        "IUse%", "Mounted on");
1036         else
1037                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
1038                        "UUID", cooked ? "bytes" : "1K-blocks",
1039                        "Used", "Available", "Use%", "Mounted on");
1040
1041         for (index = 0; ; index++) {
1042                 memset(&stat_buf, 0, sizeof(struct obd_statfs));
1043                 memset(&uuid_buf, 0, sizeof(struct obd_uuid));
1044                 rc = llapi_obd_statfs(mntdir, LL_STATFS_MDC, index,
1045                                       &stat_buf, &uuid_buf);
1046                 if (rc == -ENODEV)
1047                         break;
1048
1049                 if (rc == -EAGAIN)
1050                         continue;
1051
1052                 if (rc == -ENOTCONN || rc == -ETIMEDOUT || rc == -EIO ||
1053                     rc == -ENODATA || rc == 0) {
1054                         showdf(mntdir, &stat_buf, obd_uuid2str(&uuid_buf),
1055                                ishow, cooked, "MDT", index, rc);
1056                 } else {
1057                         fprintf(stderr,
1058                                 "error: llapi_obd_statfs(%s): %s (%d)\n",
1059                                 obd_uuid2str(&uuid_buf), strerror(-rc), rc);
1060                         return rc;
1061                 }
1062                 if (rc == 0) {
1063                         sum.os_ffree += stat_buf.os_ffree;
1064                         sum.os_files += stat_buf.os_files;
1065                 }
1066         }
1067
1068         for (index = 0; ; index++) {
1069                 memset(&stat_buf, 0, sizeof(struct obd_statfs));
1070                 memset(&uuid_buf, 0, sizeof(struct obd_uuid));
1071                 rc = llapi_obd_statfs(mntdir, LL_STATFS_LOV, index,
1072                                       &stat_buf, &uuid_buf);
1073                 if (rc == -ENODEV)
1074                         break;
1075
1076                 if (rc == -EAGAIN)
1077                         continue;
1078
1079                 if (llapi_search_ost(fsname, poolname,
1080                                      obd_uuid2str(&uuid_buf)) != 1)
1081                         continue;
1082
1083                 if (rc == -ENOTCONN || rc == -ETIMEDOUT || rc == -EIO ||
1084                     rc == -ENODATA || rc == 0) {
1085                         showdf(mntdir, &stat_buf, obd_uuid2str(&uuid_buf),
1086                                ishow, cooked, "OST", index, rc);
1087                 } else {
1088                         fprintf(stderr,
1089                                 "error: llapi_obd_statfs failed: %s (%d)\n",
1090                                 strerror(-rc), rc);
1091                         return rc;
1092                 }
1093                 if (rc == 0) {
1094                         sum.os_blocks += stat_buf.os_blocks * stat_buf.os_bsize;
1095                         sum.os_bfree  += stat_buf.os_bfree * stat_buf.os_bsize;
1096                         sum.os_bavail += stat_buf.os_bavail * stat_buf.os_bsize;
1097                 }
1098         }
1099
1100         printf("\n");
1101         showdf(mntdir, &sum, "filesystem summary:", ishow, cooked, NULL, 0,0);
1102
1103         return 0;
1104 }
1105
1106 static int lfs_df(int argc, char **argv)
1107 {
1108         char *path = NULL;
1109         char *mntdir = NULL;
1110         int ishow = 0, cooked = 0;
1111         int c, rc = 0;
1112         char fsname[PATH_MAX], *pool_name = NULL;
1113         struct option long_opts[] = {
1114                 {"pool", required_argument, 0, 'p'},
1115                 {0, 0, 0, 0}
1116         };
1117
1118         optind = 0;
1119         while ((c = getopt_long(argc, argv, "ihp:", long_opts, NULL)) != -1) {
1120                 switch (c) {
1121                 case 'i':
1122                         ishow = 1;
1123                         break;
1124                 case 'h':
1125                         cooked = 1;
1126                         break;
1127                 case 'p':
1128                         pool_name = optarg;
1129                         break;
1130                 default:
1131                         return CMD_HELP;
1132                 }
1133         }
1134         if (optind < argc )
1135                 path = argv[optind];
1136
1137         if ((mntdir = malloc(PATH_MAX)) == NULL) {
1138                 fprintf(stderr, "error: cannot allocate %d bytes\n",
1139                         PATH_MAX);
1140                 return -ENOMEM;
1141         }
1142         memset(mntdir, 0, PATH_MAX);
1143
1144         if (path) {
1145                 char rpath[PATH_MAX] = {'\0'};
1146
1147                 if (!realpath(path, rpath)) {
1148                         rc = -errno;
1149                         fprintf(stderr, "error: invalid path '%s': %s\n",
1150                                         path, strerror(-rc));
1151                 } else {
1152                         rc = llapi_search_mounts(rpath, 0, mntdir, fsname);
1153                         if (rc == 0 && mntdir[0] != '\0') {
1154                                 rc = mntdf(mntdir, fsname, pool_name,
1155                                            ishow, cooked);
1156                                 printf("\n");
1157                         }
1158                 }
1159         } else {
1160                 int index = 0;
1161
1162                 while (llapi_search_mounts(NULL, index++, mntdir, fsname)==0) {
1163                         rc = mntdf(mntdir, fsname, pool_name,
1164                                    ishow, cooked);
1165                         if (rc)
1166                                 break;
1167                         printf("\n");
1168                 }
1169         }
1170
1171         free(mntdir);
1172         return rc;
1173 }
1174
1175 static int lfs_check(int argc, char **argv)
1176 {
1177         int rc;
1178         char mntdir[PATH_MAX] = {'\0'};
1179         int num_types = 1;
1180         char *obd_types[2];
1181         char obd_type1[4];
1182         char obd_type2[4];
1183
1184         if (argc != 2)
1185                 return CMD_HELP;
1186
1187         obd_types[0] = obd_type1;
1188         obd_types[1] = obd_type2;
1189
1190         if (strcmp(argv[1], "osts") == 0) {
1191                 strcpy(obd_types[0], "osc");
1192         } else if (strcmp(argv[1], "mds") == 0) {
1193                 strcpy(obd_types[0], "mdc");
1194         } else if (strcmp(argv[1], "servers") == 0) {
1195                 num_types = 2;
1196                 strcpy(obd_types[0], "osc");
1197                 strcpy(obd_types[1], "mdc");
1198         } else {
1199                 fprintf(stderr, "error: %s: option '%s' unrecognized\n",
1200                                 argv[0], argv[1]);
1201                         return CMD_HELP;
1202         }
1203
1204         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
1205         if (rc < 0 || mntdir[0] == '\0') {
1206                 fprintf(stderr, "No suitable Lustre mount found\n");
1207                 return rc;
1208         }
1209
1210         rc = llapi_target_iterate(num_types, obd_types,
1211                                   mntdir, llapi_ping_target);
1212
1213         if (rc)
1214                 fprintf(stderr, "error: %s: %s status failed\n",
1215                                 argv[0],argv[1]);
1216
1217         return rc;
1218
1219 }
1220
1221 static int lfs_catinfo(int argc, char **argv)
1222 {
1223         char mntdir[PATH_MAX] = {'\0'};
1224         int rc;
1225
1226         if (argc < 2 || (!strcmp(argv[1],"config") && argc < 3))
1227                 return CMD_HELP;
1228
1229         if (strcmp(argv[1], "config") && strcmp(argv[1], "deletions"))
1230                 return CMD_HELP;
1231
1232         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
1233         if (rc == 0 && mntdir[0] != '\0') {
1234                 if (argc == 3)
1235                         rc = llapi_catinfo(mntdir, argv[1], argv[2]);
1236                 else
1237                         rc = llapi_catinfo(mntdir, argv[1], NULL);
1238         } else {
1239                 fprintf(stderr, "no lustre_lite mounted.\n");
1240                 rc = -1;
1241         }
1242
1243         return rc;
1244 }
1245
1246 int lfs_join(int argc, char **argv)
1247 {
1248         char *name_head, *name_tail;
1249         int fd, rc;
1250         loff_t size;
1251
1252         if (argc != 3)
1253                 return CMD_HELP;
1254         name_head = argv[1];
1255         fd = open(name_head, O_WRONLY);
1256         if (fd < 0) {
1257                 fprintf(stderr, "Can not open name_head %s rc=%d\n",
1258                         name_head, fd);
1259                 return fd;
1260         }
1261         size = lseek(fd, 0, SEEK_END);
1262         if (size % JOIN_FILE_ALIGN) {
1263                 fprintf(stderr,"head file %s size %llu must be mutiple of %d\n",
1264                         name_head, (long long)size, JOIN_FILE_ALIGN);
1265                 rc = -EINVAL;
1266                 goto out;
1267         }
1268         name_tail = argv[2];
1269         rc = ioctl(fd, LL_IOC_JOIN, name_tail);
1270 out:
1271         close(fd);
1272         if (rc) {
1273                 fprintf(stderr, "Lustre joining files: %s, %s, failed\n",
1274                         argv[1], argv[2]);
1275         }
1276         return rc;
1277 }
1278
1279 #ifdef HAVE_SYS_QUOTA_H
1280 static int lfs_quotachown(int argc, char **argv)
1281 {
1282
1283         int c,rc;
1284         int flag = 0;
1285
1286         optind = 0;
1287         while ((c = getopt(argc, argv, "i")) != -1) {
1288                 switch (c) {
1289                 case 'i':
1290                         flag++;
1291                         break;
1292                 default:
1293                         fprintf(stderr, "error: %s: option '-%c' "
1294                                         "unrecognized\n", argv[0], c);
1295                         return CMD_HELP;
1296                 }
1297         }
1298         if (optind == argc)
1299                 return CMD_HELP;
1300         rc = llapi_quotachown(argv[optind], flag);
1301         if(rc)
1302                 fprintf(stderr,"error: change file owner/group failed.\n");
1303         return rc;
1304 }
1305
1306 static int lfs_quotacheck(int argc, char **argv)
1307 {
1308         int c, check_type = 0;
1309         char *mnt;
1310         struct if_quotacheck qchk;
1311         struct if_quotactl qctl;
1312         char *obd_type = (char *)qchk.obd_type;
1313         int rc;
1314
1315         memset(&qchk, 0, sizeof(qchk));
1316
1317         optind = 0;
1318         while ((c = getopt(argc, argv, "ug")) != -1) {
1319                 switch (c) {
1320                 case 'u':
1321                         check_type |= 0x01;
1322                         break;
1323                 case 'g':
1324                         check_type |= 0x02;
1325                         break;
1326                 default:
1327                         fprintf(stderr, "error: %s: option '-%c' "
1328                                         "unrecognized\n", argv[0], c);
1329                         return CMD_HELP;
1330                 }
1331         }
1332
1333         if (check_type)
1334                 check_type--;
1335         else    /* do quotacheck for both user & group quota by default */
1336                 check_type = 0x02;
1337
1338         if (argc == optind)
1339                 return CMD_HELP;
1340
1341         mnt = argv[optind];
1342
1343         rc = llapi_quotacheck(mnt, check_type);
1344         if (rc) {
1345                 fprintf(stderr, "quotacheck failed: %s\n", strerror(errno));
1346                 return rc;
1347         }
1348
1349         rc = llapi_poll_quotacheck(mnt, &qchk);
1350         if (rc) {
1351                 if (*obd_type)
1352                         fprintf(stderr, "%s %s ", obd_type,
1353                                 obd_uuid2str(&qchk.obd_uuid));
1354                 fprintf(stderr, "quota check failed: %s\n", strerror(errno));
1355                 return rc;
1356         }
1357
1358         memset(&qctl, 0, sizeof(qctl));
1359         qctl.qc_cmd = LUSTRE_Q_QUOTAON;
1360         qctl.qc_type = check_type;
1361         rc = llapi_quotactl(mnt, &qctl);
1362         if (rc && errno != EALREADY) {
1363                 if (*obd_type)
1364                         fprintf(stderr, "%s %s ", (char *)qctl.obd_type,
1365                                 obd_uuid2str(&qctl.obd_uuid));
1366                 fprintf(stderr, "%s turn on quota failed: %s\n",
1367                         argv[0], strerror(errno));
1368                 return rc;
1369         }
1370
1371         return 0;
1372 }
1373
1374 static int lfs_quotaon(int argc, char **argv)
1375 {
1376         int c;
1377         char *mnt;
1378         struct if_quotactl qctl;
1379         char *obd_type = (char *)qctl.obd_type;
1380         int rc;
1381
1382         memset(&qctl, 0, sizeof(qctl));
1383         qctl.qc_cmd = LUSTRE_Q_QUOTAON;
1384
1385         optind = 0;
1386         while ((c = getopt(argc, argv, "ugf")) != -1) {
1387                 switch (c) {
1388                 case 'u':
1389                         qctl.qc_type |= 0x01;
1390                         break;
1391                 case 'g':
1392                         qctl.qc_type |= 0x02;
1393                         break;
1394                 case 'f':
1395                         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
1396                         break;
1397                 default:
1398                         fprintf(stderr, "error: %s: option '-%c' "
1399                                         "unrecognized\n", argv[0], c);
1400                         return CMD_HELP;
1401                 }
1402         }
1403
1404         if (qctl.qc_type)
1405                 qctl.qc_type--;
1406         else /* by default, enable quota for both user & group */
1407                 qctl.qc_type = 0x02;
1408
1409         if (argc == optind)
1410                 return CMD_HELP;
1411
1412         mnt = argv[optind];
1413
1414         rc = llapi_quotactl(mnt, &qctl);
1415         if (rc) {
1416                 if (errno == EALREADY) {
1417                         fprintf(stderr, "\n%s quotas are enabled already.\n",
1418                                 qctl.qc_type == 0x02 ? "user/group" :
1419                                 (qctl.qc_type == 0x00 ? "user" : "group"));
1420                         rc = 0;
1421                 } else if (errno == ENOENT) {
1422                         fprintf(stderr, "error: cannot find quota database, "
1423                                         "make sure you have run quotacheck\n");
1424                 } else {
1425                         if (*obd_type)
1426                                 fprintf(stderr, "%s %s ", obd_type,
1427                                         obd_uuid2str(&qctl.obd_uuid));
1428                         fprintf(stderr, "%s failed: %s\n", argv[0],
1429                                 strerror(errno));
1430                 }
1431         }
1432
1433         return rc;
1434 }
1435
1436 static int lfs_quotaoff(int argc, char **argv)
1437 {
1438         int c;
1439         char *mnt;
1440         struct if_quotactl qctl;
1441         char *obd_type = (char *)qctl.obd_type;
1442         int rc;
1443
1444         memset(&qctl, 0, sizeof(qctl));
1445         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
1446
1447         optind = 0;
1448         while ((c = getopt(argc, argv, "ug")) != -1) {
1449                 switch (c) {
1450                 case 'u':
1451                         qctl.qc_type |= 0x01;
1452                         break;
1453                 case 'g':
1454                         qctl.qc_type |= 0x02;
1455                         break;
1456                 default:
1457                         fprintf(stderr, "error: %s: option '-%c' "
1458                                         "unrecognized\n", argv[0], c);
1459                         return CMD_HELP;
1460                 }
1461         }
1462
1463         if (qctl.qc_type)
1464                 qctl.qc_type--;
1465         else /* by default, disable quota for both user & group */
1466                 qctl.qc_type = 0x02;
1467
1468         if (argc == optind)
1469                 return CMD_HELP;
1470
1471         mnt = argv[optind];
1472
1473         rc = llapi_quotactl(mnt, &qctl);
1474         if (rc) {
1475                 if (errno == EALREADY) {
1476                         fprintf(stderr, "\n%s quotas are disabled already.\n",
1477                                 qctl.qc_type == 0x02 ? "user/group" :
1478                                 (qctl.qc_type == 0x00 ? "user" : "group"));
1479                         rc = 0;
1480                 } else {
1481                         if (*obd_type)
1482                                 fprintf(stderr, "%s %s ", obd_type,
1483                                         obd_uuid2str(&qctl.obd_uuid));
1484                         fprintf(stderr, "quotaoff failed: %s\n",
1485                                 strerror(errno));
1486                 }
1487         }
1488
1489         return rc;
1490 }
1491
1492 static int lfs_quotainv(int argc, char **argv)
1493 {
1494         int c;
1495         char *mnt;
1496         struct if_quotactl qctl;
1497         int rc;
1498
1499         memset(&qctl, 0, sizeof(qctl));
1500         qctl.qc_cmd = LUSTRE_Q_INVALIDATE;
1501
1502         optind = 0;
1503         while ((c = getopt(argc, argv, "ugf")) != -1) {
1504                 switch (c) {
1505                 case 'u':
1506                         qctl.qc_type |= 0x01;
1507                         break;
1508                 case 'g':
1509                         qctl.qc_type |= 0x02;
1510                         break;
1511                 case 'f':
1512                         qctl.qc_cmd = LUSTRE_Q_FINVALIDATE;
1513                         break;
1514                 default:
1515                         fprintf(stderr, "error: %s: option '-%c' "
1516                                         "unrecognized\n", argv[0], c);
1517                         return CMD_HELP;
1518                 }
1519         }
1520
1521         if (qctl.qc_type)
1522                 qctl.qc_type--;
1523         else /* by default, invalidate quota for both user & group */
1524                 qctl.qc_type = 0x02;
1525
1526         if (argc == optind)
1527                 return CMD_HELP;
1528
1529         mnt = argv[optind];
1530
1531         rc = llapi_quotactl(mnt, &qctl);
1532         if (rc) {
1533                 fprintf(stderr, "quotainv failed: %s\n", strerror(errno));
1534                 return rc;
1535         }
1536
1537         return 0;
1538 }
1539
1540 #define ARG2INT(nr, str, msg)                                           \
1541 do {                                                                    \
1542         char *endp;                                                     \
1543         nr = strtol(str, &endp, 0);                                     \
1544         if (*endp) {                                                    \
1545                 fprintf(stderr, "error: bad %s: %s\n", msg, str);       \
1546                 return CMD_HELP;                                        \
1547         }                                                               \
1548 } while (0)
1549
1550 #define ADD_OVERFLOW(a,b) ((a + b) < a) ? (a = ULONG_MAX) : (a = a + b)
1551
1552 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
1553  * returns the value or ULONG_MAX on integer overflow or incorrect format
1554  * Notes:
1555  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
1556  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
1557  *        3. empty integer value is interpreted as 0
1558  */
1559
1560 static unsigned long str2sec(const char* timestr) {
1561         const char spec[] = "smhdw";
1562         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
1563         unsigned long val = 0;
1564         char *tail;
1565
1566         if (strpbrk(timestr, spec) == NULL) {
1567                 /* no specifiers inside the time string,
1568                    should treat it as an integer value */
1569                 val = strtoul(timestr, &tail, 10);
1570                 return *tail ? ULONG_MAX : val;
1571         }
1572
1573         /* format string is XXwXXdXXhXXmXXs */
1574         while (*timestr) {
1575                 unsigned long v;
1576                 int ind;
1577                 char* ptr;
1578
1579                 v = strtoul(timestr, &tail, 10);
1580                 if (v == ULONG_MAX || *tail == '\0')
1581                         /* value too large (ULONG_MAX or more)
1582                            or missing specifier */
1583                         goto error;
1584
1585                 ptr = strchr(spec, *tail);
1586                 if (ptr == NULL)
1587                         /* unknown specifier */
1588                         goto error;
1589
1590                 ind = ptr - spec;
1591
1592                 /* check if product will overflow the type */
1593                 if (!(v < ULONG_MAX / mult[ind]))
1594                         goto error;
1595
1596                 ADD_OVERFLOW(val, mult[ind] * v);
1597                 if (val == ULONG_MAX)
1598                         goto error;
1599
1600                 timestr = tail + 1;
1601         }
1602
1603         return val;
1604
1605 error:
1606         return ULONG_MAX;
1607 }
1608
1609 #define ARG2ULL(nr, str, defscale)                                      \
1610 do {                                                                    \
1611         unsigned long long limit, units = 0;                            \
1612         int rc;                                                         \
1613                                                                         \
1614         rc = parse_size(str, &limit, &units, 1);                        \
1615         if (rc < 0) {                                                   \
1616                 fprintf(stderr, "error: bad limit value %s\n", str);    \
1617                 return CMD_HELP;                                        \
1618         }                                                               \
1619         nr = ((units == 0) ? (defscale) : 1) * limit;                   \
1620 } while (0)
1621
1622 static inline int has_times_option(int argc, char **argv)
1623 {
1624         int i;
1625
1626         for (i = 1; i < argc; i++)
1627                 if (!strcmp(argv[i], "-t"))
1628                         return 1;
1629
1630         return 0;
1631 }
1632
1633 int lfs_setquota_times(int argc, char **argv)
1634 {
1635         int c, rc;
1636         struct if_quotactl qctl;
1637         char *mnt, *obd_type = (char *)qctl.obd_type;
1638         struct obd_dqblk *dqb = &qctl.qc_dqblk;
1639         struct obd_dqinfo *dqi = &qctl.qc_dqinfo;
1640         struct option long_opts[] = {
1641                 {"user",            no_argument,       0, 'u'},
1642                 {"group",           no_argument,       0, 'g'},
1643                 {"block-grace",     required_argument, 0, 'b'},
1644                 {"inode-grace",     required_argument, 0, 'i'},
1645                 {"times",           no_argument,       0, 't'},
1646                 {0, 0, 0, 0}
1647         };
1648
1649         memset(&qctl, 0, sizeof(qctl));
1650         qctl.qc_cmd  = LUSTRE_Q_SETINFO;
1651         qctl.qc_type = UGQUOTA;
1652
1653         optind = 0;
1654         while ((c = getopt_long(argc, argv, "ugb:i:t", long_opts, NULL)) != -1) {
1655                 switch (c) {
1656                 case 'u':
1657                 case 'g':
1658                         if (qctl.qc_type != UGQUOTA) {
1659                                 fprintf(stderr, "error: -u and -g can't be used "
1660                                                 "more than once\n");
1661                                 return CMD_HELP;
1662                         }
1663                         qctl.qc_type = (c == 'u') ? USRQUOTA : GRPQUOTA;
1664                         break;
1665                 case 'b':
1666                         if ((dqi->dqi_bgrace = str2sec(optarg)) == ULONG_MAX) {
1667                                 fprintf(stderr, "error: bad block-grace: %s\n",
1668                                         optarg);
1669                                 return CMD_HELP;
1670                         }
1671                         dqb->dqb_valid |= QIF_BTIME;
1672                         break;
1673                 case 'i':
1674                         if ((dqi->dqi_igrace = str2sec(optarg)) == ULONG_MAX) {
1675                                 fprintf(stderr, "error: bad inode-grace: %s\n",
1676                                         optarg);
1677                                 return CMD_HELP;
1678                         }
1679                         dqb->dqb_valid |= QIF_ITIME;
1680                         break;
1681                 case 't': /* Yes, of course! */
1682                         break;
1683                 default: /* getopt prints error message for us when opterr != 0 */
1684                         return CMD_HELP;
1685                 }
1686         }
1687
1688         if (qctl.qc_type == UGQUOTA) {
1689                 fprintf(stderr, "error: neither -u nor -g specified\n");
1690                 return CMD_HELP;
1691         }
1692
1693         if (optind != argc - 1) {
1694                 fprintf(stderr, "error: unexpected parameters encountered\n");
1695                 return CMD_HELP;
1696         }
1697
1698         mnt = argv[optind];
1699         rc = llapi_quotactl(mnt, &qctl);
1700         if (rc) {
1701                 if (*obd_type)
1702                         fprintf(stderr, "%s %s ", obd_type,
1703                                 obd_uuid2str(&qctl.obd_uuid));
1704                 fprintf(stderr, "setquota failed: %s\n", strerror(errno));
1705                 return rc;
1706         }
1707
1708         return 0;
1709 }
1710
1711 #define BSLIMIT (1 << 0)
1712 #define BHLIMIT (1 << 1)
1713 #define ISLIMIT (1 << 2)
1714 #define IHLIMIT (1 << 3)
1715
1716 int lfs_setquota(int argc, char **argv)
1717 {
1718         int c, rc;
1719         struct if_quotactl qctl;
1720         char *mnt, *obd_type = (char *)qctl.obd_type;
1721         struct obd_dqblk *dqb = &qctl.qc_dqblk;
1722         struct option long_opts[] = {
1723                 {"user",            required_argument, 0, 'u'},
1724                 {"group",           required_argument, 0, 'g'},
1725                 {"block-softlimit", required_argument, 0, 'b'},
1726                 {"block-hardlimit", required_argument, 0, 'B'},
1727                 {"inode-softlimit", required_argument, 0, 'i'},
1728                 {"inode-hardlimit", required_argument, 0, 'I'},
1729                 {0, 0, 0, 0}
1730         };
1731         unsigned limit_mask = 0;
1732         char *endptr;
1733
1734         if (has_times_option(argc, argv))
1735                 return lfs_setquota_times(argc, argv);
1736
1737         memset(&qctl, 0, sizeof(qctl));
1738         qctl.qc_cmd  = LUSTRE_Q_SETQUOTA;
1739         qctl.qc_type = UGQUOTA; /* UGQUOTA makes no sense for setquota,
1740                                  * so it can be used as a marker that qc_type
1741                                  * isn't reinitialized from command line */
1742
1743         optind = 0;
1744         while ((c = getopt_long(argc, argv, "u:g:b:B:i:I:", long_opts, NULL)) != -1) {
1745                 switch (c) {
1746                 case 'u':
1747                 case 'g':
1748                         if (qctl.qc_type != UGQUOTA) {
1749                                 fprintf(stderr, "error: -u and -g can't be used"
1750                                                 " more than once\n");
1751                                 return CMD_HELP;
1752                         }
1753                         qctl.qc_type = (c == 'u') ? USRQUOTA : GRPQUOTA;
1754                         rc = name2id(&qctl.qc_id, optarg,
1755                                      (qctl.qc_type == USRQUOTA) ? USER : GROUP);
1756                         if (rc) {
1757                                 qctl.qc_id = strtoul(optarg, &endptr, 10);
1758                                 if (*endptr != '\0') {
1759                                         fprintf(stderr, "error: can't find id "
1760                                                 "for name %s\n", optarg); 
1761                                         return CMD_HELP;
1762                                 }
1763                         }
1764                         break;
1765                 case 'b':
1766                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
1767                         dqb->dqb_bsoftlimit >>= 10;
1768                         limit_mask |= BSLIMIT;
1769                         break;
1770                 case 'B':
1771                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
1772                         dqb->dqb_bhardlimit >>= 10;
1773                         limit_mask |= BHLIMIT;
1774                         break;
1775                 case 'i':
1776                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
1777                         limit_mask |= ISLIMIT;
1778                         break;
1779                 case 'I':
1780                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
1781                         limit_mask |= IHLIMIT;
1782                         break;
1783                 default: /* getopt prints error message for us when opterr != 0 */
1784                         return CMD_HELP;
1785                 }
1786         }
1787
1788         if (qctl.qc_type == UGQUOTA) {
1789                 fprintf(stderr, "error: neither -u nor -g was specified\n");
1790                 return CMD_HELP;
1791         }
1792
1793         if (limit_mask == 0) {
1794                 fprintf(stderr, "error: at least one limit must be specified\n");
1795                 return CMD_HELP;
1796         }
1797
1798         if (optind != argc - 1) {
1799                 fprintf(stderr, "error: unexpected parameters encountered\n");
1800                 return CMD_HELP;
1801         }
1802
1803         mnt = argv[optind];
1804
1805         if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
1806             (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
1807                 /* sigh, we can't just set blimits/ilimits */
1808                 struct if_quotactl tmp_qctl = {.qc_cmd  = LUSTRE_Q_GETQUOTA,
1809                                                .qc_type = qctl.qc_type,
1810                                                .qc_id   = qctl.qc_id};
1811
1812                 rc = llapi_quotactl(mnt, &tmp_qctl);
1813                 if (rc < 0) {
1814                         fprintf(stderr, "error: setquota failed while retrieving"
1815                                         " current quota settings (%s)\n",
1816                                         strerror(errno));
1817                         return rc;
1818                 }
1819
1820                 if (!(limit_mask & BHLIMIT))
1821                         dqb->dqb_bhardlimit = tmp_qctl.qc_dqblk.dqb_bhardlimit;
1822                 if (!(limit_mask & BSLIMIT))
1823                         dqb->dqb_bsoftlimit = tmp_qctl.qc_dqblk.dqb_bsoftlimit;
1824                 if (!(limit_mask & IHLIMIT))
1825                         dqb->dqb_ihardlimit = tmp_qctl.qc_dqblk.dqb_ihardlimit;
1826                 if (!(limit_mask & ISLIMIT))
1827                         dqb->dqb_isoftlimit = tmp_qctl.qc_dqblk.dqb_isoftlimit;
1828
1829                 /* Keep grace times if we have got no softlimit arguments */
1830                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
1831                         dqb->dqb_valid |= QIF_BTIME;
1832                         dqb->dqb_btime = tmp_qctl.qc_dqblk.dqb_btime;
1833                 }
1834
1835                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
1836                         dqb->dqb_valid |= QIF_ITIME;
1837                         dqb->dqb_itime = tmp_qctl.qc_dqblk.dqb_itime;
1838                 }
1839         }
1840
1841         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
1842         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
1843
1844         rc = llapi_quotactl(mnt, &qctl);
1845         if (rc) {
1846                 if (*obd_type)
1847                         fprintf(stderr, "%s %s ", obd_type,
1848                                 obd_uuid2str(&qctl.obd_uuid));
1849                 fprintf(stderr, "setquota failed: %s\n", strerror(errno));
1850                 return rc;
1851         }
1852
1853         return 0;
1854 }
1855
1856 static inline char *type2name(int check_type)
1857 {
1858         if (check_type == USRQUOTA)
1859                 return "user";
1860         else if (check_type == GRPQUOTA)
1861                 return "group";
1862         else
1863                 return "unknown";
1864 }
1865
1866
1867 /* Converts seconds value into format string
1868  * result is returned in buf
1869  * Notes:
1870  *        1. result is in descenting order: 1w2d3h4m5s
1871  *        2. zero fields are not filled (except for p. 3): 5d1s
1872  *        3. zero seconds value is presented as "0s"
1873  */
1874 static void sec2str(time_t seconds, char *buf)
1875 {
1876         const char spec[] = "smhdw";
1877         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
1878         unsigned long c;
1879         char* tail = buf;
1880         int i;
1881
1882         for (i = sizeof(mult) / sizeof(mult[0]) - 1 ; i >= 0; i--) {
1883                 c = seconds / mult[i];
1884
1885                 if (c > 0 || (i == 0 && buf == tail))
1886                         tail += snprintf(tail, 40-(tail-buf), "%lu%c", c, spec[i]);
1887
1888                 seconds %= mult[i];
1889         }
1890 }
1891
1892
1893 static void diff2str(time_t seconds, char *buf, time_t now)
1894 {
1895
1896         buf[0] = 0;
1897         if (!seconds)
1898                 return;
1899         if (seconds <= now) {
1900                 strcpy(buf, "none");
1901                 return;
1902         }
1903         sec2str(seconds - now, buf);
1904 }
1905
1906 static void print_quota_title(char *name, struct if_quotactl *qctl)
1907 {
1908         printf("Disk quotas for %s %s (%cid %u):\n",
1909                type2name(qctl->qc_type), name,
1910                *type2name(qctl->qc_type), qctl->qc_id);
1911         printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
1912                "Filesystem",
1913                "kbytes", "quota", "limit", "grace",
1914                "files", "quota", "limit", "grace");
1915 }
1916
1917 static void print_quota(char *mnt, struct if_quotactl *qctl, int type, int rc)
1918 {
1919         time_t now;
1920
1921         time(&now);
1922
1923         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA) {
1924                 int bover = 0, iover = 0;
1925                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
1926
1927                 if (dqb->dqb_bhardlimit &&
1928                     toqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
1929                         bover = 1;
1930                 } else if (dqb->dqb_bsoftlimit &&
1931                            toqb(dqb->dqb_curspace) >= dqb->dqb_bsoftlimit) {
1932                         if (dqb->dqb_btime > now) {
1933                                 bover = 2;
1934                         } else {
1935                                 bover = 3;
1936                         }
1937                 }
1938
1939                 if (dqb->dqb_ihardlimit &&
1940                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
1941                         iover = 1;
1942                 } else if (dqb->dqb_isoftlimit &&
1943                            dqb->dqb_curinodes >= dqb->dqb_isoftlimit) {
1944                         if (dqb->dqb_btime > now) {
1945                                 iover = 2;
1946                         } else {
1947                                 iover = 3;
1948                         }
1949                 }
1950
1951 #if 0           /* XXX: always print quotas even when no usages */
1952                 if (dqb->dqb_curspace || dqb->dqb_curinodes)
1953 #endif
1954                 {
1955                         char numbuf[3][32];
1956                         char timebuf[40];
1957
1958                         if (strlen(mnt) > 15)
1959                                 printf("%s\n%15s", mnt, "");
1960                         else
1961                                 printf("%15s", mnt);
1962
1963                         if (bover)
1964                                 diff2str(dqb->dqb_btime, timebuf, now);
1965                         if (rc == -1 && errno == EREMOTEIO)
1966                                 sprintf(numbuf[0], LPU64"*",
1967                                         toqb(dqb->dqb_curspace));
1968                         else
1969                                 sprintf(numbuf[0],
1970                                         (dqb->dqb_valid & QIF_SPACE) ?
1971                                         LPU64 : "["LPU64"]",
1972                                         toqb(dqb->dqb_curspace));
1973                         if (type == QC_GENERAL)
1974                                 sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS)
1975                                         ? LPU64 : "["LPU64"]",
1976                                         dqb->dqb_bsoftlimit);
1977                         else
1978                                 sprintf(numbuf[1], "%s", "");
1979                         sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS)
1980                                 ? LPU64 : "["LPU64"]", dqb->dqb_bhardlimit);
1981                         printf(" %7s%c %6s %7s %7s",
1982                                numbuf[0], bover ? '*' : ' ', numbuf[1],
1983                                numbuf[2], bover > 1 ? timebuf : "");
1984
1985                         if (iover)
1986                                 diff2str(dqb->dqb_itime, timebuf, now);
1987
1988                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_INODES) ?
1989                                 LPU64 : "["LPU64"]", dqb->dqb_curinodes);
1990                        if (type == QC_GENERAL)
1991                                 sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS)
1992                                         ? LPU64 : "["LPU64"]",
1993                                         dqb->dqb_isoftlimit);
1994                         else
1995                                 sprintf(numbuf[1], "%s", "");
1996                         sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
1997                                 LPU64 : "["LPU64"]", dqb->dqb_ihardlimit);
1998                         if (type != QC_OSTIDX)
1999                                 printf(" %7s%c %6s %7s %7s",
2000                                        numbuf[0], iover ? '*' : ' ', numbuf[1],
2001                                        numbuf[2], iover > 1 ? timebuf : "");
2002                         printf("\n");
2003                 }
2004         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO ||
2005                    qctl->qc_cmd == Q_GETOINFO) {
2006                 char bgtimebuf[40];
2007                 char igtimebuf[40];
2008
2009                 sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf);
2010                 sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf);
2011                 printf("Block grace time: %s; Inode grace time: %s\n",
2012                        bgtimebuf, igtimebuf);
2013         }
2014 }
2015
2016 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt)
2017 {
2018         int rc = 0, rc1 = 0, count = 0;
2019         __u32 valid = qctl->qc_valid;
2020
2021         rc = llapi_get_obd_count(mnt, &count, is_mdt);
2022         if (rc) {
2023                 fprintf(stderr, "can not get %s count: %s\n",
2024                         is_mdt ? "mdt": "ost", strerror(errno));
2025                 return rc;
2026         }
2027
2028         for (qctl->qc_idx = 0; qctl->qc_idx < count; qctl->qc_idx++) {
2029                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
2030                 rc = llapi_quotactl(mnt, qctl);
2031                 if (rc) {
2032                         /* It is remote client case. */
2033                         if (errno == EOPNOTSUPP) {
2034                                 rc = 0;
2035                                 goto out;
2036                         }
2037
2038                         if (!rc1)
2039                                 rc1 = rc;
2040                         fprintf(stderr, "quotactl %s%d failed.\n",
2041                                 is_mdt ? "mdt": "ost", qctl->qc_idx);
2042                         continue;
2043                 }
2044
2045                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl, qctl->qc_valid, 0);
2046         }
2047
2048 out:
2049         qctl->qc_valid = valid;
2050         return rc ? : rc1;
2051 }
2052
2053 static int lfs_quota(int argc, char **argv)
2054 {
2055         int c;
2056         char *mnt, *name = NULL;
2057         struct if_quotactl qctl = { .qc_cmd = LUSTRE_Q_GETQUOTA,
2058                                     .qc_type = UGQUOTA };
2059         char *obd_type = (char *)qctl.obd_type;
2060         char *obd_uuid = (char *)qctl.obd_uuid.uuid;
2061         int rc, rc1 = 0, rc2 = 0, rc3 = 0, verbose = 0, pass = 0;
2062         char *endptr;
2063         __u32 valid = QC_GENERAL, idx = 0;
2064
2065         optind = 0;
2066         while ((c = getopt(argc, argv, "ugto:i:I:v")) != -1) {
2067                 switch (c) {
2068                 case 'u':
2069                         if (qctl.qc_type != UGQUOTA) {
2070                                 fprintf(stderr, "error: use either -u or -g\n");
2071                                 return CMD_HELP;
2072                         }
2073                         qctl.qc_type = USRQUOTA;
2074                         break;
2075                 case 'g':
2076                         if (qctl.qc_type != UGQUOTA) {
2077                                 fprintf(stderr, "error: use either -u or -g\n");
2078                                 return CMD_HELP;
2079                         }
2080                         qctl.qc_type = GRPQUOTA;
2081                         break;
2082                 case 't':
2083                         qctl.qc_cmd = LUSTRE_Q_GETINFO;
2084                         break;
2085                 case 'o':
2086                         valid = qctl.qc_valid = QC_UUID;
2087                         strncpy(obd_uuid, optarg, sizeof(qctl.obd_uuid));
2088                         break;
2089                 case 'i':
2090                         valid = qctl.qc_valid = QC_MDTIDX;
2091                         idx = qctl.qc_idx = atoi(optarg);
2092                         break;
2093                 case 'I':
2094                         valid = qctl.qc_valid = QC_OSTIDX;
2095                         idx = qctl.qc_idx = atoi(optarg);
2096                         break;
2097                 case 'v':
2098                         verbose = 1;
2099                         break;
2100                 default:
2101                         fprintf(stderr, "error: %s: option '-%c' "
2102                                         "unrecognized\n", argv[0], c);
2103                         return CMD_HELP;
2104                 }
2105         }
2106
2107         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
2108         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA && qctl.qc_type == UGQUOTA &&
2109             optind == argc - 1) {
2110 ug_output:
2111                 memset(&qctl, 0, sizeof(qctl)); /* spoiled by print_*_quota */
2112                 qctl.qc_cmd = LUSTRE_Q_GETQUOTA;
2113                 qctl.qc_valid = valid;
2114                 qctl.qc_idx = idx;
2115                 if (pass++ == 0) {
2116                         qctl.qc_type = USRQUOTA;
2117                         qctl.qc_id = geteuid();
2118                 } else {
2119                         qctl.qc_type = GRPQUOTA;
2120                         qctl.qc_id = getegid();
2121                 }
2122                 rc = id2name(&name, qctl.qc_id,
2123                              (qctl.qc_type == USRQUOTA) ? USER : GROUP);
2124                 if (rc)
2125                         name = "<unknown>";
2126         /* lfs quota -u username /path/to/lustre/mount */
2127         } else if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) {
2128                 /* options should be followed by u/g-name and mntpoint */
2129                 if (optind + 2 != argc || qctl.qc_type == UGQUOTA) {
2130                         fprintf(stderr, "error: missing quota argument(s)\n");
2131                         return CMD_HELP;
2132                 }
2133
2134                 name = argv[optind++];
2135                 rc = name2id(&qctl.qc_id, name,
2136                              (qctl.qc_type == USRQUOTA) ? USER : GROUP);
2137                 if (rc) {
2138                         qctl.qc_id = strtoul(name, &endptr, 10);
2139                         if (*endptr != '\0') {
2140                                 fprintf(stderr, "error: can't find id for name "
2141                                         "%s\n", name);
2142                                 return CMD_HELP;
2143                         }
2144                 }
2145         } else if (optind + 1 != argc || qctl.qc_type == UGQUOTA) {
2146                 fprintf(stderr, "error: missing quota info argument(s)\n");
2147                 return CMD_HELP;
2148         }
2149
2150         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA)
2151                 print_quota_title(name, &qctl);
2152
2153         mnt = argv[optind];
2154
2155         rc1 = llapi_quotactl(mnt, &qctl);
2156         if (rc1 == -1 && errno == EALREADY) {
2157                 fprintf(stderr, "\n%s quotas are not enabled.\n",
2158                         qctl.qc_type == USRQUOTA ? "user" : "group");
2159                 goto out;
2160         }
2161         if (rc1 && *obd_type)
2162                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
2163
2164         if (qctl.qc_valid != QC_GENERAL)
2165                 mnt = "";
2166
2167         print_quota(mnt, &qctl, QC_GENERAL, rc1);
2168
2169         if (qctl.qc_valid == QC_GENERAL && qctl.qc_cmd != LUSTRE_Q_GETINFO && verbose) {
2170                 rc2 = print_obd_quota(mnt, &qctl, 1);
2171                 rc3 = print_obd_quota(mnt, &qctl, 0);
2172         }
2173
2174         if (rc1 || rc2 || rc3)
2175                 printf("Some errors happened when getting quota info. "
2176                        "Some devices may be not working or deactivated. "
2177                        "The data in \"[]\" is inaccurate.\n");
2178
2179 out:
2180         if (pass == 1)
2181                 goto ug_output;
2182
2183         return 0;
2184 }
2185 #endif /* HAVE_SYS_QUOTA_H! */
2186
2187 static int flushctx_ioctl(char *mp)
2188 {
2189         int fd, rc;
2190
2191         fd = open(mp, O_RDONLY);
2192         if (fd == -1) {
2193                 fprintf(stderr, "flushctx: error open %s: %s\n",
2194                         mp, strerror(errno));
2195                 return -1;
2196         }
2197
2198         rc = ioctl(fd, LL_IOC_FLUSHCTX);
2199         if (rc == -1)
2200                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
2201                         mp, strerror(errno));
2202
2203         close(fd);
2204         return rc;
2205 }
2206
2207 static int lfs_flushctx(int argc, char **argv)
2208 {
2209         int     kdestroy = 0, c;
2210         FILE   *proc;
2211         char    procline[PATH_MAX], *line;
2212         int     rc = 0;
2213
2214         optind = 0;
2215         while ((c = getopt(argc, argv, "k")) != -1) {
2216                 switch (c) {
2217                 case 'k':
2218                         kdestroy = 1;
2219                         break;
2220                 default:
2221                         fprintf(stderr, "error: %s: option '-%c' "
2222                                         "unrecognized\n", argv[0], c);
2223                         return CMD_HELP;
2224                 }
2225         }
2226
2227         if (kdestroy) {
2228             int rc;
2229             if ((rc = system("kdestroy > /dev/null")) != 0) {
2230                 rc = WEXITSTATUS(rc);
2231                 fprintf(stderr, "error destroying tickets: %d, continuing\n", rc);
2232             }
2233         }
2234
2235         if (optind >= argc) {
2236                 /* flush for all mounted lustre fs. */
2237                 proc = fopen("/proc/mounts", "r");
2238                 if (!proc) {
2239                         fprintf(stderr, "error: %s: can't open /proc/mounts\n",
2240                                 argv[0]);
2241                         return -1;
2242                 }
2243
2244                 while ((line = fgets(procline, PATH_MAX, proc)) != NULL) {
2245                         char dev[PATH_MAX];
2246                         char mp[PATH_MAX];
2247                         char fs[PATH_MAX];
2248
2249                         if (sscanf(line, "%s %s %s", dev, mp, fs) != 3) {
2250                                 fprintf(stderr, "%s: unexpected format in "
2251                                                 "/proc/mounts\n",
2252                                         argv[0]);
2253                                 return -1;
2254                         }
2255
2256                         if (strcmp(fs, "lustre") != 0)
2257                                 continue;
2258                         /* we use '@' to determine it's a client. are there
2259                          * any other better way?
2260                          */
2261                         if (strchr(dev, '@') == NULL)
2262                                 continue;
2263
2264                         if (flushctx_ioctl(mp))
2265                                 rc = -1;
2266                 }
2267         } else {
2268                 /* flush fs as specified */
2269                 while (optind < argc) {
2270                         if (flushctx_ioctl(argv[optind++]))
2271                                 rc = -1;
2272                 }
2273         }
2274
2275         return rc;
2276 }
2277
2278 static int lfs_lsetfacl(int argc, char **argv)
2279 {
2280         argv[0]++;
2281         return(llapi_lsetfacl(argc, argv));
2282 }
2283
2284 static int lfs_lgetfacl(int argc, char **argv)
2285 {
2286         argv[0]++;
2287         return(llapi_lgetfacl(argc, argv));
2288 }
2289
2290 static int lfs_rsetfacl(int argc, char **argv)
2291 {
2292         argv[0]++;
2293         return(llapi_rsetfacl(argc, argv));
2294 }
2295
2296 static int lfs_rgetfacl(int argc, char **argv)
2297 {
2298         argv[0]++;
2299         return(llapi_rgetfacl(argc, argv));
2300 }
2301
2302 static int lfs_cp(int argc, char **argv)
2303 {
2304         return(llapi_cp(argc, argv));
2305 }
2306
2307 static int lfs_ls(int argc, char **argv)
2308 {
2309         return(llapi_ls(argc, argv));
2310 }
2311
2312 static int lfs_changelog(int argc, char **argv)
2313 {
2314         void *changelog_priv;
2315         struct changelog_rec *rec;
2316         long long startrec = 0, endrec = 0;
2317         char *mdd;
2318         struct option long_opts[] = {
2319                 {"follow", no_argument, 0, 'f'},
2320                 {0, 0, 0, 0}
2321         };
2322         char short_opts[] = "f";
2323         int rc, follow = 0;
2324
2325         optind = 0;
2326         while ((rc = getopt_long(argc, argv, short_opts,
2327                                 long_opts, NULL)) != -1) {
2328                 switch (rc) {
2329                 case 'f':
2330                         follow++;
2331                         break;
2332                 case '?':
2333                         return CMD_HELP;
2334                 default:
2335                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
2336                                 argv[0], argv[optind - 1]);
2337                         return CMD_HELP;
2338                 }
2339         }
2340         if (optind >= argc)
2341                 return CMD_HELP;
2342
2343         mdd = argv[optind++];
2344         if (argc > optind)
2345                 startrec = strtoll(argv[optind++], NULL, 10);
2346         if (argc > optind)
2347                 endrec = strtoll(argv[optind++], NULL, 10);
2348
2349         rc = llapi_changelog_start(&changelog_priv,
2350                                    CHANGELOG_FLAG_BLOCK |
2351                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
2352                                    mdd, startrec);
2353         if (rc < 0) {
2354                 fprintf(stderr, "Can't start changelog: %s\n",
2355                         strerror(errno = -rc));
2356                 return rc;
2357         }
2358
2359         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
2360                 if (endrec && rec->cr_index > endrec)
2361                         break;
2362                 if (rec->cr_index < startrec)
2363                         continue;
2364
2365                 printf(LPU64" %02d%-5s "LPU64" 0x%x t="DFID,
2366                        rec->cr_index, rec->cr_type,
2367                        changelog_type2str(rec->cr_type), rec->cr_time,
2368                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
2369                 if (rec->cr_namelen)
2370                         /* namespace rec includes parent and filename */
2371                         printf(" p="DFID" %.*s\n", PFID(&rec->cr_pfid),
2372                                rec->cr_namelen, rec->cr_name);
2373                 else
2374                         printf("\n");
2375
2376                 llapi_changelog_free(&rec);
2377         }
2378
2379         llapi_changelog_fini(&changelog_priv);
2380
2381         if (rc < 0)
2382                 fprintf(stderr, "Changelog: %s\n", strerror(errno = -rc));
2383
2384         return (rc == 1 ? 0 : rc);
2385 }
2386
2387 static int lfs_changelog_clear(int argc, char **argv)
2388 {
2389         long long endrec;
2390         int rc;
2391
2392         if (argc != 4)
2393                 return CMD_HELP;
2394
2395         endrec = strtoll(argv[3], NULL, 10);
2396
2397         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
2398         if (rc)
2399                 fprintf(stderr, "%s error: %s\n", argv[0],
2400                         strerror(errno = -rc));
2401         return rc;
2402 }
2403
2404 static int lfs_fid2path(int argc, char **argv)
2405 {
2406         struct option long_opts[] = {
2407                 {"cur", no_argument, 0, 'c'},
2408                 {"link", required_argument, 0, 'l'},
2409                 {"rec", required_argument, 0, 'r'},
2410                 {0, 0, 0, 0}
2411         };
2412         char  short_opts[] = "cl:r:";
2413         char *device, *fid, *path;
2414         long long recno = -1;
2415         int linkno = -1;
2416         int lnktmp;
2417         int printcur = 0;
2418         int rc;
2419
2420         optind = 0;
2421
2422         while ((rc = getopt_long(argc, argv, short_opts,
2423                                 long_opts, NULL)) != -1) {
2424                 switch (rc) {
2425                 case 'c':
2426                         printcur++;
2427                         break;
2428                 case 'l':
2429                         linkno = strtol(optarg, NULL, 10);
2430                         break;
2431                 case 'r':
2432                         recno = strtoll(optarg, NULL, 10);
2433                         break;
2434                 case '?':
2435                         return CMD_HELP;
2436                 default:
2437                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
2438                                 argv[0], argv[optind - 1]);
2439                         return CMD_HELP;
2440                 }
2441         }
2442         device = argv[optind++];
2443         fid = argv[optind++];
2444         if (optind != argc)
2445                 return CMD_HELP;
2446
2447         path = calloc(1, PATH_MAX);
2448
2449         lnktmp = (linkno >= 0) ? linkno : 0;
2450         while (1) {
2451                 int oldtmp = lnktmp;
2452                 long long rectmp = recno;
2453                 rc = llapi_fid2path(device, fid, path, PATH_MAX, &rectmp,
2454                                     &lnktmp);
2455                 if (rc < 0) {
2456                         fprintf(stderr, "%s error: %s\n", argv[0],
2457                                 strerror(errno = -rc));
2458                         break;
2459                 }
2460
2461                 if (printcur)
2462                         fprintf(stdout, "%lld %s\n", rectmp, path);
2463                 else
2464                         fprintf(stdout, "%s\n", path);
2465
2466                 if (linkno >= 0)
2467                         /* specified linkno */
2468                         break;
2469                 if (oldtmp == lnktmp)
2470                         /* no more links */
2471                         break;
2472         }
2473
2474         free(path);
2475         return rc;
2476 }
2477
2478 static int lfs_path2fid(int argc, char **argv)
2479 {
2480         char *path;
2481         lustre_fid fid;
2482         int rc;
2483
2484         if (argc != 2)
2485                 return CMD_HELP;
2486
2487         path = argv[1];
2488         rc = llapi_path2fid(path, &fid);
2489         if (rc) {
2490                 fprintf(stderr, "can't get fid for %s: %s\n", path,
2491                         strerror(errno = -rc));
2492                 return rc;
2493         }
2494
2495         printf(DFID"\n", PFID(&fid));
2496
2497         return 0;
2498 }
2499
2500 int main(int argc, char **argv)
2501 {
2502         int rc;
2503
2504         setlinebuf(stdout);
2505
2506         ptl_initialize(argc, argv);
2507         if (obd_initialize(argc, argv) < 0)
2508                 exit(2);
2509         if (dbg_initialize(argc, argv) < 0)
2510                 exit(3);
2511
2512         Parser_init("lfs > ", cmdlist);
2513
2514         if (argc > 1) {
2515                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
2516         } else {
2517                 rc = Parser_commands();
2518         }
2519
2520         obd_finalize(argc, argv);
2521         return rc < 0 ? -rc : rc;
2522 }
2523