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