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