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