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