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