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