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