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