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