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