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