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