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