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