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