Whamcloud - gitweb
Branch HEAD
[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         {"pool_list", lfs_poollist, 0,
137          "List pools or pool OSTs\n"
138          "usage: pool_list <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_iterate(num_types, obd_types,
1249                                   mnt->mnt_dir, llapi_ping_target);
1250
1251         if (rc)
1252                 fprintf(stderr, "error: %s: %s status failed\n",
1253                                 argv[0],argv[1]);
1254
1255         return rc;
1256
1257 }
1258
1259 static int lfs_catinfo(int argc, char **argv)
1260 {
1261         FILE *fp;
1262         struct mntent *mnt = NULL;
1263         int rc;
1264
1265         if (argc < 2 || (!strcmp(argv[1],"config") && argc < 3))
1266                 return CMD_HELP;
1267
1268         if (strcmp(argv[1], "config") && strcmp(argv[1], "deletions"))
1269                 return CMD_HELP;
1270
1271         fp = setmntent(MOUNTED, "r");
1272         if (fp == NULL) {
1273                  fprintf(stderr, "setmntent(%s): %s:", MOUNTED,
1274                          strerror(errno));
1275         } else {
1276                 mnt = getmntent(fp);
1277                 while (feof(fp) == 0 && ferror(fp) == 0) {
1278                         if (llapi_is_lustre_mnt(mnt))
1279                                 break;
1280                         mnt = getmntent(fp);
1281                 }
1282                 endmntent(fp);
1283         }
1284
1285         if (mnt) {
1286                 if (argc == 3)
1287                         rc = llapi_catinfo(mnt->mnt_dir, argv[1], argv[2]);
1288                 else
1289                         rc = llapi_catinfo(mnt->mnt_dir, argv[1], NULL);
1290         } else {
1291                 fprintf(stderr, "no lustre_lite mounted.\n");
1292                 rc = -1;
1293         }
1294
1295         return rc;
1296 }
1297
1298 int lfs_join(int argc, char **argv)
1299 {
1300         char *name_head, *name_tail;
1301         int fd, rc;
1302         loff_t size;
1303
1304         if (argc != 3)
1305                 return CMD_HELP;
1306         name_head = argv[1];
1307         fd = open(name_head, O_WRONLY);
1308         if (fd < 0) {
1309                 fprintf(stderr, "Can not open name_head %s rc=%d\n",
1310                         name_head, fd);
1311                 return fd;
1312         }
1313         size = lseek(fd, 0, SEEK_END);
1314         if (size % JOIN_FILE_ALIGN) {
1315                 fprintf(stderr,"head file %s size %llu must be mutiple of %d\n",
1316                         name_head, (long long)size, JOIN_FILE_ALIGN);
1317                 rc = -EINVAL;
1318                 goto out;
1319         }
1320         name_tail = argv[2];
1321         rc = ioctl(fd, LL_IOC_JOIN, name_tail);
1322 out:
1323         close(fd);
1324         if (rc) {
1325                 fprintf(stderr, "Lustre joining files: %s, %s, failed\n",
1326                         argv[1], argv[2]);
1327         }
1328         return rc;
1329 }
1330
1331 #ifdef HAVE_SYS_QUOTA_H
1332 static int lfs_quotachown(int argc, char **argv)
1333 {
1334
1335         int c,rc;
1336         int flag = 0;
1337
1338         optind = 0;
1339         while ((c = getopt(argc, argv, "i")) != -1) {
1340                 switch (c) {
1341                 case 'i':
1342                         flag++;
1343                         break;
1344                 default:
1345                         fprintf(stderr, "error: %s: option '-%c' "
1346                                         "unrecognized\n", argv[0], c);
1347                         return CMD_HELP;
1348                 }
1349         }
1350         if (optind == argc)
1351                 return CMD_HELP;
1352         rc = llapi_quotachown(argv[optind], flag);
1353         if(rc)
1354                 fprintf(stderr,"error: change file owner/group failed.\n");
1355         return rc;
1356 }
1357
1358 static int lfs_quotacheck(int argc, char **argv)
1359 {
1360         int c, check_type = 0;
1361         char *mnt;
1362         struct if_quotacheck qchk;
1363         struct if_quotactl qctl;
1364         char *obd_type = (char *)qchk.obd_type;
1365         int rc;
1366
1367         memset(&qchk, 0, sizeof(qchk));
1368
1369         optind = 0;
1370         while ((c = getopt(argc, argv, "ug")) != -1) {
1371                 switch (c) {
1372                 case 'u':
1373                         check_type |= 0x01;
1374                         break;
1375                 case 'g':
1376                         check_type |= 0x02;
1377                         break;
1378                 default:
1379                         fprintf(stderr, "error: %s: option '-%c' "
1380                                         "unrecognized\n", argv[0], c);
1381                         return CMD_HELP;
1382                 }
1383         }
1384
1385         if (check_type)
1386                 check_type--;
1387         else    /* do quotacheck for both user & group quota by default */
1388                 check_type = 0x02;
1389
1390         if (argc == optind)
1391                 return CMD_HELP;
1392
1393         mnt = argv[optind];
1394
1395         memset(&qctl, 0, sizeof(qctl));
1396         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
1397         qctl.qc_type = check_type;
1398         rc = llapi_quotactl(mnt, &qctl);
1399         if (rc) {
1400                 fprintf(stderr, "quota off failed: %s\n", strerror(errno));
1401                 return rc;
1402         }
1403
1404         rc = llapi_quotacheck(mnt, check_type);
1405         if (rc) {
1406                 fprintf(stderr, "quotacheck failed: %s\n", strerror(errno));
1407                 return rc;
1408         }
1409
1410         rc = llapi_poll_quotacheck(mnt, &qchk);
1411         if (rc) {
1412                 if (*obd_type)
1413                         fprintf(stderr, "%s %s ", obd_type,
1414                                 obd_uuid2str(&qchk.obd_uuid));
1415                 fprintf(stderr, "quota check failed: %s\n", strerror(errno));
1416                 return rc;
1417         }
1418
1419         memset(&qctl, 0, sizeof(qctl));
1420         qctl.qc_cmd = LUSTRE_Q_QUOTAON;
1421         qctl.qc_type = check_type;
1422         rc = llapi_quotactl(mnt, &qctl);
1423         if (rc) {
1424                 if (*obd_type)
1425                         fprintf(stderr, "%s %s ", (char *)qctl.obd_type,
1426                                 obd_uuid2str(&qctl.obd_uuid));
1427                 fprintf(stderr, "%s turn on quota failed: %s\n",
1428                         argv[0], strerror(errno));
1429                 return rc;
1430         }
1431
1432         return 0;
1433 }
1434
1435 static int lfs_quotaon(int argc, char **argv)
1436 {
1437         int c;
1438         char *mnt;
1439         struct if_quotactl qctl;
1440         char *obd_type = (char *)qctl.obd_type;
1441         int rc;
1442
1443         memset(&qctl, 0, sizeof(qctl));
1444         qctl.qc_cmd = LUSTRE_Q_QUOTAON;
1445
1446         optind = 0;
1447         while ((c = getopt(argc, argv, "ugf")) != -1) {
1448                 switch (c) {
1449                 case 'u':
1450                         qctl.qc_type |= 0x01;
1451                         break;
1452                 case 'g':
1453                         qctl.qc_type |= 0x02;
1454                         break;
1455                 case 'f':
1456                         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
1457                         break;
1458                 default:
1459                         fprintf(stderr, "error: %s: option '-%c' "
1460                                         "unrecognized\n", argv[0], c);
1461                         return CMD_HELP;
1462                 }
1463         }
1464
1465         if (qctl.qc_type)
1466                 qctl.qc_type--;
1467         else /* by default, enable quota for both user & group */
1468                 qctl.qc_type = 0x02;
1469
1470         if (argc == optind)
1471                 return CMD_HELP;
1472
1473         mnt = argv[optind];
1474
1475         rc = llapi_quotactl(mnt, &qctl);
1476         if (rc) {
1477                 if (*obd_type)
1478                         fprintf(stderr, "%s %s ", obd_type,
1479                                 obd_uuid2str(&qctl.obd_uuid));
1480                 fprintf(stderr, "%s failed: %s\n", argv[0], strerror(errno));
1481                 return rc;
1482         }
1483
1484         return 0;
1485 }
1486
1487 static int lfs_quotaoff(int argc, char **argv)
1488 {
1489         int c;
1490         char *mnt;
1491         struct if_quotactl qctl;
1492         char *obd_type = (char *)qctl.obd_type;
1493         int rc;
1494
1495         memset(&qctl, 0, sizeof(qctl));
1496         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
1497
1498         optind = 0;
1499         while ((c = getopt(argc, argv, "ug")) != -1) {
1500                 switch (c) {
1501                 case 'u':
1502                         qctl.qc_type |= 0x01;
1503                         break;
1504                 case 'g':
1505                         qctl.qc_type |= 0x02;
1506                         break;
1507                 default:
1508                         fprintf(stderr, "error: %s: option '-%c' "
1509                                         "unrecognized\n", argv[0], c);
1510                         return CMD_HELP;
1511                 }
1512         }
1513
1514         if (qctl.qc_type)
1515                 qctl.qc_type--;
1516         else /* by default, disable quota for both user & group */
1517                 qctl.qc_type = 0x02;
1518
1519         if (argc == optind)
1520                 return CMD_HELP;
1521
1522         mnt = argv[optind];
1523
1524         rc = llapi_quotactl(mnt, &qctl);
1525         if (rc == -1 && errno == ESRCH) {
1526                 fprintf(stderr, "\n%s quotas are not enabled.\n",
1527                         qctl.qc_type == 0x00 ? "user" : "group");
1528                 return 0;
1529         }
1530         if (rc) {
1531                 if (*obd_type)
1532                         fprintf(stderr, "%s %s ", obd_type,
1533                                 obd_uuid2str(&qctl.obd_uuid));
1534                 fprintf(stderr, "quotaoff failed: %s\n", strerror(errno));
1535                 return rc;
1536         }
1537
1538         return 0;
1539 }
1540
1541 static int lfs_quotainv(int argc, char **argv)
1542 {
1543         int c;
1544         char *mnt;
1545         struct if_quotactl qctl;
1546         int rc;
1547
1548         memset(&qctl, 0, sizeof(qctl));
1549         qctl.qc_cmd = LUSTRE_Q_INVALIDATE;
1550
1551         optind = 0;
1552         while ((c = getopt(argc, argv, "ugf")) != -1) {
1553                 switch (c) {
1554                 case 'u':
1555                         qctl.qc_type |= 0x01;
1556                         break;
1557                 case 'g':
1558                         qctl.qc_type |= 0x02;
1559                         break;
1560                 case 'f':
1561                         qctl.qc_cmd = LUSTRE_Q_FINVALIDATE;
1562                         break;
1563                 default:
1564                         fprintf(stderr, "error: %s: option '-%c' "
1565                                         "unrecognized\n", argv[0], c);
1566                         return CMD_HELP;
1567                 }
1568         }
1569
1570         if (qctl.qc_type)
1571                 qctl.qc_type--;
1572         else /* by default, invalidate quota for both user & group */
1573                 qctl.qc_type = 0x02;
1574
1575         if (argc == optind)
1576                 return CMD_HELP;
1577
1578         mnt = argv[optind];
1579
1580         rc = llapi_quotactl(mnt, &qctl);
1581         if (rc) {
1582                 fprintf(stderr, "quotainv failed: %s\n", strerror(errno));
1583                 return rc;
1584         }
1585
1586         return 0;
1587 }
1588
1589 #define ARG2INT(nr, str, msg)                                           \
1590 do {                                                                    \
1591         char *endp;                                                     \
1592         nr = strtol(str, &endp, 0);                                     \
1593         if (*endp) {                                                    \
1594                 fprintf(stderr, "error: bad %s: %s\n", msg, str);       \
1595                 return CMD_HELP;                                        \
1596         }                                                               \
1597 } while (0)
1598
1599 #define ADD_OVERFLOW(a,b) ((a + b) < a) ? (a = ULONG_MAX) : (a = a + b)
1600
1601 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
1602  * returns the value or ULONG_MAX on integer overflow or incorrect format
1603  * Notes:
1604  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
1605  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
1606  *        3. empty integer value is interpreted as 0
1607  */
1608
1609 static unsigned long str2sec(const char* timestr) {
1610         const char spec[] = "smhdw";
1611         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
1612         unsigned long val = 0;
1613         char *tail;
1614
1615         if (strpbrk(timestr, spec) == NULL) {
1616                 /* no specifiers inside the time string,
1617                    should treat it as an integer value */
1618                 val = strtoul(timestr, &tail, 10);
1619                 return *tail ? ULONG_MAX : val;
1620         }
1621
1622         /* format string is XXwXXdXXhXXmXXs */
1623         while (*timestr) {
1624                 unsigned long v;
1625                 int ind;
1626                 char* ptr;
1627
1628                 v = strtoul(timestr, &tail, 10);
1629                 if (v == ULONG_MAX || *tail == '\0')
1630                         /* value too large (ULONG_MAX or more)
1631                            or missing specifier */
1632                         goto error;
1633
1634                 ptr = strchr(spec, *tail);
1635                 if (ptr == NULL)
1636                         /* unknown specifier */
1637                         goto error;
1638
1639                 ind = ptr - spec;
1640
1641                 /* check if product will overflow the type */
1642                 if (!(v < ULONG_MAX / mult[ind]))
1643                         goto error;
1644
1645                 ADD_OVERFLOW(val, mult[ind] * v);
1646                 if (val == ULONG_MAX)
1647                         goto error;
1648
1649                 timestr = tail + 1;
1650         }
1651
1652         return val;
1653
1654 error:
1655         return ULONG_MAX;
1656 }
1657
1658 #define ARG2ULL(nr, str, defscale)                                      \
1659 do {                                                                    \
1660         unsigned long long limit, units = 0;                            \
1661         int rc;                                                         \
1662                                                                         \
1663         rc = parse_size(str, &limit, &units, 1);                        \
1664         if (rc < 0) {                                                   \
1665                 fprintf(stderr, "error: bad limit value %s\n", str);    \
1666                 return CMD_HELP;                                        \
1667         }                                                               \
1668         nr = ((units == 0) ? (defscale) : 1) * limit;                   \
1669 } while (0)
1670
1671 static inline int has_times_option(int argc, char **argv)
1672 {
1673         int i;
1674
1675         for (i = 1; i < argc; i++)
1676                 if (!strcmp(argv[i], "-t"))
1677                         return 1;
1678
1679         return 0;
1680 }
1681
1682 int lfs_setquota_times(int argc, char **argv)
1683 {
1684         int c, rc;
1685         struct if_quotactl qctl;
1686         char *mnt, *obd_type = (char *)qctl.obd_type;
1687         struct obd_dqblk *dqb = &qctl.qc_dqblk;
1688         struct obd_dqinfo *dqi = &qctl.qc_dqinfo;
1689         struct option long_opts[] = {
1690                 {"user",            no_argument,       0, 'u'},
1691                 {"group",           no_argument,       0, 'g'},
1692                 {"block-grace",     required_argument, 0, 'b'},
1693                 {"inode-grace",     required_argument, 0, 'i'},
1694                 {"times",           no_argument,       0, 't'},
1695                 {0, 0, 0, 0}
1696         };
1697
1698         memset(&qctl, 0, sizeof(qctl));
1699         qctl.qc_cmd  = LUSTRE_Q_SETINFO;
1700         qctl.qc_type = UGQUOTA;
1701
1702         optind = 0;
1703         while ((c = getopt_long(argc, argv, "ugb:i:t", long_opts, NULL)) != -1) {
1704                 switch (c) {
1705                 case 'u':
1706                 case 'g':
1707                         if (qctl.qc_type != UGQUOTA) {
1708                                 fprintf(stderr, "error: -u and -g can't be used "
1709                                                 "more than once\n");
1710                                 return CMD_HELP;
1711                         }
1712                         qctl.qc_type = (c == 'u') ? USRQUOTA : GRPQUOTA;
1713                         break;
1714                 case 'b':
1715                         if ((dqi->dqi_bgrace = str2sec(optarg)) == ULONG_MAX) {
1716                                 fprintf(stderr, "error: bad block-grace: %s\n",
1717                                         optarg);
1718                                 return CMD_HELP;
1719                         }
1720                         dqb->dqb_valid |= QIF_BTIME;
1721                         break;
1722                 case 'i':
1723                         if ((dqi->dqi_igrace = str2sec(optarg)) == ULONG_MAX) {
1724                                 fprintf(stderr, "error: bad inode-grace: %s\n",
1725                                         optarg);
1726                                 return CMD_HELP;
1727                         }
1728                         dqb->dqb_valid |= QIF_ITIME;
1729                         break;
1730                 case 't': /* Yes, of course! */
1731                         break;
1732                 default: /* getopt prints error message for us when opterr != 0 */
1733                         return CMD_HELP;
1734                 }
1735         }
1736
1737         if (qctl.qc_type == UGQUOTA) {
1738                 fprintf(stderr, "error: neither -u nor -g specified\n");
1739                 return CMD_HELP;
1740         }
1741
1742         if (optind != argc - 1) {
1743                 fprintf(stderr, "error: unexpected parameters encountered\n");
1744                 return CMD_HELP;
1745         }
1746
1747         mnt = argv[optind];
1748         rc = llapi_quotactl(mnt, &qctl);
1749         if (rc) {
1750                 if (*obd_type)
1751                         fprintf(stderr, "%s %s ", obd_type,
1752                                 obd_uuid2str(&qctl.obd_uuid));
1753                 fprintf(stderr, "setquota failed: %s\n", strerror(errno));
1754                 return rc;
1755         }
1756
1757         return 0;
1758 }
1759
1760 #define BSLIMIT (1 << 0)
1761 #define BHLIMIT (1 << 1)
1762 #define ISLIMIT (1 << 2)
1763 #define IHLIMIT (1 << 3)
1764
1765 int lfs_setquota(int argc, char **argv)
1766 {
1767         int c, rc;
1768         struct if_quotactl qctl;
1769         char *mnt, *obd_type = (char *)qctl.obd_type;
1770         struct obd_dqblk *dqb = &qctl.qc_dqblk;
1771         struct option long_opts[] = {
1772                 {"user",            required_argument, 0, 'u'},
1773                 {"group",           required_argument, 0, 'g'},
1774                 {"block-softlimit", required_argument, 0, 'b'},
1775                 {"block-hardlimit", required_argument, 0, 'B'},
1776                 {"inode-softlimit", required_argument, 0, 'i'},
1777                 {"inode-hardlimit", required_argument, 0, 'I'},
1778                 {0, 0, 0, 0}
1779         };
1780         unsigned limit_mask = 0;
1781
1782         if (has_times_option(argc, argv))
1783                 return lfs_setquota_times(argc, argv);
1784
1785         memset(&qctl, 0, sizeof(qctl));
1786         qctl.qc_cmd  = LUSTRE_Q_SETQUOTA;
1787         qctl.qc_type = UGQUOTA; /* UGQUOTA makes no sense for setquota,
1788                                  * so it can be used as a marker that qc_type
1789                                  * isn't reinitialized from command line */
1790
1791         optind = 0;
1792         while ((c = getopt_long(argc, argv, "u:g:b:B:i:I:", long_opts, NULL)) != -1) {
1793                 switch (c) {
1794                 case 'u':
1795                 case 'g':
1796                         if (qctl.qc_type != UGQUOTA) {
1797                                 fprintf(stderr, "error: -u and -g can't be used"
1798                                                 " more than once\n");
1799                                 return CMD_HELP;
1800                         }
1801                         qctl.qc_type = (c == 'u') ? USRQUOTA : GRPQUOTA;
1802                         rc = name2id(&qctl.qc_id, optarg,
1803                                      (qctl.qc_type == USRQUOTA) ? USER : GROUP);
1804                         if (rc) {
1805                                 fprintf(stderr, "error: unknown id %s\n",
1806                                         optarg);
1807                                 return CMD_HELP;
1808                         }
1809                         break;
1810                 case 'b':
1811                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
1812                         dqb->dqb_bsoftlimit >>= 10;
1813                         limit_mask |= BSLIMIT;
1814                         break;
1815                 case 'B':
1816                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
1817                         dqb->dqb_bhardlimit >>= 10;
1818                         limit_mask |= BHLIMIT;
1819                         break;
1820                 case 'i':
1821                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
1822                         limit_mask |= ISLIMIT;
1823                         break;
1824                 case 'I':
1825                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
1826                         limit_mask |= IHLIMIT;
1827                         break;
1828                 default: /* getopt prints error message for us when opterr != 0 */
1829                         return CMD_HELP;
1830                 }
1831         }
1832
1833         if (qctl.qc_type == UGQUOTA) {
1834                 fprintf(stderr, "error: neither -u nor -g are specified\n");
1835                 return CMD_HELP;
1836         }
1837
1838         if (optind != argc - 1) {
1839                 fprintf(stderr, "error: unexpected parameters encountered\n");
1840                 return CMD_HELP;
1841         }
1842
1843         mnt = argv[optind];
1844
1845         if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
1846             (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
1847                 /* sigh, we can't just set blimits/ilimits */
1848                 struct if_quotactl tmp_qctl = {.qc_cmd  = LUSTRE_Q_GETQUOTA,
1849                                                .qc_type = qctl.qc_type,
1850                                                .qc_id   = qctl.qc_id};
1851
1852                 rc = llapi_quotactl(mnt, &tmp_qctl);
1853                 if (rc < 0) {
1854                         fprintf(stderr, "error: getquota failed\n");
1855                         return CMD_HELP;
1856                 }
1857
1858                 if (!(limit_mask & BHLIMIT))
1859                         dqb->dqb_bhardlimit = tmp_qctl.qc_dqblk.dqb_bhardlimit;
1860                 if (!(limit_mask & BSLIMIT))
1861                         dqb->dqb_bsoftlimit = tmp_qctl.qc_dqblk.dqb_bsoftlimit;
1862                 if (!(limit_mask & IHLIMIT))
1863                         dqb->dqb_ihardlimit = tmp_qctl.qc_dqblk.dqb_ihardlimit;
1864                 if (!(limit_mask & ISLIMIT))
1865                         dqb->dqb_isoftlimit = tmp_qctl.qc_dqblk.dqb_isoftlimit;
1866         }
1867
1868         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
1869         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
1870
1871         rc = llapi_quotactl(mnt, &qctl);
1872         if (rc) {
1873                 if (*obd_type)
1874                         fprintf(stderr, "%s %s ", obd_type,
1875                                 obd_uuid2str(&qctl.obd_uuid));
1876                 fprintf(stderr, "setquota failed: %s\n", strerror(errno));
1877                 return rc;
1878         }
1879
1880         return 0;
1881 }
1882
1883 static inline char *type2name(int check_type)
1884 {
1885         if (check_type == USRQUOTA)
1886                 return "user";
1887         else if (check_type == GRPQUOTA)
1888                 return "group";
1889         else
1890                 return "unknown";
1891 }
1892
1893
1894 /* Converts seconds value into format string
1895  * result is returned in buf
1896  * Notes:
1897  *        1. result is in descenting order: 1w2d3h4m5s
1898  *        2. zero fields are not filled (except for p. 3): 5d1s
1899  *        3. zero seconds value is presented as "0s"
1900  */
1901 static void sec2str(time_t seconds, char *buf)
1902 {
1903         const char spec[] = "smhdw";
1904         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
1905         unsigned long c;
1906         char* tail = buf;
1907         int i;
1908
1909         for (i = sizeof(mult) / sizeof(mult[0]) - 1 ; i >= 0; i--) {
1910                 c = seconds / mult[i];
1911
1912                 if (c > 0 || (i == 0 && buf == tail))
1913                         tail += snprintf(tail, 40-(tail-buf), "%lu%c", c, spec[i]);
1914
1915                 seconds %= mult[i];
1916         }
1917 }
1918
1919
1920 static void diff2str(time_t seconds, char *buf, time_t now)
1921 {
1922
1923         buf[0] = 0;
1924         if (!seconds)
1925                 return;
1926         if (seconds <= now) {
1927                 strcpy(buf, "none");
1928                 return;
1929         }
1930         sec2str(seconds - now, buf);
1931 }
1932
1933 static void print_quota_title(char *name, struct if_quotactl *qctl)
1934 {
1935         printf("Disk quotas for %s %s (%cid %u):\n",
1936                type2name(qctl->qc_type), name,
1937                *type2name(qctl->qc_type), qctl->qc_id);
1938         printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
1939                "Filesystem",
1940                "kbytes", "quota", "limit", "grace",
1941                "files", "quota", "limit", "grace");
1942 }
1943
1944 static void print_quota(char *mnt, struct if_quotactl *qctl, int type)
1945 {
1946         time_t now;
1947
1948         time(&now);
1949
1950         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA) {
1951                 int bover = 0, iover = 0;
1952                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
1953
1954                 if (dqb->dqb_bhardlimit &&
1955                     toqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
1956                         bover = 1;
1957                 } else if (dqb->dqb_bsoftlimit &&
1958                            toqb(dqb->dqb_curspace) >= dqb->dqb_bsoftlimit) {
1959                         if (dqb->dqb_btime > now) {
1960                                 bover = 2;
1961                         } else {
1962                                 bover = 3;
1963                         }
1964                 }
1965
1966                 if (dqb->dqb_ihardlimit &&
1967                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
1968                         iover = 1;
1969                 } else if (dqb->dqb_isoftlimit &&
1970                            dqb->dqb_curinodes >= dqb->dqb_isoftlimit) {
1971                         if (dqb->dqb_btime > now) {
1972                                 iover = 2;
1973                         } else {
1974                                 iover = 3;
1975                         }
1976                 }
1977
1978 #if 0           /* XXX: always print quotas even when no usages */
1979                 if (dqb->dqb_curspace || dqb->dqb_curinodes)
1980 #endif
1981                 {
1982                         char numbuf[3][32];
1983                         char timebuf[40];
1984
1985                         if (strlen(mnt) > 15)
1986                                 printf("%s\n%15s", mnt, "");
1987                         else
1988                                 printf("%15s", mnt);
1989
1990                         if (bover)
1991                                 diff2str(dqb->dqb_btime, timebuf, now);
1992                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
1993                                 LPU64 : "["LPU64"]", toqb(dqb->dqb_curspace));
1994                         if (type == QC_GENERAL)
1995                                 sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS)
1996                                         ? LPU64 : "["LPU64"]",
1997                                         dqb->dqb_bsoftlimit);
1998                         else
1999                                 sprintf(numbuf[1], "%s", "");
2000                         sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS)
2001                                 ? LPU64 : "["LPU64"]", dqb->dqb_bhardlimit);
2002                         printf(" %7s%c %6s %7s %7s",
2003                                numbuf[0], bover ? '*' : ' ', numbuf[1],
2004                                numbuf[2], bover > 1 ? timebuf : "");
2005
2006                         if (iover)
2007                                 diff2str(dqb->dqb_itime, timebuf, now);
2008
2009                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_INODES) ?
2010                                 LPU64 : "["LPU64"]", dqb->dqb_curinodes);
2011                        if (type == QC_GENERAL)
2012                                 sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS)
2013                                         ? LPU64 : "["LPU64"]",
2014                                         dqb->dqb_isoftlimit);
2015                         else
2016                                 sprintf(numbuf[1], "%s", "");
2017                         sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
2018                                 LPU64 : "["LPU64"]", dqb->dqb_ihardlimit);
2019                         if (type != QC_OSTIDX)
2020                                 printf(" %7s%c %6s %7s %7s",
2021                                        numbuf[0], iover ? '*' : ' ', numbuf[1],
2022                                        numbuf[2], iover > 1 ? timebuf : "");
2023                         printf("\n");
2024                 }
2025         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO ||
2026                    qctl->qc_cmd == Q_GETOINFO) {
2027                 char bgtimebuf[40];
2028                 char igtimebuf[40];
2029
2030                 sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf);
2031                 sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf);
2032                 printf("Block grace time: %s; Inode grace time: %s\n",
2033                        bgtimebuf, igtimebuf);
2034         }
2035 }
2036
2037 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt)
2038 {
2039         int rc = 0, rc1 = 0, count = 0;
2040         __u32 valid = qctl->qc_valid;
2041
2042         rc = llapi_get_obd_count(mnt, &count, is_mdt);
2043         if (rc) {
2044                 fprintf(stderr, "can not get %s count: %s\n",
2045                         is_mdt ? "mdt": "ost", strerror(errno));
2046                 return rc;
2047         }
2048
2049         for (qctl->qc_idx = 0; qctl->qc_idx < count; qctl->qc_idx++) {
2050                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
2051                 rc = llapi_quotactl(mnt, qctl);
2052                 if (rc) {
2053                         /* It is remote client case. */
2054                         if (errno == EOPNOTSUPP) {
2055                                 rc = 0;
2056                                 goto out;
2057                         }
2058
2059                         if (!rc1)
2060                                 rc1 = rc;
2061                         fprintf(stderr, "quotactl %s%d failed.\n",
2062                                 is_mdt ? "mdt": "ost", qctl->qc_idx);
2063                         continue;
2064                 }
2065
2066                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl, qctl->qc_valid);
2067         }
2068
2069 out:
2070         qctl->qc_valid = valid;
2071         return rc ? : rc1;
2072 }
2073
2074 static int lfs_quota(int argc, char **argv)
2075 {
2076         int c;
2077         char *mnt, *name = NULL;
2078         struct if_quotactl qctl = { .qc_cmd = LUSTRE_Q_GETQUOTA,
2079                                     .qc_type = UGQUOTA };
2080         char *obd_type = (char *)qctl.obd_type;
2081         char *obd_uuid = (char *)qctl.obd_uuid.uuid;
2082         int rc, rc1 = 0, rc2 = 0, rc3 = 0, verbose = 0, pass = 0;
2083         __u32 valid = QC_GENERAL, idx = 0;
2084
2085         optind = 0;
2086         while ((c = getopt(argc, argv, "ugto:i:I:v")) != -1) {
2087                 switch (c) {
2088                 case 'u':
2089                         if (qctl.qc_type != UGQUOTA) {
2090                                 fprintf(stderr, "error: use either -u or -g\n");
2091                                 return CMD_HELP;
2092                         }
2093                         qctl.qc_type = USRQUOTA;
2094                         break;
2095                 case 'g':
2096                         if (qctl.qc_type != UGQUOTA) {
2097                                 fprintf(stderr, "error: use either -u or -g\n");
2098                                 return CMD_HELP;
2099                         }
2100                         qctl.qc_type = GRPQUOTA;
2101                         break;
2102                 case 't':
2103                         qctl.qc_cmd = LUSTRE_Q_GETINFO;
2104                         break;
2105                 case 'o':
2106                         valid = qctl.qc_valid = QC_UUID;
2107                         strncpy(obd_uuid, optarg, sizeof(qctl.obd_uuid));
2108                         break;
2109                 case 'i':
2110                         valid = qctl.qc_valid = QC_MDTIDX;
2111                         idx = qctl.qc_idx = atoi(optarg);
2112                         break;
2113                 case 'I':
2114                         valid = qctl.qc_valid = QC_OSTIDX;
2115                         idx = qctl.qc_idx = atoi(optarg);
2116                         break;
2117                 case 'v':
2118                         verbose = 1;
2119                         break;
2120                 default:
2121                         fprintf(stderr, "error: %s: option '-%c' "
2122                                         "unrecognized\n", argv[0], c);
2123                         return CMD_HELP;
2124                 }
2125         }
2126
2127         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
2128         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA && qctl.qc_type == UGQUOTA &&
2129             optind == argc - 1) {
2130 ug_output:
2131                 memset(&qctl, 0, sizeof(qctl)); /* spoiled by print_*_quota */
2132                 qctl.qc_cmd = LUSTRE_Q_GETQUOTA;
2133                 qctl.qc_valid = valid;
2134                 qctl.qc_idx = idx;
2135                 if (pass++ == 0) {
2136                         qctl.qc_type = USRQUOTA;
2137                         qctl.qc_id = geteuid();
2138                 } else {
2139                         qctl.qc_type = GRPQUOTA;
2140                         qctl.qc_id = getegid();
2141                 }
2142                 rc = id2name(&name, qctl.qc_id,
2143                              (qctl.qc_type == USRQUOTA) ? USER : GROUP);
2144                 if (rc)
2145                         name = "<unknown>";
2146         } else if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) {
2147                 if (optind + 2 != argc) {
2148                         fprintf(stderr, "error: missing quota argument(s)\n");
2149                         return CMD_HELP;
2150                 }
2151
2152                 name = argv[optind++];
2153                 rc = name2id(&qctl.qc_id, name,
2154                              (qctl.qc_type == USRQUOTA) ? USER : GROUP);
2155                 if (rc) {
2156                         fprintf(stderr,"error: can't find id for name %s: %s\n",
2157                                 name, strerror(errno));
2158                         return CMD_HELP;
2159                 }
2160         } else if (optind + 1 != argc) {
2161                 fprintf(stderr, "error: missing quota info argument(s)\n");
2162                 return CMD_HELP;
2163         }
2164
2165         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA)
2166                 print_quota_title(name, &qctl);
2167
2168         mnt = argv[optind];
2169
2170         rc1 = llapi_quotactl(mnt, &qctl);
2171         if (rc1 == -1 && errno == ESRCH) {
2172                 fprintf(stderr, "\n%s quotas are not enabled.\n",
2173                         qctl.qc_type == USRQUOTA ? "user" : "group");
2174                 goto out;
2175         }
2176         if (rc1 && *obd_type)
2177                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
2178
2179         if (qctl.qc_valid != QC_GENERAL)
2180                 mnt = "";
2181
2182         print_quota(mnt, &qctl, QC_GENERAL);
2183
2184         if (qctl.qc_valid == QC_GENERAL && qctl.qc_cmd != LUSTRE_Q_GETINFO && verbose) {
2185                 rc2 = print_obd_quota(mnt, &qctl, 1);
2186                 rc3 = print_obd_quota(mnt, &qctl, 0);
2187         }
2188
2189         if (rc1 || rc2 || rc3)
2190                 printf("Some errors happened when getting quota info. "
2191                        "Some devices may be not working or deactivated. "
2192                        "The data in \"[]\" is inaccurate.\n");
2193
2194 out:
2195         if (pass == 1)
2196                 goto ug_output;
2197
2198         return 0;
2199 }
2200 #endif /* HAVE_SYS_QUOTA_H! */
2201
2202 static int flushctx_ioctl(char *mp)
2203 {
2204         int fd, rc;
2205
2206         fd = open(mp, O_RDONLY);
2207         if (fd == -1) {
2208                 fprintf(stderr, "flushctx: error open %s: %s\n",
2209                         mp, strerror(errno));
2210                 return -1;
2211         }
2212
2213         rc = ioctl(fd, LL_IOC_FLUSHCTX);
2214         if (rc == -1)
2215                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
2216                         mp, strerror(errno));
2217
2218         close(fd);
2219         return rc;
2220 }
2221
2222 static int lfs_flushctx(int argc, char **argv)
2223 {
2224         int     kdestroy = 0, c;
2225         FILE   *proc;
2226         char    procline[PATH_MAX], *line;
2227         int     rc = 0;
2228
2229         optind = 0;
2230         while ((c = getopt(argc, argv, "k")) != -1) {
2231                 switch (c) {
2232                 case 'k':
2233                         kdestroy = 1;
2234                         break;
2235                 default:
2236                         fprintf(stderr, "error: %s: option '-%c' "
2237                                         "unrecognized\n", argv[0], c);
2238                         return CMD_HELP;
2239                 }
2240         }
2241
2242         if (kdestroy)
2243                 system("kdestroy > /dev/null");
2244
2245         if (optind >= argc) {
2246                 /* flush for all mounted lustre fs. */
2247                 proc = fopen("/proc/mounts", "r");
2248                 if (!proc) {
2249                         fprintf(stderr, "error: %s: can't open /proc/mounts\n",
2250                                 argv[0]);
2251                         return -1;
2252                 }
2253
2254                 while ((line = fgets(procline, PATH_MAX, proc)) != NULL) {
2255                         char dev[PATH_MAX];
2256                         char mp[PATH_MAX];
2257                         char fs[PATH_MAX];
2258
2259                         if (sscanf(line, "%s %s %s", dev, mp, fs) != 3) {
2260                                 fprintf(stderr, "%s: unexpected format in "
2261                                                 "/proc/mounts\n",
2262                                         argv[0]);
2263                                 return -1;
2264                         }
2265
2266                         if (strcmp(fs, "lustre") != 0)
2267                                 continue;
2268                         /* we use '@' to determine it's a client. are there
2269                          * any other better way?
2270                          */
2271                         if (strchr(dev, '@') == NULL)
2272                                 continue;
2273
2274                         if (flushctx_ioctl(mp))
2275                                 rc = -1;
2276                 }
2277         } else {
2278                 /* flush fs as specified */
2279                 while (optind < argc) {
2280                         if (flushctx_ioctl(argv[optind++]))
2281                                 rc = -1;
2282                 }
2283         }
2284
2285         return rc;
2286 }
2287
2288 static int lfs_lsetfacl(int argc, char **argv)
2289 {
2290         argv[0]++;
2291         return(llapi_lsetfacl(argc, argv));
2292 }
2293
2294 static int lfs_lgetfacl(int argc, char **argv)
2295 {
2296         argv[0]++;
2297         return(llapi_lgetfacl(argc, argv));
2298 }
2299
2300 static int lfs_rsetfacl(int argc, char **argv)
2301 {
2302         argv[0]++;
2303         return(llapi_rsetfacl(argc, argv));
2304 }
2305
2306 static int lfs_rgetfacl(int argc, char **argv)
2307 {
2308         argv[0]++;
2309         return(llapi_rgetfacl(argc, argv));
2310 }
2311
2312 static int lfs_cp(int argc, char **argv)
2313 {
2314         return(llapi_cp(argc, argv));
2315 }
2316
2317 static int lfs_ls(int argc, char **argv)
2318 {
2319         return(llapi_ls(argc, argv));
2320 }
2321
2322 /* A helper function to return single, whole lines delimited by newline.
2323    Returns length of line.  Not reentrant! */
2324 static int get_next_full_line(int fd, char **ptr)
2325 {
2326         static char buf[8192]; /* bigger than MAX_PATH_LENGTH */
2327         static char *sptr = buf, *eptr = buf;
2328         static int len, rem;
2329
2330         if ((*ptr == NULL) /* first time */
2331             || (eptr >= buf + len) /* buffer empty */) {
2332                 sptr = eptr = buf;
2333                 len = read(fd, buf, sizeof(buf));
2334                 if (len <= 0)
2335                         return len;
2336         } else {
2337                 sptr = eptr + 1;
2338         }
2339
2340 full_line:
2341         while (eptr < buf + len) {
2342                 eptr++;
2343                 /* parse full lines */
2344                 if (*eptr == '\n') {
2345                         *eptr = '\0';
2346                         *ptr = sptr;
2347                         return (eptr - sptr);
2348                 }
2349         }
2350
2351         /* partial line; move to front of buf */
2352         rem = buf + len - sptr;
2353         memcpy(buf, sptr, rem);
2354         sptr = buf;
2355         eptr = buf + rem;
2356         len = read(fd, eptr, sizeof(buf) - rem);
2357         if (len <= 0)
2358                 return len;
2359         len += rem;
2360         goto full_line;
2361 }
2362
2363 static int lfs_changelog(int argc, char **argv)
2364 {
2365         long long startrec = 0, endrec = 0, recnum;
2366         int fd, len;
2367         char c, *mdd, *ptr = NULL;
2368         struct option long_opts[] = {
2369                 {"follow", 0, 0, 'f'},
2370                 {0, 0, 0, 0}
2371         };
2372         char short_opts[] = "f";
2373         int follow = 0;
2374
2375         optind = 0;
2376         while ((c = getopt_long(argc, argv, short_opts,
2377                                 long_opts, NULL)) != -1) {
2378                 switch (c) {
2379                 case 'f':
2380                         follow++;
2381                         break;
2382                 case '?':
2383                         return CMD_HELP;
2384                 default:
2385                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
2386                                 argv[0], argv[optind - 1]);
2387                         return CMD_HELP;
2388                 }
2389         }
2390         if (optind >= argc)
2391                 return CMD_HELP;
2392
2393         mdd = argv[optind++];
2394         if (argc > optind)
2395                 startrec = strtoll(argv[optind++], NULL, 10);
2396         if (argc > optind)
2397                 endrec = strtoll(argv[optind++], NULL, 10);
2398
2399         fd = llapi_changelog_open(mdd, startrec);
2400         if (fd < 0)
2401                 return fd;
2402
2403         while ((len = get_next_full_line(fd, &ptr)) >= 0) {
2404                 if (len == 0) {
2405                         struct pollfd pfds[1];
2406                         int rc;
2407
2408                         if (!follow)
2409                                 break;
2410                         pfds[0].fd = fd;
2411                         pfds[0].events = POLLIN;
2412                         rc = poll(pfds, 1, -1);
2413                         if (rc < 0)
2414                                 break;
2415                         continue;
2416                 }
2417      /* eg. 2 02MKDIR 4405821890 t=[0x100000400/0x5] p=[0x100000400/0x4] pics */
2418                 sscanf(ptr, "%lld *", &recnum);
2419                 if (endrec && recnum > endrec)
2420                         break;
2421                 if (recnum < startrec)
2422                         continue;
2423                 printf("%.*s\n", len, ptr);
2424         }
2425
2426         close(fd);
2427
2428         if (len < 0) {
2429                 printf("read err %d\n", errno);
2430                 return -errno;
2431         }
2432
2433         return 0;
2434 }
2435
2436 static int lfs_changelog_clear(int argc, char **argv)
2437 {
2438         long long endrec;
2439
2440         if (argc != 3)
2441                 return CMD_HELP;
2442
2443         endrec = strtoll(argv[2], NULL, 10);
2444
2445         return(llapi_changelog_clear(argv[1], endrec));
2446 }
2447
2448 static int lfs_fid2path(int argc, char **argv)
2449 {
2450         struct option long_opts[] = {
2451                 {"link", 1, 0, 'l'},
2452                 {"rec", 1, 0, 'r'},
2453                 {0, 0, 0, 0}
2454         };
2455         char c, short_opts[] = "l:r:";
2456         char *device, *fid, *path;
2457         long long recno = -1;
2458         int linkno = -1;
2459         int lnktmp;
2460         int rc;
2461
2462         optind = 0;
2463         while ((c = getopt_long(argc, argv, short_opts,
2464                                 long_opts, NULL)) != -1) {
2465                 switch (c) {
2466                 case 'l':
2467                         linkno = strtol(optarg, NULL, 10);
2468                         break;
2469                 case 'r':
2470                         recno = strtoll(optarg, NULL, 10);
2471                         break;
2472                 case '?':
2473                         return CMD_HELP;
2474                 default:
2475                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
2476                                 argv[0], argv[optind - 1]);
2477                         return CMD_HELP;
2478                 }
2479         }
2480
2481         device = argv[optind++];
2482         fid = argv[optind++];
2483         if (optind != argc)
2484                 return CMD_HELP;
2485
2486         path = calloc(1, PATH_MAX);
2487
2488         lnktmp = (linkno >= 0) ? linkno : 0;
2489         while (1) {
2490                 int oldtmp = lnktmp;
2491                 rc = llapi_fid2path(device, fid, path, PATH_MAX, recno,
2492                                     &lnktmp);
2493                 if (rc < 0) {
2494                         fprintf(stderr, "%s error: %s\n", argv[0],
2495                                 strerror(errno = -rc));
2496                         break;
2497                 } else {
2498                         fprintf(stdout, "%s\n", path);
2499                 }
2500                 if (linkno >= 0)
2501                         /* specified linkno */
2502                         break;
2503                 if (oldtmp == lnktmp)
2504                         /* no more links */
2505                         break;
2506         }
2507
2508         free(path);
2509         return rc;
2510 }
2511
2512 static int lfs_path2fid(int argc, char **argv)
2513 {
2514         char *path;
2515         unsigned long long seq;
2516         unsigned long oid, ver;
2517         int rc;
2518
2519         if (argc != 2)
2520                 return CMD_HELP;
2521
2522         path = argv[1];
2523         rc = llapi_path2fid(path, &seq, &oid, &ver);
2524         if (rc) {
2525                 fprintf(stderr, "can't get fid for %s: %s\n", path,
2526                         strerror(errno = -rc));
2527                 return rc;
2528         }
2529
2530         printf(DFID"\n", seq, (unsigned int)oid, (unsigned int)ver);
2531
2532         return 0;
2533 }
2534
2535 int main(int argc, char **argv)
2536 {
2537         int rc;
2538
2539         setlinebuf(stdout);
2540
2541         ptl_initialize(argc, argv);
2542         if (obd_initialize(argc, argv) < 0)
2543                 exit(2);
2544         if (dbg_initialize(argc, argv) < 0)
2545                 exit(3);
2546
2547         Parser_init("lfs > ", cmdlist);
2548
2549         if (argc > 1) {
2550                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
2551         } else {
2552                 rc = Parser_commands();
2553         }
2554
2555         obd_finalize(argc, argv);
2556         return rc;
2557 }
2558