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