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