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