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