Whamcloud - gitweb
LU-611 utils: lfs find --stripe-{count,size,index}
[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                 {"obd",          required_argument, 0, 'O'},
587                 {"ost",          required_argument, 0, 'O'},
588                 /* no short option for pool, p/P already used */
589                 {"pool",         required_argument, 0, FIND_POOL_OPT},
590                 {"print0",       no_argument,       0, 'p'},
591                 {"print",        no_argument,       0, 'P'},
592                 {"size",         required_argument, 0, 's'},
593                 {"stripe-size",  required_argument, 0, 'S'},
594                 {"stripe_size",  required_argument, 0, 'S'},
595                 {"type",         required_argument, 0, 't'},
596                 {"uid",          required_argument, 0, 'u'},
597                 {"user",         required_argument, 0, 'U'},
598                 {0, 0, 0, 0}
599         };
600         int pathstart = -1;
601         int pathend = -1;
602         int neg_opt = 0;
603         time_t *xtime;
604         int *xsign;
605         int isoption;
606         char *endptr;
607
608         time(&t);
609
610         optind = 0;
611         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
612         while ((c = getopt_long_only(argc, argv,
613                                      "-A:c:C:D:g:G:i:m:M:n:O:Ppqrs:S:t:u:U:v",
614                                      long_opts, NULL)) >= 0) {
615                 xtime = NULL;
616                 xsign = NULL;
617                 if (neg_opt)
618                         --neg_opt;
619                 /* '!' is part of option */
620                 /* when getopt_long_only() finds a string which is not
621                  * an option nor a known option argument it returns 1
622                  * in that case if we already have found pathstart and pathend
623                  * (i.e. we have the list of pathnames),
624                  * the only supported value is "!"
625                  */
626                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
627                 if (!isoption && pathend != -1) {
628                         fprintf(stderr, "err: %s: filename|dirname must either "
629                                         "precede options or follow options\n",
630                                         argv[0]);
631                         ret = CMD_HELP;
632                         goto err;
633                 }
634                 if (!isoption && pathstart == -1)
635                         pathstart = optind - 1;
636                 if (isoption && pathstart != -1 && pathend == -1)
637                         pathend = optind - 2;
638                 switch (c) {
639                 case 0:
640                         /* Long options. */
641                         break;
642                 case 1:
643                         /* unknown; opt is "!" or path component,
644                          * checking done above.
645                          */
646                         if (strcmp(optarg, "!") == 0)
647                                 neg_opt = 2;
648                         break;
649                 case 'A':
650                         xtime = &param.atime;
651                         xsign = &param.asign;
652                         param.exclude_atime = !!neg_opt;
653                         /* no break, this falls through to 'C' for ctime */
654                 case 'C':
655                         if (c == 'C') {
656                                 xtime = &param.ctime;
657                                 xsign = &param.csign;
658                                 param.exclude_ctime = !!neg_opt;
659                         }
660                         /* no break, this falls through to 'M' for mtime */
661                 case 'M':
662                         if (c == 'M') {
663                                 xtime = &param.mtime;
664                                 xsign = &param.msign;
665                                 param.exclude_mtime = !!neg_opt;
666                         }
667                         ret = set_time(&t, xtime, optarg);
668                         if (ret == INT_MAX) {
669                                 ret = -1;
670                                 goto err;
671                         }
672                         if (ret)
673                                 *xsign = ret;
674                         break;
675                 case 'c':
676                         if (optarg[0] == '+') {
677                                 param.stripecount_sign = -1;
678                                 optarg++;
679                         } else if (optarg[0] == '-') {
680                                 param.stripecount_sign =  1;
681                                 optarg++;
682                         }
683
684                         param.stripecount = strtoul(optarg, &endptr, 0);
685                         if (*endptr != '\0') {
686                                 fprintf(stderr,"error: bad stripe_count '%s'\n",
687                                         optarg);
688                                 ret = -1;
689                                 goto err;
690                         }
691                         param.check_stripecount = 1;
692                         param.exclude_stripecount = !!neg_opt;
693                         break;
694                 case 'D':
695                         param.maxdepth = strtol(optarg, 0, 0);
696                         break;
697                 case 'g':
698                 case 'G':
699                         ret = name2id(&param.gid, optarg, GROUP);
700                         if (ret) {
701                                 param.gid = strtoul(optarg, &endptr, 10);
702                                 if (*endptr != '\0') {
703                                         fprintf(stderr, "Group/GID: %s cannot "
704                                                 "be found.\n", optarg);
705                                         ret = -1;
706                                         goto err;
707                                 }
708                         }
709                         param.exclude_gid = !!neg_opt;
710                         param.check_gid = 1;
711                         break;
712                 case 'u':
713                 case 'U':
714                         ret = name2id(&param.uid, optarg, USER);
715                         if (ret) {
716                                 param.uid = strtoul(optarg, &endptr, 10);
717                                 if (*endptr != '\0') {
718                                         fprintf(stderr, "User/UID: %s cannot "
719                                                 "be found.\n", optarg);
720                                         ret = -1;
721                                         goto err;
722                                 }
723                         }
724                         param.exclude_uid = !!neg_opt;
725                         param.check_uid = 1;
726                         break;
727                 case FIND_POOL_OPT:
728                         if (strlen(optarg) > LOV_MAXPOOLNAME) {
729                                 fprintf(stderr,
730                                         "Pool name %s is too long"
731                                         " (max is %d)\n", optarg,
732                                         LOV_MAXPOOLNAME);
733                                 ret = -1;
734                                 goto err;
735                         }
736                         /* we do check for empty pool because empty pool
737                          * is used to find V1 lov attributes */
738                         strncpy(param.poolname, optarg, LOV_MAXPOOLNAME);
739                         param.poolname[LOV_MAXPOOLNAME] = '\0';
740                         param.exclude_pool = !!neg_opt;
741                         param.check_pool = 1;
742                         break;
743                 case 'n':
744                         param.pattern = (char *)optarg;
745                         param.exclude_pattern = !!neg_opt;
746                         break;
747                 case 'm':
748                 case 'i':
749                 case 'O': {
750                         char *buf, *token, *next, *p;
751                         int len = 1;
752                         void *tmp;
753
754                         buf = strdup(optarg);
755                         if (buf == NULL) {
756                                 ret = -ENOMEM;
757                                 goto err;
758                         }
759
760                         param.exclude_obd = !!neg_opt;
761
762                         token = buf;
763                         while (token && *token) {
764                                 token = strchr(token, ',');
765                                 if (token) {
766                                         len++;
767                                         token++;
768                                 }
769                         }
770                         if (c == 'm') {
771                                 param.exclude_mdt = !!neg_opt;
772                                 param.num_alloc_mdts += len;
773                                 tmp = realloc(param.mdtuuid,
774                                               param.num_alloc_mdts *
775                                               sizeof(*param.mdtuuid));
776                                 if (tmp == NULL)
777                                         GOTO(err_free, ret = -ENOMEM);
778                                 param.mdtuuid = tmp;
779                         } else {
780                                 param.exclude_obd = !!neg_opt;
781                                 param.num_alloc_obds += len;
782                                 tmp = realloc(param.obduuid,
783                                               param.num_alloc_obds *
784                                               sizeof(*param.obduuid));
785                                 if (tmp == NULL)
786                                         GOTO(err_free, ret = -ENOMEM);
787                                 param.obduuid = tmp;
788                         }
789                         for (token = buf; token && *token; token = next) {
790                                 char *uuid;
791                                 if (c == 'm')
792                                         uuid =
793                                           param.mdtuuid[param.num_mdts++].uuid;
794                                 else
795                                         uuid =
796                                           param.obduuid[param.num_obds++].uuid;
797                                 p = strchr(token, ',');
798                                 next = 0;
799                                 if (p) {
800                                         *p = 0;
801                                         next = p+1;
802                                 }
803                                 strcpy((char *)uuid, token);
804                         }
805 err_free:
806                         if (buf)
807                                 free(buf);
808                         break;
809                 }
810                 case 'p':
811                         param.zeroend = 1;
812                         break;
813                 case 'P':
814                         break;
815                 case 's':
816                         if (optarg[0] == '+') {
817                                 param.size_sign = -1;
818                                 optarg++;
819                         } else if (optarg[0] == '-') {
820                                 param.size_sign =  1;
821                                 optarg++;
822                         }
823
824                         ret = parse_size(optarg, &param.size,
825                                          &param.size_units, 0);
826                         if (ret) {
827                                 fprintf(stderr, "error: bad file size '%s'\n",
828                                         optarg);
829                                 goto err;
830                         }
831                         param.check_size = 1;
832                         param.exclude_size = !!neg_opt;
833                         break;
834                 case 'S':
835                         if (optarg[0] == '+') {
836                                 param.stripesize_sign = -1;
837                                 optarg++;
838                         } else if (optarg[0] == '-') {
839                                 param.stripesize_sign =  1;
840                                 optarg++;
841                         }
842
843                         ret = parse_size(optarg, &param.stripesize,
844                                          &param.stripesize_units, 0);
845                         if (ret) {
846                                 fprintf(stderr, "error: bad stripe_size '%s'\n",
847                                         optarg);
848                                 goto err;
849                         }
850                         param.check_stripesize = 1;
851                         param.exclude_stripesize = !!neg_opt;
852                         break;
853                 case 't':
854                         param.exclude_type = !!neg_opt;
855                         switch(optarg[0]) {
856                         case 'b': param.type = S_IFBLK; break;
857                         case 'c': param.type = S_IFCHR; break;
858                         case 'd': param.type = S_IFDIR; break;
859                         case 'f': param.type = S_IFREG; break;
860                         case 'l': param.type = S_IFLNK; break;
861                         case 'p': param.type = S_IFIFO; break;
862                         case 's': param.type = S_IFSOCK; break;
863 #ifdef S_IFDOOR /* Solaris only */
864                         case 'D': param.type = S_IFDOOR; break;
865 #endif
866                         default: fprintf(stderr, "error: %s: bad type '%s'\n",
867                                          argv[0], optarg);
868                                  ret = CMD_HELP;
869                                  goto err;
870                         };
871                         break;
872                 default:
873                         ret = CMD_HELP;
874                         goto err;
875                 };
876         }
877
878         if (pathstart == -1) {
879                 fprintf(stderr, "error: %s: no filename|pathname\n",
880                         argv[0]);
881                 ret = CMD_HELP;
882                 goto err;
883         } else if (pathend == -1) {
884                 /* no options */
885                 pathend = argc;
886         }
887
888         do {
889                 ret = llapi_find(argv[pathstart], &param);
890         } while (++pathstart < pathend && !ret);
891
892         if (ret)
893                 fprintf(stderr, "error: %s failed for %s.\n",
894                         argv[0], argv[optind - 1]);
895 err:
896         if (param.obduuid && param.num_alloc_obds)
897                 free(param.obduuid);
898
899         if (param.mdtuuid && param.num_alloc_mdts)
900                 free(param.mdtuuid);
901
902         return ret;
903 }
904
905 static int lfs_getstripe(int argc, char **argv)
906 {
907         struct option long_opts[] = {
908 #if LUSTRE_VERSION >= OBD_OCD_VERSION(2,9,50,0)
909 #warning "remove deprecated --count option"
910 #else
911                 /* This formerly implied "stripe-count", but was explicitly
912                  * made "stripe-count" for consistency with other options,
913                  * and to separate it from "mdt-count" when DNE arrives. */
914                 {"count",        no_argument,       0, 'c'},
915 #endif
916                 {"stripe-count", no_argument,       0, 'c'},
917                 {"stripe_count", no_argument,       0, 'c'},
918                 {"directory",    no_argument,       0, 'd'},
919                 {"generation",   no_argument,       0, 'g'},
920 #if LUSTRE_VERSION >= OBD_OCD_VERSION(2,9,50,0)
921 #warning "remove deprecated --index option"
922 #else
923                 /* This formerly implied "stripe-index", but was explicitly
924                  * made "stripe-index" for consistency with other options,
925                  * and to separate it from "mdt-index" when DNE arrives. */
926                 {"index",        no_argument,       0, 'i'},
927 #endif
928                 {"stripe-index", no_argument,       0, 'i'},
929                 {"stripe_index", no_argument,       0, 'i'},
930                 {"mdt-index",    no_argument,       0, 'M'},
931                 {"mdt_index",    no_argument,       0, 'M'},
932 #if LUSTRE_VERSION >= OBD_OCD_VERSION(2,9,50,0)
933 #warning "remove deprecated --offset option"
934 #else
935                 /* This formerly implied "stripe-index", but was confusing
936                  * with "file offset" (which will eventually be needed for
937                  * with different layouts by offset), so deprecate it. */
938                 {"offset",       no_argument,       0, 'o'},
939 #endif
940                 {"obd",          required_argument, 0, 'O'},
941                 {"ost",          required_argument, 0, 'O'},
942                 {"pool",         no_argument,       0, 'p'},
943                 {"quiet",        no_argument,       0, 'q'},
944                 {"recursive",    no_argument,       0, 'r'},
945                 {"raw",          no_argument,       0, 'R'},
946 #if LUSTRE_VERSION >= OBD_OCD_VERSION(2,9,50,0)
947 #warning "remove deprecated --size option"
948 #else
949                 /* This formerly implied "--stripe-size", but was confusing
950                  * with "lfs find --size|-s", which means "file size", so use
951                  * the consistent "--stripe-size|-S" for all commands. */
952                 {"size",         no_argument,       0, 's'},
953 #endif
954                 {"stripe-size",  no_argument,       0, 'S'},
955                 {"stripe_size",  no_argument,       0, 'S'},
956                 {"verbose",      no_argument,       0, 'v'},
957                 {0, 0, 0, 0}
958         };
959         int c, rc;
960         struct find_param param = { 0 };
961
962         param.maxdepth = 1;
963         optind = 0;
964         while ((c = getopt_long(argc, argv, "cdghiMoO:pqrRsSv",
965                                 long_opts, NULL)) != -1) {
966                 switch (c) {
967                 case 'O':
968                         if (param.obduuid) {
969                                 fprintf(stderr,
970                                         "error: %s: only one obduuid allowed",
971                                         argv[0]);
972                                 return CMD_HELP;
973                         }
974                         param.obduuid = (struct obd_uuid *)optarg;
975                         break;
976                 case 'q':
977                         param.quiet++;
978                         break;
979                 case 'd':
980                         param.maxdepth = 0;
981                         break;
982                 case 'r':
983                         param.recursive = 1;
984                         break;
985                 case 'v':
986                         param.verbose = VERBOSE_ALL | VERBOSE_DETAIL;
987                         break;
988                 case 'c':
989 #if LUSTRE_VERSION >= OBD_OCD_VERSION(2,9,50,0)
990 #warning "remove deprecated --count option"
991 #elif LUSTRE_VERSION >= OBD_OCD_VERSION(2,6,50,0)
992                         if (strcmp(argv[optind - 1], "--count") == 0)
993                                 fprintf(stderr, "warning: '--count' deprecated,"
994                                         " use '--stripe-count' instead\n");
995 #endif
996                         if (!(param.verbose & VERBOSE_DETAIL)) {
997                                 param.verbose |= VERBOSE_COUNT;
998                                 param.maxdepth = 0;
999                         }
1000                         break;
1001                 case 's':
1002 #if LUSTRE_VERSION >= OBD_OCD_VERSION(2,9,50,0)
1003 #warning "remove deprecated --size option"
1004 #elif LUSTRE_VERSION >= OBD_OCD_VERSION(2,6,50,0)
1005                         fprintf(stderr, "warning: '--size|-s' deprecated, "
1006                                 "use '--stripe-size|-S' instead\n");
1007 #endif
1008                 case 'S':
1009                         if (!(param.verbose & VERBOSE_DETAIL)) {
1010                                 param.verbose |= VERBOSE_SIZE;
1011                                 param.maxdepth = 0;
1012                         }
1013                         break;
1014                 case 'o':
1015 #if LUSTRE_VERSION >= OBD_OCD_VERSION(2,4,50,0)
1016                         fprintf(stderr, "warning: '--offset|-o' deprecated, "
1017                                 "use '--stripe-index|-i' instead\n");
1018 #else
1019                         if (strcmp(argv[optind - 1], "--offset") == 0)
1020                                 /* need --stripe-index established first */
1021                                 fprintf(stderr, "warning: '--offset' deprecated"
1022                                         ", use '--index' instead\n");
1023 #endif
1024                 case 'i':
1025 #if LUSTRE_VERSION >= OBD_OCD_VERSION(2,9,50,0)
1026 #warning "remove deprecated --offset and --index options"
1027 #elif LUSTRE_VERSION >= OBD_OCD_VERSION(2,6,50,0)
1028                         if (strcmp(argv[optind - 1], "--index") == 0)
1029                                 fprintf(stderr, "warning: '--index' deprecated"
1030                                         ", use '--stripe-index' instead\n");
1031 #endif
1032                         if (!(param.verbose & VERBOSE_DETAIL)) {
1033                                 param.verbose |= VERBOSE_OFFSET;
1034                                 param.maxdepth = 0;
1035                         }
1036                         break;
1037                 case 'p':
1038                         if (!(param.verbose & VERBOSE_DETAIL)) {
1039                                 param.verbose |= VERBOSE_POOL;
1040                                 param.maxdepth = 0;
1041                         }
1042                         break;
1043                 case 'g':
1044                         if (!(param.verbose & VERBOSE_DETAIL)) {
1045                                 param.verbose |= VERBOSE_GENERATION;
1046                                 param.maxdepth = 0;
1047                         }
1048                         break;
1049                 case 'M':
1050                         if (!(param.verbose & VERBOSE_DETAIL))
1051                                 param.maxdepth = 0;
1052                         param.verbose |= VERBOSE_MDTINDEX;
1053                         break;
1054                 case 'R':
1055                         param.raw = 1;
1056                         break;
1057                 default:
1058                         return CMD_HELP;
1059                 }
1060         }
1061
1062         if (optind >= argc)
1063                 return CMD_HELP;
1064
1065         if (param.recursive)
1066                 param.maxdepth = -1;
1067
1068         if (!param.verbose)
1069                 param.verbose = VERBOSE_ALL;
1070         if (param.quiet)
1071                 param.verbose = VERBOSE_OBJID;
1072
1073         do {
1074                 rc = llapi_getstripe(argv[optind], &param);
1075         } while (++optind < argc && !rc);
1076
1077         if (rc)
1078                 fprintf(stderr, "error: %s failed for %s.\n",
1079                         argv[0], argv[optind - 1]);
1080         return rc;
1081 }
1082
1083 static int lfs_tgts(int argc, char **argv)
1084 {
1085         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
1086         struct find_param param;
1087         int index = 0, rc=0;
1088
1089         if (argc > 2)
1090                 return CMD_HELP;
1091
1092         if (argc == 2 && !realpath(argv[1], path)) {
1093                 rc = -errno;
1094                 fprintf(stderr, "error: invalid path '%s': %s\n",
1095                         argv[1], strerror(-rc));
1096                 return rc;
1097         }
1098
1099         while (!llapi_search_mounts(path, index++, mntdir, NULL)) {
1100                 /* Check if we have a mount point */
1101                 if (mntdir[0] == '\0')
1102                         continue;
1103
1104                 memset(&param, 0, sizeof(param));
1105                 if (!strcmp(argv[0], "mdts"))
1106                         param.get_lmv = 1;
1107
1108                 rc = llapi_ostlist(mntdir, &param);
1109                 if (rc) {
1110                         fprintf(stderr, "error: %s: failed on %s\n",
1111                                 argv[0], mntdir);
1112                 }
1113                 if (path[0] != '\0')
1114                         break;
1115                 memset(mntdir, 0, PATH_MAX);
1116         }
1117
1118         return rc;
1119 }
1120
1121 static int lfs_osts(int argc, char **argv)
1122 {
1123         return lfs_tgts(argc, argv);
1124 }
1125
1126 static int lfs_mdts(int argc, char **argv)
1127 {
1128         return lfs_tgts(argc, argv);
1129 }
1130
1131 #define COOK(value)                                                     \
1132 ({                                                                      \
1133         int radix = 0;                                                  \
1134         while (value > 1024) {                                          \
1135                 value /= 1024;                                          \
1136                 radix++;                                                \
1137         }                                                               \
1138         radix;                                                          \
1139 })
1140 #define UUF     "%-20s"
1141 #define CSF     "%11s"
1142 #define CDF     "%11llu"
1143 #define HDF     "%8.1f%c"
1144 #define RSF     "%4s"
1145 #define RDF     "%3d%%"
1146
1147 static int showdf(char *mntdir, struct obd_statfs *stat,
1148                   char *uuid, int ishow, int cooked,
1149                   char *type, int index, int rc)
1150 {
1151         long long avail, used, total;
1152         double ratio = 0;
1153         char *suffix = "KMGTPEZY";
1154         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
1155         char tbuf[20], ubuf[20], abuf[20], rbuf[20];
1156
1157         if (!uuid || !stat)
1158                 return -EINVAL;
1159
1160         switch (rc) {
1161         case 0:
1162                 if (ishow) {
1163                         avail = stat->os_ffree;
1164                         used = stat->os_files - stat->os_ffree;
1165                         total = stat->os_files;
1166                 } else {
1167                         int shift = cooked ? 0 : 10;
1168
1169                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
1170                         used  = ((stat->os_blocks - stat->os_bfree) *
1171                                  stat->os_bsize) >> shift;
1172                         total = (stat->os_blocks * stat->os_bsize) >> shift;
1173                 }
1174
1175                 if ((used + avail) > 0)
1176                         ratio = (double)used / (double)(used + avail);
1177
1178                 if (cooked) {
1179                         int i;
1180                         double cook_val;
1181
1182                         cook_val = (double)total;
1183                         i = COOK(cook_val);
1184                         if (i > 0)
1185                                 sprintf(tbuf, HDF, cook_val, suffix[i - 1]);
1186                         else
1187                                 sprintf(tbuf, CDF, total);
1188
1189                         cook_val = (double)used;
1190                         i = COOK(cook_val);
1191                         if (i > 0)
1192                                 sprintf(ubuf, HDF, cook_val, suffix[i - 1]);
1193                         else
1194                                 sprintf(ubuf, CDF, used);
1195
1196                         cook_val = (double)avail;
1197                         i = COOK(cook_val);
1198                         if (i > 0)
1199                                 sprintf(abuf, HDF, cook_val, suffix[i - 1]);
1200                         else
1201                                 sprintf(abuf, CDF, avail);
1202                 } else {
1203                         sprintf(tbuf, CDF, total);
1204                         sprintf(ubuf, CDF, used);
1205                         sprintf(abuf, CDF, avail);
1206                 }
1207
1208                 sprintf(rbuf, RDF, (int)(ratio * 100 + 0.5));
1209                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
1210                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
1211                 if (type)
1212                         printf("[%s:%d]\n", type, index);
1213                 else
1214                         printf("\n");
1215
1216                 break;
1217         case -ENODATA:
1218                 printf(UUF": inactive device\n", uuid);
1219                 break;
1220         default:
1221                 printf(UUF": %s\n", uuid, strerror(-rc));
1222                 break;
1223         }
1224
1225         return 0;
1226 }
1227
1228 struct ll_stat_type {
1229         int   st_op;
1230         char *st_name;
1231 };
1232
1233 static int mntdf(char *mntdir, char *fsname, char *pool, int ishow, int cooked)
1234 {
1235         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
1236         struct obd_uuid uuid_buf;
1237         char *poolname = NULL;
1238         struct ll_stat_type types[] = { { LL_STATFS_LMV, "MDT" },
1239                                         { LL_STATFS_LOV, "OST" },
1240                                         { 0, NULL } };
1241         struct ll_stat_type *tp;
1242         __u32 index;
1243         int rc;
1244
1245         if (pool) {
1246                 poolname = strchr(pool, '.');
1247                 if (poolname != NULL) {
1248                         if (strncmp(fsname, pool, strlen(fsname))) {
1249                                 fprintf(stderr, "filesystem name incorrect\n");
1250                                 return -ENODEV;
1251                         }
1252                         poolname++;
1253                 } else
1254                         poolname = pool;
1255         }
1256
1257         if (ishow)
1258                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
1259                        "UUID", "Inodes", "IUsed", "IFree",
1260                        "IUse%", "Mounted on");
1261         else
1262                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
1263                        "UUID", cooked ? "bytes" : "1K-blocks",
1264                        "Used", "Available", "Use%", "Mounted on");
1265
1266         for (tp = types; tp->st_name != NULL; tp++) {
1267                 for (index = 0; ; index++) {
1268                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
1269                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
1270                         rc = llapi_obd_statfs(mntdir, tp->st_op, index,
1271                                               &stat_buf, &uuid_buf);
1272                         if (rc == -ENODEV)
1273                                 break;
1274
1275                         if (poolname && tp->st_op == LL_STATFS_LOV &&
1276                             llapi_search_ost(fsname, poolname,
1277                                              obd_uuid2str(&uuid_buf)) != 1)
1278                                 continue;
1279
1280                         /* the llapi_obd_statfs() call may have returned with
1281                          * an error, but if it filled in uuid_buf we will at
1282                          * lease use that to print out a message for that OBD.
1283                          * If we didn't get anything in the uuid_buf, then fill
1284                          * it in so that we can print an error message. */
1285                         if (uuid_buf.uuid[0] == '\0')
1286                                 sprintf(uuid_buf.uuid, "%s%04x",
1287                                         tp->st_name, index);
1288                         showdf(mntdir,&stat_buf,obd_uuid2str(&uuid_buf),
1289                                ishow, cooked, tp->st_name, index, rc);
1290
1291                         if (rc == 0) {
1292                                 if (tp->st_op == LL_STATFS_LMV) {
1293                                         sum.os_ffree += stat_buf.os_ffree;
1294                                         sum.os_files += stat_buf.os_files;
1295                                 } else /* if (tp->st_op == LL_STATFS_LOV) */ {
1296                                         sum.os_blocks += stat_buf.os_blocks *
1297                                                 stat_buf.os_bsize;
1298                                         sum.os_bfree  += stat_buf.os_bfree *
1299                                                 stat_buf.os_bsize;
1300                                         sum.os_bavail += stat_buf.os_bavail *
1301                                                 stat_buf.os_bsize;
1302                                 }
1303                         } else if (rc == -EINVAL || rc == -EFAULT) {
1304                                 break;
1305                         }
1306                 }
1307         }
1308
1309         printf("\n");
1310         showdf(mntdir, &sum, "filesystem summary:", ishow, cooked, NULL, 0,0);
1311         printf("\n");
1312         return 0;
1313 }
1314
1315 static int lfs_df(int argc, char **argv)
1316 {
1317         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
1318         int ishow = 0, cooked = 0;
1319         int c, rc = 0, index = 0;
1320         char fsname[PATH_MAX] = "", *pool_name = NULL;
1321         struct option long_opts[] = {
1322                 {"pool", required_argument, 0, 'p'},
1323                 {0, 0, 0, 0}
1324         };
1325
1326         optind = 0;
1327         while ((c = getopt_long(argc, argv, "hip:", long_opts, NULL)) != -1) {
1328                 switch (c) {
1329                 case 'i':
1330                         ishow = 1;
1331                         break;
1332                 case 'h':
1333                         cooked = 1;
1334                         break;
1335                 case 'p':
1336                         pool_name = optarg;
1337                         break;
1338                 default:
1339                         return CMD_HELP;
1340                 }
1341         }
1342         if (optind < argc && !realpath(argv[optind], path)) {
1343                 rc = -errno;
1344                 fprintf(stderr, "error: invalid path '%s': %s\n",
1345                         argv[optind], strerror(-rc));
1346                 return rc;
1347         }
1348
1349         while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
1350                 /* Check if we have a mount point */
1351                 if (mntdir[0] == '\0')
1352                         continue;
1353
1354                 rc = mntdf(mntdir, fsname, pool_name, ishow, cooked);
1355                 if (rc || path[0] != '\0')
1356                         break;
1357                 fsname[0] = '\0'; /* avoid matching in next loop */
1358                 mntdir[0] = '\0'; /* avoid matching in next loop */
1359         }
1360
1361         return rc;
1362 }
1363
1364 static int lfs_getname(int argc, char **argv)
1365 {
1366         char mntdir[PATH_MAX] = "", path[PATH_MAX] = "", fsname[PATH_MAX] = "";
1367         int rc = 0, index = 0, c;
1368         char buf[sizeof(struct obd_uuid)];
1369
1370         optind = 0;
1371         while ((c = getopt(argc, argv, "h")) != -1)
1372                 return CMD_HELP;
1373
1374         if (optind == argc) { /* no paths specified, get all paths. */
1375                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
1376                         rc = llapi_getname(mntdir, buf, sizeof(buf));
1377                         if (rc < 0) {
1378                                 fprintf(stderr,
1379                                         "cannot get name for `%s': %s\n",
1380                                         mntdir, strerror(-rc));
1381                                 break;
1382                         }
1383
1384                         printf("%s %s\n", buf, mntdir);
1385
1386                         path[0] = fsname[0] = mntdir[0] = 0;
1387                 }
1388         } else { /* paths specified, only attempt to search these. */
1389                 for (; optind < argc; optind++) {
1390                         rc = llapi_getname(argv[optind], buf, sizeof(buf));
1391                         if (rc < 0) {
1392                                 fprintf(stderr,
1393                                         "cannot get name for `%s': %s\n",
1394                                         argv[optind], strerror(-rc));
1395                                 break;
1396                         }
1397
1398                         printf("%s %s\n", buf, argv[optind]);
1399                 }
1400         }
1401         return rc;
1402 }
1403
1404 static int lfs_check(int argc, char **argv)
1405 {
1406         int rc;
1407         char mntdir[PATH_MAX] = {'\0'};
1408         int num_types = 1;
1409         char *obd_types[2];
1410         char obd_type1[4];
1411         char obd_type2[4];
1412
1413         if (argc != 2)
1414                 return CMD_HELP;
1415
1416         obd_types[0] = obd_type1;
1417         obd_types[1] = obd_type2;
1418
1419         if (strcmp(argv[1], "osts") == 0) {
1420                 strcpy(obd_types[0], "osc");
1421         } else if (strcmp(argv[1], "mds") == 0) {
1422                 strcpy(obd_types[0], "mdc");
1423         } else if (strcmp(argv[1], "servers") == 0) {
1424                 num_types = 2;
1425                 strcpy(obd_types[0], "osc");
1426                 strcpy(obd_types[1], "mdc");
1427         } else {
1428                 fprintf(stderr, "error: %s: option '%s' unrecognized\n",
1429                                 argv[0], argv[1]);
1430                         return CMD_HELP;
1431         }
1432
1433         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
1434         if (rc < 0 || mntdir[0] == '\0') {
1435                 fprintf(stderr, "No suitable Lustre mount found\n");
1436                 return rc;
1437         }
1438
1439         rc = llapi_target_iterate(num_types, obd_types,
1440                                   mntdir, llapi_ping_target);
1441
1442         if (rc)
1443                 fprintf(stderr, "error: %s: %s status failed\n",
1444                                 argv[0],argv[1]);
1445
1446         return rc;
1447
1448 }
1449
1450 static int lfs_catinfo(int argc, char **argv)
1451 {
1452         char mntdir[PATH_MAX] = {'\0'};
1453         int rc;
1454
1455         if (argc < 2 || (!strcmp(argv[1],"config") && argc < 3))
1456                 return CMD_HELP;
1457
1458         if (strcmp(argv[1], "config") && strcmp(argv[1], "deletions"))
1459                 return CMD_HELP;
1460
1461         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
1462         if (rc == 0 && mntdir[0] != '\0') {
1463                 if (argc == 3)
1464                         rc = llapi_catinfo(mntdir, argv[1], argv[2]);
1465                 else
1466                         rc = llapi_catinfo(mntdir, argv[1], NULL);
1467         } else {
1468                 fprintf(stderr, "no lustre_lite mounted.\n");
1469                 rc = -1;
1470         }
1471
1472         return rc;
1473 }
1474
1475 static int lfs_join(int argc, char **argv)
1476 {
1477         fprintf(stderr, "join two lustre files into one.\n"
1478                         "obsolete, HEAD does not support it anymore.\n");
1479         return 0;
1480 }
1481
1482 #ifdef HAVE_SYS_QUOTA_H
1483 static int lfs_quotachown(int argc, char **argv)
1484 {
1485
1486         int c,rc;
1487         int flag = 0;
1488
1489         optind = 0;
1490         while ((c = getopt(argc, argv, "i")) != -1) {
1491                 switch (c) {
1492                 case 'i':
1493                         flag++;
1494                         break;
1495                 default:
1496                         fprintf(stderr, "error: %s: option '-%c' "
1497                                         "unrecognized\n", argv[0], c);
1498                         return CMD_HELP;
1499                 }
1500         }
1501         if (optind == argc)
1502                 return CMD_HELP;
1503         rc = llapi_quotachown(argv[optind], flag);
1504         if(rc)
1505                 fprintf(stderr,"error: change file owner/group failed.\n");
1506         return rc;
1507 }
1508
1509 static int lfs_quotacheck(int argc, char **argv)
1510 {
1511         int c, check_type = 0;
1512         char *mnt;
1513         struct if_quotacheck qchk;
1514         struct if_quotactl qctl;
1515         char *obd_type = (char *)qchk.obd_type;
1516         int rc;
1517
1518         memset(&qchk, 0, sizeof(qchk));
1519
1520         optind = 0;
1521         while ((c = getopt(argc, argv, "gu")) != -1) {
1522                 switch (c) {
1523                 case 'u':
1524                         check_type |= 0x01;
1525                         break;
1526                 case 'g':
1527                         check_type |= 0x02;
1528                         break;
1529                 default:
1530                         fprintf(stderr, "error: %s: option '-%c' "
1531                                         "unrecognized\n", argv[0], c);
1532                         return CMD_HELP;
1533                 }
1534         }
1535
1536         if (check_type)
1537                 check_type--;
1538         else    /* do quotacheck for both user & group quota by default */
1539                 check_type = 0x02;
1540
1541         if (argc == optind)
1542                 return CMD_HELP;
1543
1544         mnt = argv[optind];
1545
1546         rc = llapi_quotacheck(mnt, check_type);
1547         if (rc) {
1548                 fprintf(stderr, "quotacheck failed: %s\n", strerror(-rc));
1549                 return rc;
1550         }
1551
1552         rc = llapi_poll_quotacheck(mnt, &qchk);
1553         if (rc) {
1554                 if (*obd_type)
1555                         fprintf(stderr, "%s %s ", obd_type,
1556                                 obd_uuid2str(&qchk.obd_uuid));
1557                 fprintf(stderr, "quota check failed: %s\n", strerror(-rc));
1558                 return rc;
1559         }
1560
1561         memset(&qctl, 0, sizeof(qctl));
1562         qctl.qc_cmd = LUSTRE_Q_QUOTAON;
1563         qctl.qc_type = check_type;
1564         rc = llapi_quotactl(mnt, &qctl);
1565         if (rc && rc != -EALREADY) {
1566                 if (*obd_type)
1567                         fprintf(stderr, "%s %s ", (char *)qctl.obd_type,
1568                                 obd_uuid2str(&qctl.obd_uuid));
1569                 fprintf(stderr, "%s turn on quota failed: %s\n",
1570                         argv[0], strerror(-rc));
1571                 return rc;
1572         }
1573
1574         return 0;
1575 }
1576
1577 static int lfs_quotaon(int argc, char **argv)
1578 {
1579         int c;
1580         char *mnt;
1581         struct if_quotactl qctl;
1582         char *obd_type = (char *)qctl.obd_type;
1583         int rc;
1584
1585         memset(&qctl, 0, sizeof(qctl));
1586         qctl.qc_cmd = LUSTRE_Q_QUOTAON;
1587
1588         optind = 0;
1589         while ((c = getopt(argc, argv, "fgu")) != -1) {
1590                 switch (c) {
1591                 case 'u':
1592                         qctl.qc_type |= 0x01;
1593                         break;
1594                 case 'g':
1595                         qctl.qc_type |= 0x02;
1596                         break;
1597                 case 'f':
1598                         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
1599                         break;
1600                 default:
1601                         fprintf(stderr, "error: %s: option '-%c' "
1602                                         "unrecognized\n", argv[0], c);
1603                         return CMD_HELP;
1604                 }
1605         }
1606
1607         if (qctl.qc_type)
1608                 qctl.qc_type--;
1609         else /* by default, enable quota for both user & group */
1610                 qctl.qc_type = 0x02;
1611
1612         if (argc == optind)
1613                 return CMD_HELP;
1614
1615         mnt = argv[optind];
1616
1617         rc = llapi_quotactl(mnt, &qctl);
1618         if (rc) {
1619                 if (rc == -EALREADY) {
1620                         rc = 0;
1621                 } else if (rc == -ENOENT) {
1622                         fprintf(stderr, "error: cannot find quota database, "
1623                                         "make sure you have run quotacheck\n");
1624                 } else {
1625                         if (*obd_type)
1626                                 fprintf(stderr, "%s %s ", obd_type,
1627                                         obd_uuid2str(&qctl.obd_uuid));
1628                         fprintf(stderr, "%s failed: %s\n", argv[0],
1629                                 strerror(-rc));
1630                 }
1631         }
1632
1633         return rc;
1634 }
1635
1636 static int lfs_quotaoff(int argc, char **argv)
1637 {
1638         int c;
1639         char *mnt;
1640         struct if_quotactl qctl;
1641         char *obd_type = (char *)qctl.obd_type;
1642         int rc;
1643
1644         memset(&qctl, 0, sizeof(qctl));
1645         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
1646
1647         optind = 0;
1648         while ((c = getopt(argc, argv, "gu")) != -1) {
1649                 switch (c) {
1650                 case 'u':
1651                         qctl.qc_type |= 0x01;
1652                         break;
1653                 case 'g':
1654                         qctl.qc_type |= 0x02;
1655                         break;
1656                 default:
1657                         fprintf(stderr, "error: %s: option '-%c' "
1658                                         "unrecognized\n", argv[0], c);
1659                         return CMD_HELP;
1660                 }
1661         }
1662
1663         if (qctl.qc_type)
1664                 qctl.qc_type--;
1665         else /* by default, disable quota for both user & group */
1666                 qctl.qc_type = 0x02;
1667
1668         if (argc == optind)
1669                 return CMD_HELP;
1670
1671         mnt = argv[optind];
1672
1673         rc = llapi_quotactl(mnt, &qctl);
1674         if (rc) {
1675                 if (rc == -EALREADY) {
1676                         rc = 0;
1677                 } else {
1678                         if (*obd_type)
1679                                 fprintf(stderr, "%s %s ", obd_type,
1680                                         obd_uuid2str(&qctl.obd_uuid));
1681                         fprintf(stderr, "quotaoff failed: %s\n",
1682                                 strerror(-rc));
1683                 }
1684         }
1685
1686         return rc;
1687 }
1688
1689 static int lfs_quotainv(int argc, char **argv)
1690 {
1691         int c;
1692         char *mnt;
1693         struct if_quotactl qctl;
1694         int rc;
1695
1696         memset(&qctl, 0, sizeof(qctl));
1697         qctl.qc_cmd = LUSTRE_Q_INVALIDATE;
1698
1699         optind = 0;
1700         while ((c = getopt(argc, argv, "fgu")) != -1) {
1701                 switch (c) {
1702                 case 'u':
1703                         qctl.qc_type |= 0x01;
1704                         break;
1705                 case 'g':
1706                         qctl.qc_type |= 0x02;
1707                         break;
1708                 case 'f':
1709                         qctl.qc_cmd = LUSTRE_Q_FINVALIDATE;
1710                         break;
1711                 default:
1712                         fprintf(stderr, "error: %s: option '-%c' "
1713                                         "unrecognized\n", argv[0], c);
1714                         return CMD_HELP;
1715                 }
1716         }
1717
1718         if (qctl.qc_type)
1719                 qctl.qc_type--;
1720         else /* by default, invalidate quota for both user & group */
1721                 qctl.qc_type = 0x02;
1722
1723         if (argc == optind)
1724                 return CMD_HELP;
1725
1726         mnt = argv[optind];
1727
1728         rc = llapi_quotactl(mnt, &qctl);
1729         if (rc) {
1730                 fprintf(stderr, "quotainv failed: %s\n", strerror(-rc));
1731                 return rc;
1732         }
1733
1734         return 0;
1735 }
1736
1737 #define ARG2INT(nr, str, msg)                                           \
1738 do {                                                                    \
1739         char *endp;                                                     \
1740         nr = strtol(str, &endp, 0);                                     \
1741         if (*endp) {                                                    \
1742                 fprintf(stderr, "error: bad %s: %s\n", msg, str);       \
1743                 return CMD_HELP;                                        \
1744         }                                                               \
1745 } while (0)
1746
1747 #define ADD_OVERFLOW(a,b) ((a + b) < a) ? (a = ULONG_MAX) : (a = a + b)
1748
1749 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
1750  * returns the value or ULONG_MAX on integer overflow or incorrect format
1751  * Notes:
1752  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
1753  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
1754  *        3. empty integer value is interpreted as 0
1755  */
1756 static unsigned long str2sec(const char* timestr)
1757 {
1758         const char spec[] = "smhdw";
1759         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
1760         unsigned long val = 0;
1761         char *tail;
1762
1763         if (strpbrk(timestr, spec) == NULL) {
1764                 /* no specifiers inside the time string,
1765                    should treat it as an integer value */
1766                 val = strtoul(timestr, &tail, 10);
1767                 return *tail ? ULONG_MAX : val;
1768         }
1769
1770         /* format string is XXwXXdXXhXXmXXs */
1771         while (*timestr) {
1772                 unsigned long v;
1773                 int ind;
1774                 char* ptr;
1775
1776                 v = strtoul(timestr, &tail, 10);
1777                 if (v == ULONG_MAX || *tail == '\0')
1778                         /* value too large (ULONG_MAX or more)
1779                            or missing specifier */
1780                         goto error;
1781
1782                 ptr = strchr(spec, *tail);
1783                 if (ptr == NULL)
1784                         /* unknown specifier */
1785                         goto error;
1786
1787                 ind = ptr - spec;
1788
1789                 /* check if product will overflow the type */
1790                 if (!(v < ULONG_MAX / mult[ind]))
1791                         goto error;
1792
1793                 ADD_OVERFLOW(val, mult[ind] * v);
1794                 if (val == ULONG_MAX)
1795                         goto error;
1796
1797                 timestr = tail + 1;
1798         }
1799
1800         return val;
1801
1802 error:
1803         return ULONG_MAX;
1804 }
1805
1806 #define ARG2ULL(nr, str, def_units)                                     \
1807 do {                                                                    \
1808         unsigned long long limit, units = def_units;                    \
1809         int rc;                                                         \
1810                                                                         \
1811         rc = parse_size(str, &limit, &units, 1);                        \
1812         if (rc < 0) {                                                   \
1813                 fprintf(stderr, "error: bad limit value %s\n", str);    \
1814                 return CMD_HELP;                                        \
1815         }                                                               \
1816         nr = limit;                                                     \
1817 } while (0)
1818
1819 static inline int has_times_option(int argc, char **argv)
1820 {
1821         int i;
1822
1823         for (i = 1; i < argc; i++)
1824                 if (!strcmp(argv[i], "-t"))
1825                         return 1;
1826
1827         return 0;
1828 }
1829
1830 int lfs_setquota_times(int argc, char **argv)
1831 {
1832         int c, rc;
1833         struct if_quotactl qctl;
1834         char *mnt, *obd_type = (char *)qctl.obd_type;
1835         struct obd_dqblk *dqb = &qctl.qc_dqblk;
1836         struct obd_dqinfo *dqi = &qctl.qc_dqinfo;
1837         struct option long_opts[] = {
1838                 {"block-grace",     required_argument, 0, 'b'},
1839                 {"group",           no_argument,       0, 'g'},
1840                 {"inode-grace",     required_argument, 0, 'i'},
1841                 {"times",           no_argument,       0, 't'},
1842                 {"user",            no_argument,       0, 'u'},
1843                 {0, 0, 0, 0}
1844         };
1845
1846         memset(&qctl, 0, sizeof(qctl));
1847         qctl.qc_cmd  = LUSTRE_Q_SETINFO;
1848         qctl.qc_type = UGQUOTA;
1849
1850         optind = 0;
1851         while ((c = getopt_long(argc, argv, "b:gi:tu", long_opts, NULL)) != -1) {
1852                 switch (c) {
1853                 case 'u':
1854                 case 'g':
1855                         if (qctl.qc_type != UGQUOTA) {
1856                                 fprintf(stderr, "error: -u and -g can't be used "
1857                                                 "more than once\n");
1858                                 return CMD_HELP;
1859                         }
1860                         qctl.qc_type = (c == 'u') ? USRQUOTA : GRPQUOTA;
1861                         break;
1862                 case 'b':
1863                         if ((dqi->dqi_bgrace = str2sec(optarg)) == ULONG_MAX) {
1864                                 fprintf(stderr, "error: bad block-grace: %s\n",
1865                                         optarg);
1866                                 return CMD_HELP;
1867                         }
1868                         dqb->dqb_valid |= QIF_BTIME;
1869                         break;
1870                 case 'i':
1871                         if ((dqi->dqi_igrace = str2sec(optarg)) == ULONG_MAX) {
1872                                 fprintf(stderr, "error: bad inode-grace: %s\n",
1873                                         optarg);
1874                                 return CMD_HELP;
1875                         }
1876                         dqb->dqb_valid |= QIF_ITIME;
1877                         break;
1878                 case 't': /* Yes, of course! */
1879                         break;
1880                 default: /* getopt prints error message for us when opterr != 0 */
1881                         return CMD_HELP;
1882                 }
1883         }
1884
1885         if (qctl.qc_type == UGQUOTA) {
1886                 fprintf(stderr, "error: neither -u nor -g specified\n");
1887                 return CMD_HELP;
1888         }
1889
1890         if (optind != argc - 1) {
1891                 fprintf(stderr, "error: unexpected parameters encountered\n");
1892                 return CMD_HELP;
1893         }
1894
1895         mnt = argv[optind];
1896         rc = llapi_quotactl(mnt, &qctl);
1897         if (rc) {
1898                 if (*obd_type)
1899                         fprintf(stderr, "%s %s ", obd_type,
1900                                 obd_uuid2str(&qctl.obd_uuid));
1901                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
1902                 return rc;
1903         }
1904
1905         return 0;
1906 }
1907
1908 #define BSLIMIT (1 << 0)
1909 #define BHLIMIT (1 << 1)
1910 #define ISLIMIT (1 << 2)
1911 #define IHLIMIT (1 << 3)
1912
1913 int lfs_setquota(int argc, char **argv)
1914 {
1915         int c, rc;
1916         struct if_quotactl qctl;
1917         char *mnt, *obd_type = (char *)qctl.obd_type;
1918         struct obd_dqblk *dqb = &qctl.qc_dqblk;
1919         struct option long_opts[] = {
1920                 {"block-softlimit", required_argument, 0, 'b'},
1921                 {"block-hardlimit", required_argument, 0, 'B'},
1922                 {"group",           required_argument, 0, 'g'},
1923                 {"inode-softlimit", required_argument, 0, 'i'},
1924                 {"inode-hardlimit", required_argument, 0, 'I'},
1925                 {"user",            required_argument, 0, 'u'},
1926                 {0, 0, 0, 0}
1927         };
1928         unsigned limit_mask = 0;
1929         char *endptr;
1930
1931         if (has_times_option(argc, argv))
1932                 return lfs_setquota_times(argc, argv);
1933
1934         memset(&qctl, 0, sizeof(qctl));
1935         qctl.qc_cmd  = LUSTRE_Q_SETQUOTA;
1936         qctl.qc_type = UGQUOTA; /* UGQUOTA makes no sense for setquota,
1937                                  * so it can be used as a marker that qc_type
1938                                  * isn't reinitialized from command line */
1939
1940         optind = 0;
1941         while ((c = getopt_long(argc, argv, "b:B:g:i:I:u:", long_opts, NULL)) != -1) {
1942                 switch (c) {
1943                 case 'u':
1944                 case 'g':
1945                         if (qctl.qc_type != UGQUOTA) {
1946                                 fprintf(stderr, "error: -u and -g can't be used"
1947                                                 " more than once\n");
1948                                 return CMD_HELP;
1949                         }
1950                         qctl.qc_type = (c == 'u') ? USRQUOTA : GRPQUOTA;
1951                         rc = name2id(&qctl.qc_id, optarg,
1952                                      (qctl.qc_type == USRQUOTA) ? USER : GROUP);
1953                         if (rc) {
1954                                 qctl.qc_id = strtoul(optarg, &endptr, 10);
1955                                 if (*endptr != '\0') {
1956                                         fprintf(stderr, "error: can't find id "
1957                                                 "for name %s\n", optarg);
1958                                         return CMD_HELP;
1959                                 }
1960                         }
1961                         break;
1962                 case 'b':
1963                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
1964                         dqb->dqb_bsoftlimit >>= 10;
1965                         limit_mask |= BSLIMIT;
1966                         break;
1967                 case 'B':
1968                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
1969                         dqb->dqb_bhardlimit >>= 10;
1970                         limit_mask |= BHLIMIT;
1971                         break;
1972                 case 'i':
1973                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
1974                         limit_mask |= ISLIMIT;
1975                         break;
1976                 case 'I':
1977                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
1978                         limit_mask |= IHLIMIT;
1979                         break;
1980                 default: /* getopt prints error message for us when opterr != 0 */
1981                         return CMD_HELP;
1982                 }
1983         }
1984
1985         if (qctl.qc_type == UGQUOTA) {
1986                 fprintf(stderr, "error: neither -u nor -g was specified\n");
1987                 return CMD_HELP;
1988         }
1989
1990         if (limit_mask == 0) {
1991                 fprintf(stderr, "error: at least one limit must be specified\n");
1992                 return CMD_HELP;
1993         }
1994
1995         if (optind != argc - 1) {
1996                 fprintf(stderr, "error: unexpected parameters encountered\n");
1997                 return CMD_HELP;
1998         }
1999
2000         mnt = argv[optind];
2001
2002         if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
2003             (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
2004                 /* sigh, we can't just set blimits/ilimits */
2005                 struct if_quotactl tmp_qctl = {.qc_cmd  = LUSTRE_Q_GETQUOTA,
2006                                                .qc_type = qctl.qc_type,
2007                                                .qc_id   = qctl.qc_id};
2008
2009                 rc = llapi_quotactl(mnt, &tmp_qctl);
2010                 if (rc < 0) {
2011                         fprintf(stderr, "error: setquota failed while retrieving"
2012                                         " current quota settings (%s)\n",
2013                                         strerror(-rc));
2014                         return rc;
2015                 }
2016
2017                 if (!(limit_mask & BHLIMIT))
2018                         dqb->dqb_bhardlimit = tmp_qctl.qc_dqblk.dqb_bhardlimit;
2019                 if (!(limit_mask & BSLIMIT))
2020                         dqb->dqb_bsoftlimit = tmp_qctl.qc_dqblk.dqb_bsoftlimit;
2021                 if (!(limit_mask & IHLIMIT))
2022                         dqb->dqb_ihardlimit = tmp_qctl.qc_dqblk.dqb_ihardlimit;
2023                 if (!(limit_mask & ISLIMIT))
2024                         dqb->dqb_isoftlimit = tmp_qctl.qc_dqblk.dqb_isoftlimit;
2025
2026                 /* Keep grace times if we have got no softlimit arguments */
2027                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
2028                         dqb->dqb_valid |= QIF_BTIME;
2029                         dqb->dqb_btime = tmp_qctl.qc_dqblk.dqb_btime;
2030                 }
2031
2032                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
2033                         dqb->dqb_valid |= QIF_ITIME;
2034                         dqb->dqb_itime = tmp_qctl.qc_dqblk.dqb_itime;
2035                 }
2036         }
2037
2038         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
2039         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
2040
2041         rc = llapi_quotactl(mnt, &qctl);
2042         if (rc) {
2043                 if (*obd_type)
2044                         fprintf(stderr, "%s %s ", obd_type,
2045                                 obd_uuid2str(&qctl.obd_uuid));
2046                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
2047                 return rc;
2048         }
2049
2050         return 0;
2051 }
2052
2053 static inline char *type2name(int check_type)
2054 {
2055         if (check_type == USRQUOTA)
2056                 return "user";
2057         else if (check_type == GRPQUOTA)
2058                 return "group";
2059         else
2060                 return "unknown";
2061 }
2062
2063 /* Converts seconds value into format string
2064  * result is returned in buf
2065  * Notes:
2066  *        1. result is in descenting order: 1w2d3h4m5s
2067  *        2. zero fields are not filled (except for p. 3): 5d1s
2068  *        3. zero seconds value is presented as "0s"
2069  */
2070 static char * __sec2str(time_t seconds, char *buf)
2071 {
2072         const char spec[] = "smhdw";
2073         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
2074         unsigned long c;
2075         char *tail = buf;
2076         int i;
2077
2078         for (i = sizeof(mult) / sizeof(mult[0]) - 1 ; i >= 0; i--) {
2079                 c = seconds / mult[i];
2080
2081                 if (c > 0 || (i == 0 && buf == tail))
2082                         tail += snprintf(tail, 40-(tail-buf), "%lu%c", c, spec[i]);
2083
2084                 seconds %= mult[i];
2085         }
2086
2087         return tail;
2088 }
2089
2090 static void sec2str(time_t seconds, char *buf, int rc)
2091 {
2092         char *tail = buf;
2093
2094         if (rc)
2095                 *tail++ = '[';
2096
2097         tail = __sec2str(seconds, tail);
2098
2099         if (rc && tail - buf < 39) {
2100                 *tail++ = ']';
2101                 *tail++ = 0;
2102         }
2103 }
2104
2105 static void diff2str(time_t seconds, char *buf, time_t now)
2106 {
2107
2108         buf[0] = 0;
2109         if (!seconds)
2110                 return;
2111         if (seconds <= now) {
2112                 strcpy(buf, "none");
2113                 return;
2114         }
2115         __sec2str(seconds - now, buf);
2116 }
2117
2118 static void print_quota_title(char *name, struct if_quotactl *qctl)
2119 {
2120         printf("Disk quotas for %s %s (%cid %u):\n",
2121                type2name(qctl->qc_type), name,
2122                *type2name(qctl->qc_type), qctl->qc_id);
2123         printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
2124                "Filesystem",
2125                "kbytes", "quota", "limit", "grace",
2126                "files", "quota", "limit", "grace");
2127 }
2128
2129 static void print_quota(char *mnt, struct if_quotactl *qctl, int type, int rc)
2130 {
2131         time_t now;
2132
2133         time(&now);
2134
2135         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA) {
2136                 int bover = 0, iover = 0;
2137                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
2138
2139                 if (dqb->dqb_bhardlimit &&
2140                     toqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
2141                         bover = 1;
2142                 } else if (dqb->dqb_bsoftlimit && dqb->dqb_btime) {
2143                         if (dqb->dqb_btime > now) {
2144                                 bover = 2;
2145                         } else {
2146                                 bover = 3;
2147                         }
2148                 }
2149
2150                 if (dqb->dqb_ihardlimit &&
2151                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
2152                         iover = 1;
2153                 } else if (dqb->dqb_isoftlimit && dqb->dqb_itime) {
2154                         if (dqb->dqb_btime > now) {
2155                                 iover = 2;
2156                         } else {
2157                                 iover = 3;
2158                         }
2159                 }
2160
2161 #if 0           /* XXX: always print quotas even when no usages */
2162                 if (dqb->dqb_curspace || dqb->dqb_curinodes)
2163 #endif
2164                 {
2165                         char numbuf[3][32];
2166                         char timebuf[40];
2167
2168                         if (strlen(mnt) > 15)
2169                                 printf("%s\n%15s", mnt, "");
2170                         else
2171                                 printf("%15s", mnt);
2172
2173                         if (bover)
2174                                 diff2str(dqb->dqb_btime, timebuf, now);
2175                         if (rc == -EREMOTEIO)
2176                                 sprintf(numbuf[0], LPU64"*",
2177                                         toqb(dqb->dqb_curspace));
2178                         else
2179                                 sprintf(numbuf[0],
2180                                         (dqb->dqb_valid & QIF_SPACE) ?
2181                                         LPU64 : "["LPU64"]",
2182                                         toqb(dqb->dqb_curspace));
2183                         if (type == QC_GENERAL)
2184                                 sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS)
2185                                         ? LPU64 : "["LPU64"]",
2186                                         dqb->dqb_bsoftlimit);
2187                         else
2188                                 sprintf(numbuf[1], "%s", "-");
2189                         sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS)
2190                                 ? LPU64 : "["LPU64"]", dqb->dqb_bhardlimit);
2191                         printf(" %7s%c %6s %7s %7s",
2192                                numbuf[0], bover ? '*' : ' ', numbuf[1],
2193                                numbuf[2], bover > 1 ? timebuf : "-");
2194
2195                         if (iover)
2196                                 diff2str(dqb->dqb_itime, timebuf, now);
2197
2198                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_INODES) ?
2199                                 LPU64 : "["LPU64"]", dqb->dqb_curinodes);
2200                        if (type == QC_GENERAL)
2201                                 sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS)
2202                                         ? LPU64 : "["LPU64"]",
2203                                         dqb->dqb_isoftlimit);
2204                         else
2205                                 sprintf(numbuf[1], "%s", "-");
2206                         sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
2207                                 LPU64 : "["LPU64"]", dqb->dqb_ihardlimit);
2208                         if (type != QC_OSTIDX)
2209                                 printf(" %7s%c %6s %7s %7s",
2210                                        numbuf[0], iover ? '*' : ' ', numbuf[1],
2211                                        numbuf[2], iover > 1 ? timebuf : "-");
2212                         else
2213                                 printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
2214                         printf("\n");
2215                 }
2216         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO ||
2217                    qctl->qc_cmd == Q_GETOINFO) {
2218                 char bgtimebuf[40];
2219                 char igtimebuf[40];
2220
2221                 sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
2222                 sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
2223                 printf("Block grace time: %s; Inode grace time: %s\n",
2224                        bgtimebuf, igtimebuf);
2225         }
2226 }
2227
2228 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt)
2229 {
2230         int rc = 0, rc1 = 0, count = 0;
2231         __u32 valid = qctl->qc_valid;
2232
2233         rc = llapi_get_obd_count(mnt, &count, is_mdt);
2234         if (rc) {
2235                 fprintf(stderr, "can not get %s count: %s\n",
2236                         is_mdt ? "mdt": "ost", strerror(-rc));
2237                 return rc;
2238         }
2239
2240         for (qctl->qc_idx = 0; qctl->qc_idx < count; qctl->qc_idx++) {
2241                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
2242                 rc = llapi_quotactl(mnt, qctl);
2243                 if (rc) {
2244                         /* It is remote client case. */
2245                         if (-rc == EOPNOTSUPP) {
2246                                 rc = 0;
2247                                 goto out;
2248                         }
2249
2250                         if (!rc1)
2251                                 rc1 = rc;
2252                         fprintf(stderr, "quotactl %s%d failed.\n",
2253                                 is_mdt ? "mdt": "ost", qctl->qc_idx);
2254                         continue;
2255                 }
2256
2257                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl, qctl->qc_valid, 0);
2258         }
2259
2260 out:
2261         qctl->qc_valid = valid;
2262         return rc ? : rc1;
2263 }
2264
2265 static int lfs_quota(int argc, char **argv)
2266 {
2267         int c;
2268         char *mnt, *name = NULL;
2269         struct if_quotactl qctl = { .qc_cmd = LUSTRE_Q_GETQUOTA,
2270                                     .qc_type = UGQUOTA };
2271         char *obd_type = (char *)qctl.obd_type;
2272         char *obd_uuid = (char *)qctl.obd_uuid.uuid;
2273         int rc, rc1 = 0, rc2 = 0, rc3 = 0,
2274             verbose = 0, pass = 0, quiet = 0, inacc;
2275         char *endptr;
2276         __u32 valid = QC_GENERAL, idx = 0;
2277
2278         optind = 0;
2279         while ((c = getopt(argc, argv, "gi:I:o:qtuv")) != -1) {
2280                 switch (c) {
2281                 case 'u':
2282                         if (qctl.qc_type != UGQUOTA) {
2283                                 fprintf(stderr, "error: use either -u or -g\n");
2284                                 return CMD_HELP;
2285                         }
2286                         qctl.qc_type = USRQUOTA;
2287                         break;
2288                 case 'g':
2289                         if (qctl.qc_type != UGQUOTA) {
2290                                 fprintf(stderr, "error: use either -u or -g\n");
2291                                 return CMD_HELP;
2292                         }
2293                         qctl.qc_type = GRPQUOTA;
2294                         break;
2295                 case 't':
2296                         qctl.qc_cmd = LUSTRE_Q_GETINFO;
2297                         break;
2298                 case 'o':
2299                         valid = qctl.qc_valid = QC_UUID;
2300                         strncpy(obd_uuid, optarg, sizeof(qctl.obd_uuid));
2301                         break;
2302                 case 'i':
2303                         valid = qctl.qc_valid = QC_MDTIDX;
2304                         idx = qctl.qc_idx = atoi(optarg);
2305                         break;
2306                 case 'I':
2307                         valid = qctl.qc_valid = QC_OSTIDX;
2308                         idx = qctl.qc_idx = atoi(optarg);
2309                         break;
2310                 case 'v':
2311                         verbose = 1;
2312                         break;
2313                 case 'q':
2314                         quiet = 1;
2315                         break;
2316                 default:
2317                         fprintf(stderr, "error: %s: option '-%c' "
2318                                         "unrecognized\n", argv[0], c);
2319                         return CMD_HELP;
2320                 }
2321         }
2322
2323         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
2324         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA && qctl.qc_type == UGQUOTA &&
2325             optind == argc - 1) {
2326 ug_output:
2327                 memset(&qctl, 0, sizeof(qctl)); /* spoiled by print_*_quota */
2328                 qctl.qc_cmd = LUSTRE_Q_GETQUOTA;
2329                 qctl.qc_valid = valid;
2330                 qctl.qc_idx = idx;
2331                 if (pass++ == 0) {
2332                         qctl.qc_type = USRQUOTA;
2333                         qctl.qc_id = geteuid();
2334                 } else {
2335                         qctl.qc_type = GRPQUOTA;
2336                         qctl.qc_id = getegid();
2337                 }
2338                 rc = id2name(&name, qctl.qc_id,
2339                              (qctl.qc_type == USRQUOTA) ? USER : GROUP);
2340                 if (rc)
2341                         name = "<unknown>";
2342         /* lfs quota -u username /path/to/lustre/mount */
2343         } else if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) {
2344                 /* options should be followed by u/g-name and mntpoint */
2345                 if (optind + 2 != argc || qctl.qc_type == UGQUOTA) {
2346                         fprintf(stderr, "error: missing quota argument(s)\n");
2347                         return CMD_HELP;
2348                 }
2349
2350                 name = argv[optind++];
2351                 rc = name2id(&qctl.qc_id, name,
2352                              (qctl.qc_type == USRQUOTA) ? USER : GROUP);
2353                 if (rc) {
2354                         qctl.qc_id = strtoul(name, &endptr, 10);
2355                         if (*endptr != '\0') {
2356                                 fprintf(stderr, "error: can't find id for name "
2357                                         "%s\n", name);
2358                                 return CMD_HELP;
2359                         }
2360                 }
2361         } else if (optind + 1 != argc || qctl.qc_type == UGQUOTA) {
2362                 fprintf(stderr, "error: missing quota info argument(s)\n");
2363                 return CMD_HELP;
2364         }
2365
2366         mnt = argv[optind];
2367
2368         rc1 = llapi_quotactl(mnt, &qctl);
2369         if (rc1 < 0) {
2370                 switch (rc1) {
2371                 case -ESRCH:
2372                         fprintf(stderr, "%s quotas are not enabled.\n",
2373                                 qctl.qc_type == USRQUOTA ? "user" : "group");
2374                         goto out;
2375                 case -EPERM:
2376                         fprintf(stderr, "Permission denied.\n");
2377                 case -ENOENT:
2378                         /* We already got a "No such file..." message. */
2379                         goto out;
2380                 default:
2381                         fprintf(stderr, "Unexpected quotactl error: %s\n",
2382                                 strerror(-rc1));
2383                 }
2384         }
2385
2386         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA && !quiet)
2387                 print_quota_title(name, &qctl);
2388
2389         if (rc1 && *obd_type)
2390                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
2391
2392         if (qctl.qc_valid != QC_GENERAL)
2393                 mnt = "";
2394
2395         inacc = (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) &&
2396                 ((qctl.qc_dqblk.dqb_valid&(QIF_LIMITS|QIF_USAGE))!=(QIF_LIMITS|QIF_USAGE));
2397
2398         print_quota(mnt, &qctl, QC_GENERAL, rc1);
2399
2400         if (qctl.qc_valid == QC_GENERAL && qctl.qc_cmd != LUSTRE_Q_GETINFO && verbose) {
2401                 rc2 = print_obd_quota(mnt, &qctl, 1);
2402                 rc3 = print_obd_quota(mnt, &qctl, 0);
2403         }
2404
2405         if (rc1 || rc2 || rc3 || inacc)
2406                 printf("Some errors happened when getting quota info. "
2407                        "Some devices may be not working or deactivated. "
2408                        "The data in \"[]\" is inaccurate.\n");
2409
2410 out:
2411         if (pass == 1)
2412                 goto ug_output;
2413
2414         return rc1;
2415 }
2416 #endif /* HAVE_SYS_QUOTA_H! */
2417
2418 static int flushctx_ioctl(char *mp)
2419 {
2420         int fd, rc;
2421
2422         fd = open(mp, O_RDONLY);
2423         if (fd == -1) {
2424                 fprintf(stderr, "flushctx: error open %s: %s\n",
2425                         mp, strerror(errno));
2426                 return -1;
2427         }
2428
2429         rc = ioctl(fd, LL_IOC_FLUSHCTX);
2430         if (rc == -1)
2431                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
2432                         mp, strerror(errno));
2433
2434         close(fd);
2435         return rc;
2436 }
2437
2438 static int lfs_flushctx(int argc, char **argv)
2439 {
2440         int     kdestroy = 0, c;
2441         FILE   *proc;
2442         char    procline[PATH_MAX], *line;
2443         int     rc = 0;
2444
2445         optind = 0;
2446         while ((c = getopt(argc, argv, "k")) != -1) {
2447                 switch (c) {
2448                 case 'k':
2449                         kdestroy = 1;
2450                         break;
2451                 default:
2452                         fprintf(stderr, "error: %s: option '-%c' "
2453                                         "unrecognized\n", argv[0], c);
2454                         return CMD_HELP;
2455                 }
2456         }
2457
2458         if (kdestroy) {
2459             int rc;
2460             if ((rc = system("kdestroy > /dev/null")) != 0) {
2461                 rc = WEXITSTATUS(rc);
2462                 fprintf(stderr, "error destroying tickets: %d, continuing\n", rc);
2463             }
2464         }
2465
2466         if (optind >= argc) {
2467                 /* flush for all mounted lustre fs. */
2468                 proc = fopen("/proc/mounts", "r");
2469                 if (!proc) {
2470                         fprintf(stderr, "error: %s: can't open /proc/mounts\n",
2471                                 argv[0]);
2472                         return -1;
2473                 }
2474
2475                 while ((line = fgets(procline, PATH_MAX, proc)) != NULL) {
2476                         char dev[PATH_MAX];
2477                         char mp[PATH_MAX];
2478                         char fs[PATH_MAX];
2479
2480                         if (sscanf(line, "%s %s %s", dev, mp, fs) != 3) {
2481                                 fprintf(stderr, "%s: unexpected format in "
2482                                                 "/proc/mounts\n",
2483                                         argv[0]);
2484                                 return -1;
2485                         }
2486
2487                         if (strcmp(fs, "lustre") != 0)
2488                                 continue;
2489                         /* we use '@' to determine it's a client. are there
2490                          * any other better way?
2491                          */
2492                         if (strchr(dev, '@') == NULL)
2493                                 continue;
2494
2495                         if (flushctx_ioctl(mp))
2496                                 rc = -1;
2497                 }
2498         } else {
2499                 /* flush fs as specified */
2500                 while (optind < argc) {
2501                         if (flushctx_ioctl(argv[optind++]))
2502                                 rc = -1;
2503                 }
2504         }
2505
2506         return rc;
2507 }
2508
2509 static int lfs_lsetfacl(int argc, char **argv)
2510 {
2511         argv[0]++;
2512         return(llapi_lsetfacl(argc, argv));
2513 }
2514
2515 static int lfs_lgetfacl(int argc, char **argv)
2516 {
2517         argv[0]++;
2518         return(llapi_lgetfacl(argc, argv));
2519 }
2520
2521 static int lfs_rsetfacl(int argc, char **argv)
2522 {
2523         argv[0]++;
2524         return(llapi_rsetfacl(argc, argv));
2525 }
2526
2527 static int lfs_rgetfacl(int argc, char **argv)
2528 {
2529         argv[0]++;
2530         return(llapi_rgetfacl(argc, argv));
2531 }
2532
2533 static int lfs_cp(int argc, char **argv)
2534 {
2535         return(llapi_cp(argc, argv));
2536 }
2537
2538 static int lfs_ls(int argc, char **argv)
2539 {
2540         return(llapi_ls(argc, argv));
2541 }
2542
2543 static int lfs_changelog(int argc, char **argv)
2544 {
2545         void *changelog_priv;
2546         struct changelog_rec *rec;
2547         long long startrec = 0, endrec = 0;
2548         char *mdd;
2549         struct option long_opts[] = {
2550                 {"follow", no_argument, 0, 'f'},
2551                 {0, 0, 0, 0}
2552         };
2553         char short_opts[] = "f";
2554         int rc, follow = 0;
2555
2556         optind = 0;
2557         while ((rc = getopt_long(argc, argv, short_opts,
2558                                 long_opts, NULL)) != -1) {
2559                 switch (rc) {
2560                 case 'f':
2561                         follow++;
2562                         break;
2563                 case '?':
2564                         return CMD_HELP;
2565                 default:
2566                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
2567                                 argv[0], argv[optind - 1]);
2568                         return CMD_HELP;
2569                 }
2570         }
2571         if (optind >= argc)
2572                 return CMD_HELP;
2573
2574         mdd = argv[optind++];
2575         if (argc > optind)
2576                 startrec = strtoll(argv[optind++], NULL, 10);
2577         if (argc > optind)
2578                 endrec = strtoll(argv[optind++], NULL, 10);
2579
2580         rc = llapi_changelog_start(&changelog_priv,
2581                                    CHANGELOG_FLAG_BLOCK |
2582                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
2583                                    mdd, startrec);
2584         if (rc < 0) {
2585                 fprintf(stderr, "Can't start changelog: %s\n",
2586                         strerror(errno = -rc));
2587                 return rc;
2588         }
2589
2590         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
2591                 time_t secs;
2592                 struct tm ts;
2593
2594                 if (endrec && rec->cr_index > endrec) {
2595                         llapi_changelog_free(&rec);
2596                         break;
2597                 }
2598                 if (rec->cr_index < startrec) {
2599                         llapi_changelog_free(&rec);
2600                         continue;
2601                 }
2602
2603                 secs = rec->cr_time >> 30;
2604                 gmtime_r(&secs, &ts);
2605                 printf(LPU64" %02d%-5s %02d:%02d:%02d.%06d %04d.%02d.%02d "
2606                        "0x%x t="DFID, rec->cr_index, rec->cr_type,
2607                        changelog_type2str(rec->cr_type),
2608                        ts.tm_hour, ts.tm_min, ts.tm_sec,
2609                        (int)(rec->cr_time & ((1<<30) - 1)),
2610                        ts.tm_year+1900, ts.tm_mon+1, ts.tm_mday,
2611                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
2612                 if (rec->cr_namelen)
2613                         /* namespace rec includes parent and filename */
2614                         printf(" p="DFID" %.*s\n", PFID(&rec->cr_pfid),
2615                                rec->cr_namelen, rec->cr_name);
2616                 else
2617                         printf("\n");
2618
2619                 llapi_changelog_free(&rec);
2620         }
2621
2622         llapi_changelog_fini(&changelog_priv);
2623
2624         if (rc < 0)
2625                 fprintf(stderr, "Changelog: %s\n", strerror(errno = -rc));
2626
2627         return (rc == 1 ? 0 : rc);
2628 }
2629
2630 static int lfs_changelog_clear(int argc, char **argv)
2631 {
2632         long long endrec;
2633         int rc;
2634
2635         if (argc != 4)
2636                 return CMD_HELP;
2637
2638         endrec = strtoll(argv[3], NULL, 10);
2639
2640         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
2641         if (rc)
2642                 fprintf(stderr, "%s error: %s\n", argv[0],
2643                         strerror(errno = -rc));
2644         return rc;
2645 }
2646
2647 static int lfs_fid2path(int argc, char **argv)
2648 {
2649         struct option long_opts[] = {
2650                 {"cur", no_argument, 0, 'c'},
2651                 {"link", required_argument, 0, 'l'},
2652                 {"rec", required_argument, 0, 'r'},
2653                 {0, 0, 0, 0}
2654         };
2655         char  short_opts[] = "cl:r:";
2656         char *device, *fid, *path;
2657         long long recno = -1;
2658         int linkno = -1;
2659         int lnktmp;
2660         int printcur = 0;
2661         int rc;
2662
2663         optind = 0;
2664
2665         while ((rc = getopt_long(argc, argv, short_opts,
2666                                 long_opts, NULL)) != -1) {
2667                 switch (rc) {
2668                 case 'c':
2669                         printcur++;
2670                         break;
2671                 case 'l':
2672                         linkno = strtol(optarg, NULL, 10);
2673                         break;
2674                 case 'r':
2675                         recno = strtoll(optarg, NULL, 10);
2676                         break;
2677                 case '?':
2678                         return CMD_HELP;
2679                 default:
2680                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
2681                                 argv[0], argv[optind - 1]);
2682                         return CMD_HELP;
2683                 }
2684         }
2685         device = argv[optind++];
2686         fid = argv[optind++];
2687         if (optind != argc)
2688                 return CMD_HELP;
2689
2690         path = calloc(1, PATH_MAX);
2691
2692         lnktmp = (linkno >= 0) ? linkno : 0;
2693         while (1) {
2694                 int oldtmp = lnktmp;
2695                 long long rectmp = recno;
2696                 rc = llapi_fid2path(device, fid, path, PATH_MAX, &rectmp,
2697                                     &lnktmp);
2698                 if (rc < 0) {
2699                         fprintf(stderr, "%s error: %s\n", argv[0],
2700                                 strerror(errno = -rc));
2701                         break;
2702                 }
2703
2704                 if (printcur)
2705                         fprintf(stdout, "%lld ", rectmp);
2706                 if (device[0] == '/') {
2707                         fprintf(stdout, "%s", device);
2708                         if (device[strlen(device) - 1] != '/')
2709                                 fprintf(stdout, "/");
2710                 } else if (path[0] == '\0') {
2711                         fprintf(stdout, "/");
2712                 }
2713                 fprintf(stdout, "%s\n", path);
2714
2715                 if (linkno >= 0)
2716                         /* specified linkno */
2717                         break;
2718                 if (oldtmp == lnktmp)
2719                         /* no more links */
2720                         break;
2721         }
2722
2723         free(path);
2724         return rc;
2725 }
2726
2727 static int lfs_path2fid(int argc, char **argv)
2728 {
2729         char *path;
2730         lustre_fid fid;
2731         int rc;
2732
2733         if (argc != 2)
2734                 return CMD_HELP;
2735
2736         path = argv[1];
2737         rc = llapi_path2fid(path, &fid);
2738         if (rc) {
2739                 fprintf(stderr, "can't get fid for %s: %s\n", path,
2740                         strerror(errno = -rc));
2741                 return rc;
2742         }
2743
2744         printf(DFID"\n", PFID(&fid));
2745
2746         return 0;
2747 }
2748
2749 static int lfs_data_version(int argc, char **argv)
2750 {
2751         char *path;
2752         __u64 data_version;
2753         int fd;
2754         int rc;
2755         int c;
2756         int nolock = 0;
2757
2758         if (argc < 2)
2759                 return CMD_HELP;
2760
2761         optind = 0;
2762         while ((c = getopt(argc, argv, "n")) != -1) {
2763                 switch (c) {
2764                 case 'n':
2765                         nolock = LL_DV_NOFLUSH;
2766                         break;
2767                 default:
2768                         return CMD_HELP;
2769                 }
2770         }
2771         if (optind == argc)
2772                 return CMD_HELP;
2773
2774         path = argv[optind];
2775         fd = open(path, O_RDONLY);
2776         if (fd < 0) {
2777                 fprintf(stderr, "can't open %s: %s\n", path,
2778                         strerror(errno));
2779                 return errno;
2780         }
2781
2782         rc = llapi_get_data_version(fd, &data_version, nolock);
2783         if (rc) {
2784                 fprintf(stderr, "can't get version for %s: %s\n", path,
2785                         strerror(errno = -rc));
2786                 return rc;
2787         }
2788
2789         printf("%llu\n", data_version);
2790
2791         close(fd);
2792
2793         return 0;
2794 }
2795
2796 int main(int argc, char **argv)
2797 {
2798         int rc;
2799
2800         setlinebuf(stdout);
2801
2802         ptl_initialize(argc, argv);
2803         if (obd_initialize(argc, argv) < 0)
2804                 exit(2);
2805         if (dbg_initialize(argc, argv) < 0)
2806                 exit(3);
2807
2808         Parser_init("lfs > ", cmdlist);
2809
2810         if (argc > 1) {
2811                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
2812         } else {
2813                 rc = Parser_commands();
2814         }
2815
2816         obd_finalize(argc, argv);
2817         return rc < 0 ? -rc : rc;
2818 }
2819