Whamcloud - gitweb
LU-4724 hsm: Safe copytool event logging
[fs/lustre-release.git] / lustre / utils / lfs.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 2013, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/utils/lfs.c
37  *
38  * Author: Peter J. Braam <braam@clusterfs.com>
39  * Author: Phil Schwan <phil@clusterfs.com>
40  * Author: Robert Read <rread@clusterfs.com>
41  */
42
43 /* for O_DIRECTORY */
44 #ifndef _GNU_SOURCE
45 #define _GNU_SOURCE
46 #endif
47
48 #include <stdlib.h>
49 #include <stdio.h>
50 #include <getopt.h>
51 #include <string.h>
52 #include <mntent.h>
53 #include <errno.h>
54 #include <err.h>
55 #include <pwd.h>
56 #include <grp.h>
57 #include <sys/types.h>
58 #include <sys/stat.h>
59 #include <fcntl.h>
60 #include <dirent.h>
61 #include <time.h>
62 #include <ctype.h>
63 #ifdef HAVE_SYS_QUOTA_H
64 # include <sys/quota.h>
65 #endif
66
67 /* For dirname() */
68 #include <libgen.h>
69
70 #include <lnet/lnetctl.h>
71
72 #include <liblustre.h>
73 #include <lustre/lustreapi.h>
74
75 #include <libcfs/libcfsutil.h>
76 #include <obd.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 = { .maxdepth = -1, .quiet = 1 };
890         struct option long_opts[] = {
891                 {"atime",        required_argument, 0, 'A'},
892                 {"stripe-count", required_argument, 0, 'c'},
893                 {"stripe_count", required_argument, 0, 'c'},
894                 {"ctime",        required_argument, 0, 'C'},
895                 {"maxdepth",     required_argument, 0, 'D'},
896                 {"gid",          required_argument, 0, 'g'},
897                 {"group",        required_argument, 0, 'G'},
898                 {"stripe-index", required_argument, 0, 'i'},
899                 {"stripe_index", required_argument, 0, 'i'},
900                 {"layout",       required_argument, 0, 'L'},
901                 {"mdt",          required_argument, 0, 'm'},
902                 {"mtime",        required_argument, 0, 'M'},
903                 {"name",         required_argument, 0, 'n'},
904      /* reserve {"or",           no_argument,     , 0, 'o'}, to match find(1) */
905                 {"obd",          required_argument, 0, 'O'},
906                 {"ost",          required_argument, 0, 'O'},
907                 /* no short option for pool, p/P already used */
908                 {"pool",         required_argument, 0, FIND_POOL_OPT},
909                 {"print0",       no_argument,       0, 'p'},
910                 {"print",        no_argument,       0, 'P'},
911                 {"size",         required_argument, 0, 's'},
912                 {"stripe-size",  required_argument, 0, 'S'},
913                 {"stripe_size",  required_argument, 0, 'S'},
914                 {"type",         required_argument, 0, 't'},
915                 {"uid",          required_argument, 0, 'u'},
916                 {"user",         required_argument, 0, 'U'},
917                 {0, 0, 0, 0}
918         };
919         int pathstart = -1;
920         int pathend = -1;
921         int neg_opt = 0;
922         time_t *xtime;
923         int *xsign;
924         int isoption;
925         char *endptr;
926
927         time(&t);
928
929         optind = 0;
930         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
931         while ((c = getopt_long_only(argc, argv,
932                                      "-A:c:C:D:g:G:i:L:m:M:n:O:Ppqrs:S:t:u:U:v",
933                                      long_opts, NULL)) >= 0) {
934                 xtime = NULL;
935                 xsign = NULL;
936                 if (neg_opt)
937                         --neg_opt;
938                 /* '!' is part of option */
939                 /* when getopt_long_only() finds a string which is not
940                  * an option nor a known option argument it returns 1
941                  * in that case if we already have found pathstart and pathend
942                  * (i.e. we have the list of pathnames),
943                  * the only supported value is "!"
944                  */
945                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
946                 if (!isoption && pathend != -1) {
947                         fprintf(stderr, "err: %s: filename|dirname must either "
948                                         "precede options or follow options\n",
949                                         argv[0]);
950                         ret = CMD_HELP;
951                         goto err;
952                 }
953                 if (!isoption && pathstart == -1)
954                         pathstart = optind - 1;
955                 if (isoption && pathstart != -1 && pathend == -1)
956                         pathend = optind - 2;
957                 switch (c) {
958                 case 0:
959                         /* Long options. */
960                         break;
961                 case 1:
962                         /* unknown; opt is "!" or path component,
963                          * checking done above.
964                          */
965                         if (strcmp(optarg, "!") == 0)
966                                 neg_opt = 2;
967                         break;
968                 case 'A':
969                         xtime = &param.atime;
970                         xsign = &param.asign;
971                         param.exclude_atime = !!neg_opt;
972                         /* no break, this falls through to 'C' for ctime */
973                 case 'C':
974                         if (c == 'C') {
975                                 xtime = &param.ctime;
976                                 xsign = &param.csign;
977                                 param.exclude_ctime = !!neg_opt;
978                         }
979                         /* no break, this falls through to 'M' for mtime */
980                 case 'M':
981                         if (c == 'M') {
982                                 xtime = &param.mtime;
983                                 xsign = &param.msign;
984                                 param.exclude_mtime = !!neg_opt;
985                         }
986                         ret = set_time(&t, xtime, optarg);
987                         if (ret == INT_MAX) {
988                                 ret = -1;
989                                 goto err;
990                         }
991                         if (ret)
992                                 *xsign = ret;
993                         break;
994                 case 'c':
995                         if (optarg[0] == '+') {
996                                 param.stripecount_sign = -1;
997                                 optarg++;
998                         } else if (optarg[0] == '-') {
999                                 param.stripecount_sign =  1;
1000                                 optarg++;
1001                         }
1002
1003                         param.stripecount = strtoul(optarg, &endptr, 0);
1004                         if (*endptr != '\0') {
1005                                 fprintf(stderr,"error: bad stripe_count '%s'\n",
1006                                         optarg);
1007                                 ret = -1;
1008                                 goto err;
1009                         }
1010                         param.check_stripecount = 1;
1011                         param.exclude_stripecount = !!neg_opt;
1012                         break;
1013                 case 'D':
1014                         param.maxdepth = strtol(optarg, 0, 0);
1015                         break;
1016                 case 'g':
1017                 case 'G':
1018                         ret = name2id(&param.gid, optarg, GROUP);
1019                         if (ret) {
1020                                 param.gid = strtoul(optarg, &endptr, 10);
1021                                 if (*endptr != '\0') {
1022                                         fprintf(stderr, "Group/GID: %s cannot "
1023                                                 "be found.\n", optarg);
1024                                         ret = -1;
1025                                         goto err;
1026                                 }
1027                         }
1028                         param.exclude_gid = !!neg_opt;
1029                         param.check_gid = 1;
1030                         break;
1031                 case 'L':
1032                         ret = name2layout(&param.layout, optarg);
1033                         if (ret)
1034                                 goto err;
1035                         param.exclude_layout = !!neg_opt;
1036                         param.check_layout = 1;
1037                         break;
1038                 case 'u':
1039                 case 'U':
1040                         ret = name2id(&param.uid, optarg, USER);
1041                         if (ret) {
1042                                 param.uid = strtoul(optarg, &endptr, 10);
1043                                 if (*endptr != '\0') {
1044                                         fprintf(stderr, "User/UID: %s cannot "
1045                                                 "be found.\n", optarg);
1046                                         ret = -1;
1047                                         goto err;
1048                                 }
1049                         }
1050                         param.exclude_uid = !!neg_opt;
1051                         param.check_uid = 1;
1052                         break;
1053                 case FIND_POOL_OPT:
1054                         if (strlen(optarg) > LOV_MAXPOOLNAME) {
1055                                 fprintf(stderr,
1056                                         "Pool name %s is too long"
1057                                         " (max is %d)\n", optarg,
1058                                         LOV_MAXPOOLNAME);
1059                                 ret = -1;
1060                                 goto err;
1061                         }
1062                         /* we do check for empty pool because empty pool
1063                          * is used to find V1 lov attributes */
1064                         strncpy(param.poolname, optarg, LOV_MAXPOOLNAME);
1065                         param.poolname[LOV_MAXPOOLNAME] = '\0';
1066                         param.exclude_pool = !!neg_opt;
1067                         param.check_pool = 1;
1068                         break;
1069                 case 'n':
1070                         param.pattern = (char *)optarg;
1071                         param.exclude_pattern = !!neg_opt;
1072                         break;
1073                 case 'm':
1074                 case 'i':
1075                 case 'O': {
1076                         char *buf, *token, *next, *p;
1077                         int len = 1;
1078                         void *tmp;
1079
1080                         buf = strdup(optarg);
1081                         if (buf == NULL) {
1082                                 ret = -ENOMEM;
1083                                 goto err;
1084                         }
1085
1086                         param.exclude_obd = !!neg_opt;
1087
1088                         token = buf;
1089                         while (token && *token) {
1090                                 token = strchr(token, ',');
1091                                 if (token) {
1092                                         len++;
1093                                         token++;
1094                                 }
1095                         }
1096                         if (c == 'm') {
1097                                 param.exclude_mdt = !!neg_opt;
1098                                 param.num_alloc_mdts += len;
1099                                 tmp = realloc(param.mdtuuid,
1100                                               param.num_alloc_mdts *
1101                                               sizeof(*param.mdtuuid));
1102                                 if (tmp == NULL)
1103                                         GOTO(err_free, ret = -ENOMEM);
1104                                 param.mdtuuid = tmp;
1105                         } else {
1106                                 param.exclude_obd = !!neg_opt;
1107                                 param.num_alloc_obds += len;
1108                                 tmp = realloc(param.obduuid,
1109                                               param.num_alloc_obds *
1110                                               sizeof(*param.obduuid));
1111                                 if (tmp == NULL)
1112                                         GOTO(err_free, ret = -ENOMEM);
1113                                 param.obduuid = tmp;
1114                         }
1115                         for (token = buf; token && *token; token = next) {
1116                                 struct obd_uuid *puuid;
1117                                 if (c == 'm') {
1118                                         puuid =
1119                                           &param.mdtuuid[param.num_mdts++];
1120                                 } else {
1121                                         puuid =
1122                                           &param.obduuid[param.num_obds++];
1123                                 }
1124                                 p = strchr(token, ',');
1125                                 next = 0;
1126                                 if (p) {
1127                                         *p = 0;
1128                                         next = p+1;
1129                                 }
1130                                 if (strlen(token) > sizeof(puuid->uuid)-1)
1131                                         GOTO(err_free, ret = -E2BIG);
1132                                 strncpy(puuid->uuid, token,
1133                                         sizeof(puuid->uuid));
1134                         }
1135 err_free:
1136                         if (buf)
1137                                 free(buf);
1138                         break;
1139                 }
1140                 case 'p':
1141                         param.zeroend = 1;
1142                         break;
1143                 case 'P':
1144                         break;
1145                 case 's':
1146                         if (optarg[0] == '+') {
1147                                 param.size_sign = -1;
1148                                 optarg++;
1149                         } else if (optarg[0] == '-') {
1150                                 param.size_sign =  1;
1151                                 optarg++;
1152                         }
1153
1154                         ret = llapi_parse_size(optarg, &param.size,
1155                                                &param.size_units, 0);
1156                         if (ret) {
1157                                 fprintf(stderr, "error: bad file size '%s'\n",
1158                                         optarg);
1159                                 goto err;
1160                         }
1161                         param.check_size = 1;
1162                         param.exclude_size = !!neg_opt;
1163                         break;
1164                 case 'S':
1165                         if (optarg[0] == '+') {
1166                                 param.stripesize_sign = -1;
1167                                 optarg++;
1168                         } else if (optarg[0] == '-') {
1169                                 param.stripesize_sign =  1;
1170                                 optarg++;
1171                         }
1172
1173                         ret = llapi_parse_size(optarg, &param.stripesize,
1174                                                &param.stripesize_units, 0);
1175                         if (ret) {
1176                                 fprintf(stderr, "error: bad stripe_size '%s'\n",
1177                                         optarg);
1178                                 goto err;
1179                         }
1180                         param.check_stripesize = 1;
1181                         param.exclude_stripesize = !!neg_opt;
1182                         break;
1183                 case 't':
1184                         param.exclude_type = !!neg_opt;
1185                         switch(optarg[0]) {
1186                         case 'b': param.type = S_IFBLK; break;
1187                         case 'c': param.type = S_IFCHR; break;
1188                         case 'd': param.type = S_IFDIR; break;
1189                         case 'f': param.type = S_IFREG; break;
1190                         case 'l': param.type = S_IFLNK; break;
1191                         case 'p': param.type = S_IFIFO; break;
1192                         case 's': param.type = S_IFSOCK; break;
1193 #ifdef S_IFDOOR /* Solaris only */
1194                         case 'D': param.type = S_IFDOOR; break;
1195 #endif
1196                         default: fprintf(stderr, "error: %s: bad type '%s'\n",
1197                                          argv[0], optarg);
1198                                  ret = CMD_HELP;
1199                                  goto err;
1200                         };
1201                         break;
1202                 default:
1203                         ret = CMD_HELP;
1204                         goto err;
1205                 };
1206         }
1207
1208         if (pathstart == -1) {
1209                 fprintf(stderr, "error: %s: no filename|pathname\n",
1210                         argv[0]);
1211                 ret = CMD_HELP;
1212                 goto err;
1213         } else if (pathend == -1) {
1214                 /* no options */
1215                 pathend = argc;
1216         }
1217
1218         do {
1219                 ret = llapi_find(argv[pathstart], &param);
1220         } while (++pathstart < pathend && !ret);
1221
1222         if (ret)
1223                 fprintf(stderr, "error: %s failed for %s.\n",
1224                         argv[0], argv[optind - 1]);
1225 err:
1226         if (param.obduuid && param.num_alloc_obds)
1227                 free(param.obduuid);
1228
1229         if (param.mdtuuid && param.num_alloc_mdts)
1230                 free(param.mdtuuid);
1231
1232         return ret;
1233 }
1234
1235 static int lfs_getstripe_internal(int argc, char **argv,
1236                                   struct find_param *param)
1237 {
1238         struct option long_opts[] = {
1239 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1240                 /* This formerly implied "stripe-count", but was explicitly
1241                  * made "stripe-count" for consistency with other options,
1242                  * and to separate it from "mdt-count" when DNE arrives. */
1243                 {"count",               no_argument,            0, 'c'},
1244 #endif
1245                 {"stripe-count",        no_argument,            0, 'c'},
1246                 {"stripe_count",        no_argument,            0, 'c'},
1247                 {"directory",           no_argument,            0, 'd'},
1248                 {"default",             no_argument,            0, 'D'},
1249                 {"generation",          no_argument,            0, 'g'},
1250 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1251                 /* This formerly implied "stripe-index", but was explicitly
1252                  * made "stripe-index" for consistency with other options,
1253                  * and to separate it from "mdt-index" when DNE arrives. */
1254                 {"index",               no_argument,            0, 'i'},
1255 #endif
1256                 {"stripe-index",        no_argument,            0, 'i'},
1257                 {"stripe_index",        no_argument,            0, 'i'},
1258                 {"layout",              no_argument,            0, 'L'},
1259                 {"mdt-index",           no_argument,            0, 'M'},
1260                 {"mdt_index",           no_argument,            0, 'M'},
1261 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1262                 /* This formerly implied "stripe-index", but was confusing
1263                  * with "file offset" (which will eventually be needed for
1264                  * with different layouts by offset), so deprecate it. */
1265                 {"offset",              no_argument,            0, 'o'},
1266 #endif
1267                 {"obd",                 required_argument,      0, 'O'},
1268                 {"ost",                 required_argument,      0, 'O'},
1269                 {"pool",                no_argument,            0, 'p'},
1270                 {"quiet",               no_argument,            0, 'q'},
1271                 {"recursive",           no_argument,            0, 'r'},
1272                 {"raw",                 no_argument,            0, 'R'},
1273 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1274                 /* This formerly implied "--stripe-size", but was confusing
1275                  * with "lfs find --size|-s", which means "file size", so use
1276                  * the consistent "--stripe-size|-S" for all commands. */
1277                 {"size",                no_argument,            0, 's'},
1278 #endif
1279                 {"stripe-size",         no_argument,            0, 'S'},
1280                 {"stripe_size",         no_argument,            0, 'S'},
1281                 {"verbose",             no_argument,            0, 'v'},
1282                 {0, 0, 0, 0}
1283         };
1284         int c, rc;
1285
1286         param->maxdepth = 1;
1287         optind = 0;
1288         while ((c = getopt_long(argc, argv, "cdDghiLMoO:pqrRsSv",
1289                                 long_opts, NULL)) != -1) {
1290                 switch (c) {
1291                 case 'O':
1292                         if (param->obduuid) {
1293                                 fprintf(stderr,
1294                                         "error: %s: only one obduuid allowed",
1295                                         argv[0]);
1296                                 return CMD_HELP;
1297                         }
1298                         param->obduuid = (struct obd_uuid *)optarg;
1299                         break;
1300                 case 'q':
1301                         param->quiet++;
1302                         break;
1303                 case 'd':
1304                         param->maxdepth = 0;
1305                         break;
1306                 case 'D':
1307                         param->get_default_lmv = 1;
1308                         break;
1309                 case 'r':
1310                         param->recursive = 1;
1311                         break;
1312                 case 'v':
1313                         param->verbose = VERBOSE_ALL | VERBOSE_DETAIL;
1314                         break;
1315                 case 'c':
1316 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 6, 53, 0)
1317                         if (strcmp(argv[optind - 1], "--count") == 0)
1318                                 fprintf(stderr, "warning: '--count' deprecated,"
1319                                         " use '--stripe-count' instead\n");
1320 #endif
1321                         if (!(param->verbose & VERBOSE_DETAIL)) {
1322                                 param->verbose |= VERBOSE_COUNT;
1323                                 param->maxdepth = 0;
1324                         }
1325                         break;
1326 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1327                 case 's':
1328 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 6, 53, 0)
1329                         fprintf(stderr, "warning: '--size|-s' deprecated, "
1330                                 "use '--stripe-size|-S' instead\n");
1331 #endif
1332 #endif /* LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0) */
1333                 case 'S':
1334                         if (!(param->verbose & VERBOSE_DETAIL)) {
1335                                 param->verbose |= VERBOSE_SIZE;
1336                                 param->maxdepth = 0;
1337                         }
1338                         break;
1339 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1340                 case 'o':
1341                         fprintf(stderr, "warning: '--offset|-o' deprecated, "
1342                                 "use '--stripe-index|-i' instead\n");
1343 #endif
1344                 case 'i':
1345 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 6, 53, 0)
1346                         if (strcmp(argv[optind - 1], "--index") == 0)
1347                                 fprintf(stderr, "warning: '--index' deprecated"
1348                                         ", use '--stripe-index' instead\n");
1349 #endif
1350                         if (!(param->verbose & VERBOSE_DETAIL)) {
1351                                 param->verbose |= VERBOSE_OFFSET;
1352                                 param->maxdepth = 0;
1353                         }
1354                         break;
1355                 case 'p':
1356                         if (!(param->verbose & VERBOSE_DETAIL)) {
1357                                 param->verbose |= VERBOSE_POOL;
1358                                 param->maxdepth = 0;
1359                         }
1360                         break;
1361                 case 'g':
1362                         if (!(param->verbose & VERBOSE_DETAIL)) {
1363                                 param->verbose |= VERBOSE_GENERATION;
1364                                 param->maxdepth = 0;
1365                         }
1366                         break;
1367                 case 'L':
1368                         if (!(param->verbose & VERBOSE_DETAIL)) {
1369                                 param->verbose |= VERBOSE_LAYOUT;
1370                                 param->maxdepth = 0;
1371                         }
1372                         break;
1373                 case 'M':
1374                         if (!(param->verbose & VERBOSE_DETAIL))
1375                                 param->maxdepth = 0;
1376                         param->verbose |= VERBOSE_MDTINDEX;
1377                         break;
1378                 case 'R':
1379                         param->raw = 1;
1380                         break;
1381                 default:
1382                         return CMD_HELP;
1383                 }
1384         }
1385
1386         if (optind >= argc)
1387                 return CMD_HELP;
1388
1389         if (param->recursive)
1390                 param->maxdepth = -1;
1391
1392         if (!param->verbose)
1393                 param->verbose = VERBOSE_ALL;
1394         if (param->quiet)
1395                 param->verbose = VERBOSE_OBJID;
1396
1397         do {
1398                 rc = llapi_getstripe(argv[optind], param);
1399         } while (++optind < argc && !rc);
1400
1401         if (rc)
1402                 fprintf(stderr, "error: %s failed for %s.\n",
1403                         argv[0], argv[optind - 1]);
1404         return rc;
1405 }
1406
1407 static int lfs_tgts(int argc, char **argv)
1408 {
1409         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
1410         struct find_param param;
1411         int index = 0, rc=0;
1412
1413         if (argc > 2)
1414                 return CMD_HELP;
1415
1416         if (argc == 2 && !realpath(argv[1], path)) {
1417                 rc = -errno;
1418                 fprintf(stderr, "error: invalid path '%s': %s\n",
1419                         argv[1], strerror(-rc));
1420                 return rc;
1421         }
1422
1423         while (!llapi_search_mounts(path, index++, mntdir, NULL)) {
1424                 /* Check if we have a mount point */
1425                 if (mntdir[0] == '\0')
1426                         continue;
1427
1428                 memset(&param, 0, sizeof(param));
1429                 if (!strcmp(argv[0], "mdts"))
1430                         param.get_lmv = 1;
1431
1432                 rc = llapi_ostlist(mntdir, &param);
1433                 if (rc) {
1434                         fprintf(stderr, "error: %s: failed on %s\n",
1435                                 argv[0], mntdir);
1436                 }
1437                 if (path[0] != '\0')
1438                         break;
1439                 memset(mntdir, 0, PATH_MAX);
1440         }
1441
1442         return rc;
1443 }
1444
1445 static int lfs_getstripe(int argc, char **argv)
1446 {
1447         struct find_param param = { 0 };
1448         return lfs_getstripe_internal(argc, argv, &param);
1449 }
1450
1451 /* functions */
1452 static int lfs_getdirstripe(int argc, char **argv)
1453 {
1454         struct find_param param = { 0 };
1455
1456         param.get_lmv = 1;
1457         return lfs_getstripe_internal(argc, argv, &param);
1458 }
1459
1460 /* functions */
1461 static int lfs_setdirstripe(int argc, char **argv)
1462 {
1463         char                    *dname;
1464         int                     result;
1465         unsigned int            stripe_offset = -1;
1466         unsigned int            stripe_count = 1;
1467         enum lmv_hash_type      hash_type;
1468         char                    *end;
1469         int                     c;
1470         char                    *stripe_offset_opt = NULL;
1471         char                    *stripe_count_opt = NULL;
1472         char                    *stripe_hash_opt = NULL;
1473         int                     default_stripe = 0;
1474
1475         struct option long_opts[] = {
1476                 {"count",       required_argument, 0, 'c'},
1477                 {"index",       required_argument, 0, 'i'},
1478                 {"hash-type",   required_argument, 0, 't'},
1479                 {"default_stripe", required_argument, 0, 'D'},
1480                 {0, 0, 0, 0}
1481         };
1482
1483         optind = 0;
1484
1485         while ((c = getopt_long(argc, argv, "c:Di:t:", long_opts, NULL)) >= 0) {
1486                 switch (c) {
1487                 case 0:
1488                         /* Long options. */
1489                         break;
1490                 case 'c':
1491                         stripe_count_opt = optarg;
1492                         break;
1493                 case 'D':
1494                         default_stripe = 1;
1495                         break;
1496                 case 'i':
1497                         stripe_offset_opt = optarg;
1498                         break;
1499                 case 't':
1500                         stripe_hash_opt = optarg;
1501                         break;
1502                 default:
1503                         fprintf(stderr, "error: %s: option '%s' "
1504                                         "unrecognized\n",
1505                                         argv[0], argv[optind - 1]);
1506                         return CMD_HELP;
1507                 }
1508         }
1509
1510         if (optind == argc) {
1511                 fprintf(stderr, "error: %s: missing dirname\n",
1512                         argv[0]);
1513                 return CMD_HELP;
1514         }
1515
1516         if (stripe_offset_opt == NULL && stripe_count_opt == NULL) {
1517                 fprintf(stderr, "error: %s: missing stripe offset and count.\n",
1518                         argv[0]);
1519                 return CMD_HELP;
1520         }
1521
1522         if (stripe_offset_opt != NULL) {
1523                 /* get the stripe offset */
1524                 stripe_offset = strtoul(stripe_offset_opt, &end, 0);
1525                 if (*end != '\0') {
1526                         fprintf(stderr, "error: %s: bad stripe offset '%s'\n",
1527                                 argv[0], stripe_offset_opt);
1528                         return CMD_HELP;
1529                 }
1530         }
1531
1532         if (stripe_hash_opt == NULL ||
1533             strcmp(stripe_hash_opt, LMV_HASH_NAME_FNV_1A_64) == 0) {
1534                 hash_type = LMV_HASH_TYPE_FNV_1A_64;
1535         } else if (strcmp(stripe_hash_opt, LMV_HASH_NAME_ALL_CHARS) == 0) {
1536                 hash_type = LMV_HASH_TYPE_ALL_CHARS;
1537         } else {
1538                 fprintf(stderr, "error: %s: bad stripe hash type '%s'\n",
1539                         argv[0], stripe_hash_opt);
1540                 return CMD_HELP;
1541         }
1542
1543         /* get the stripe count */
1544         if (stripe_count_opt != NULL) {
1545                 stripe_count = strtoul(stripe_count_opt, &end, 0);
1546                 if (*end != '\0') {
1547                         fprintf(stderr, "error: %s: bad stripe count '%s'\n",
1548                                 argv[0], stripe_count_opt);
1549                         return CMD_HELP;
1550                 }
1551         }
1552
1553         dname = argv[optind];
1554         do {
1555                 if (default_stripe == 1) {
1556                         result = llapi_dir_set_default_lmv_stripe(dname,
1557                                                     stripe_offset, stripe_count,
1558                                                     hash_type, NULL);
1559                 } else {
1560                         result = llapi_dir_create_pool(dname, 0, stripe_offset,
1561                                                        stripe_count, hash_type,
1562                                                        NULL);
1563                 }
1564
1565                 if (result) {
1566                         fprintf(stderr, "error: %s: create stripe dir '%s' "
1567                                 "failed\n", argv[0], dname);
1568                         break;
1569                 }
1570                 dname = argv[++optind];
1571         } while (dname != NULL);
1572
1573         return result;
1574 }
1575
1576 /* functions */
1577 static int lfs_rmentry(int argc, char **argv)
1578 {
1579         char *dname;
1580         int   index;
1581         int   result = 0;
1582
1583         if (argc <= 1) {
1584                 fprintf(stderr, "error: %s: missing dirname\n",
1585                         argv[0]);
1586                 return CMD_HELP;
1587         }
1588
1589         index = 1;
1590         dname = argv[index];
1591         while (dname != NULL) {
1592                 result = llapi_direntry_remove(dname);
1593                 if (result) {
1594                         fprintf(stderr, "error: %s: remove dir entry '%s' "
1595                                 "failed\n", argv[0], dname);
1596                         break;
1597                 }
1598                 dname = argv[++index];
1599         }
1600         return result;
1601 }
1602
1603 static int lfs_mv(int argc, char **argv)
1604 {
1605         struct  find_param param = { .maxdepth = -1, .mdtindex = -1};
1606         char   *end;
1607         int     c;
1608         int     rc = 0;
1609         struct option long_opts[] = {
1610                 {"--mdt-index", required_argument, 0, 'M'},
1611                 {"verbose",     no_argument,       0, 'v'},
1612                 {0, 0, 0, 0}
1613         };
1614
1615         while ((c = getopt_long(argc, argv, "M:v", long_opts, NULL)) != -1) {
1616                 switch (c) {
1617                 case 'M': {
1618                         param.mdtindex = strtoul(optarg, &end, 0);
1619                         if (*end != '\0') {
1620                                 fprintf(stderr, "%s: invalid MDT index'%s'\n",
1621                                         argv[0], optarg);
1622                                 return CMD_HELP;
1623                         }
1624                         break;
1625                 }
1626                 case 'v': {
1627                         param.verbose = VERBOSE_DETAIL;
1628                         break;
1629                 }
1630                 default:
1631                         fprintf(stderr, "error: %s: unrecognized option '%s'\n",
1632                                 argv[0], argv[optind - 1]);
1633                         return CMD_HELP;
1634                 }
1635         }
1636
1637         if (param.mdtindex == -1) {
1638                 fprintf(stderr, "%s MDT index must be indicated\n", argv[0]);
1639                 return CMD_HELP;
1640         }
1641
1642         if (optind >= argc) {
1643                 fprintf(stderr, "%s missing operand path\n", argv[0]);
1644                 return CMD_HELP;
1645         }
1646
1647         param.migrate = 1;
1648         rc = llapi_mv(argv[optind], &param);
1649         if (rc != 0)
1650                 fprintf(stderr, "cannot migrate '%s' to MDT%04x: %s\n",
1651                         argv[optind], param.mdtindex, strerror(-rc));
1652         return rc;
1653 }
1654
1655 static int lfs_osts(int argc, char **argv)
1656 {
1657         return lfs_tgts(argc, argv);
1658 }
1659
1660 static int lfs_mdts(int argc, char **argv)
1661 {
1662         return lfs_tgts(argc, argv);
1663 }
1664
1665 #define COOK(value)                                                     \
1666 ({                                                                      \
1667         int radix = 0;                                                  \
1668         while (value > 1024) {                                          \
1669                 value /= 1024;                                          \
1670                 radix++;                                                \
1671         }                                                               \
1672         radix;                                                          \
1673 })
1674 #define UUF     "%-20s"
1675 #define CSF     "%11s"
1676 #define CDF     "%11llu"
1677 #define HDF     "%8.1f%c"
1678 #define RSF     "%4s"
1679 #define RDF     "%3d%%"
1680
1681 static int showdf(char *mntdir, struct obd_statfs *stat,
1682                   char *uuid, int ishow, int cooked,
1683                   char *type, int index, int rc)
1684 {
1685         long long avail, used, total;
1686         double ratio = 0;
1687         char *suffix = "KMGTPEZY";
1688         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
1689         char tbuf[20], ubuf[20], abuf[20], rbuf[20];
1690
1691         if (!uuid || !stat)
1692                 return -EINVAL;
1693
1694         switch (rc) {
1695         case 0:
1696                 if (ishow) {
1697                         avail = stat->os_ffree;
1698                         used = stat->os_files - stat->os_ffree;
1699                         total = stat->os_files;
1700                 } else {
1701                         int shift = cooked ? 0 : 10;
1702
1703                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
1704                         used  = ((stat->os_blocks - stat->os_bfree) *
1705                                  stat->os_bsize) >> shift;
1706                         total = (stat->os_blocks * stat->os_bsize) >> shift;
1707                 }
1708
1709                 if ((used + avail) > 0)
1710                         ratio = (double)used / (double)(used + avail);
1711
1712                 if (cooked) {
1713                         int i;
1714                         double cook_val;
1715
1716                         cook_val = (double)total;
1717                         i = COOK(cook_val);
1718                         if (i > 0)
1719                                 sprintf(tbuf, HDF, cook_val, suffix[i - 1]);
1720                         else
1721                                 sprintf(tbuf, CDF, total);
1722
1723                         cook_val = (double)used;
1724                         i = COOK(cook_val);
1725                         if (i > 0)
1726                                 sprintf(ubuf, HDF, cook_val, suffix[i - 1]);
1727                         else
1728                                 sprintf(ubuf, CDF, used);
1729
1730                         cook_val = (double)avail;
1731                         i = COOK(cook_val);
1732                         if (i > 0)
1733                                 sprintf(abuf, HDF, cook_val, suffix[i - 1]);
1734                         else
1735                                 sprintf(abuf, CDF, avail);
1736                 } else {
1737                         sprintf(tbuf, CDF, total);
1738                         sprintf(ubuf, CDF, used);
1739                         sprintf(abuf, CDF, avail);
1740                 }
1741
1742                 sprintf(rbuf, RDF, (int)(ratio * 100 + 0.5));
1743                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
1744                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
1745                 if (type)
1746                         printf("[%s:%d]\n", type, index);
1747                 else
1748                         printf("\n");
1749
1750                 break;
1751         case -ENODATA:
1752                 printf(UUF": inactive device\n", uuid);
1753                 break;
1754         default:
1755                 printf(UUF": %s\n", uuid, strerror(-rc));
1756                 break;
1757         }
1758
1759         return 0;
1760 }
1761
1762 struct ll_stat_type {
1763         int   st_op;
1764         char *st_name;
1765 };
1766
1767 static int mntdf(char *mntdir, char *fsname, char *pool, int ishow,
1768                 int cooked, int lazy)
1769 {
1770         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
1771         struct obd_uuid uuid_buf;
1772         char *poolname = NULL;
1773         struct ll_stat_type types[] = { { LL_STATFS_LMV, "MDT" },
1774                                         { LL_STATFS_LOV, "OST" },
1775                                         { 0, NULL } };
1776         struct ll_stat_type *tp;
1777         __u64 ost_ffree = 0;
1778         __u32 index;
1779         __u32 type;
1780         int rc;
1781
1782         if (pool) {
1783                 poolname = strchr(pool, '.');
1784                 if (poolname != NULL) {
1785                         if (strncmp(fsname, pool, strlen(fsname))) {
1786                                 fprintf(stderr, "filesystem name incorrect\n");
1787                                 return -ENODEV;
1788                         }
1789                         poolname++;
1790                 } else
1791                         poolname = pool;
1792         }
1793
1794         if (ishow)
1795                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
1796                        "UUID", "Inodes", "IUsed", "IFree",
1797                        "IUse%", "Mounted on");
1798         else
1799                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
1800                        "UUID", cooked ? "bytes" : "1K-blocks",
1801                        "Used", "Available", "Use%", "Mounted on");
1802
1803         for (tp = types; tp->st_name != NULL; tp++) {
1804                 for (index = 0; ; index++) {
1805                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
1806                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
1807                         type = lazy ? tp->st_op | LL_STATFS_NODELAY : tp->st_op;
1808                         rc = llapi_obd_statfs(mntdir, type, index,
1809                                               &stat_buf, &uuid_buf);
1810                         if (rc == -ENODEV)
1811                                 break;
1812
1813                         if (poolname && tp->st_op == LL_STATFS_LOV &&
1814                             llapi_search_ost(fsname, poolname,
1815                                              obd_uuid2str(&uuid_buf)) != 1)
1816                                 continue;
1817
1818                         /* the llapi_obd_statfs() call may have returned with
1819                          * an error, but if it filled in uuid_buf we will at
1820                          * lease use that to print out a message for that OBD.
1821                          * If we didn't get anything in the uuid_buf, then fill
1822                          * it in so that we can print an error message. */
1823                         if (uuid_buf.uuid[0] == '\0')
1824                                 sprintf(uuid_buf.uuid, "%s%04x",
1825                                         tp->st_name, index);
1826                         showdf(mntdir, &stat_buf, obd_uuid2str(&uuid_buf),
1827                                ishow, cooked, tp->st_name, index, rc);
1828
1829                         if (rc == 0) {
1830                                 if (tp->st_op == LL_STATFS_LMV) {
1831                                         sum.os_ffree += stat_buf.os_ffree;
1832                                         sum.os_files += stat_buf.os_files;
1833                                 } else /* if (tp->st_op == LL_STATFS_LOV) */ {
1834                                         sum.os_blocks += stat_buf.os_blocks *
1835                                                 stat_buf.os_bsize;
1836                                         sum.os_bfree  += stat_buf.os_bfree *
1837                                                 stat_buf.os_bsize;
1838                                         sum.os_bavail += stat_buf.os_bavail *
1839                                                 stat_buf.os_bsize;
1840                                         ost_ffree += stat_buf.os_ffree;
1841                                 }
1842                         } else if (rc == -EINVAL || rc == -EFAULT) {
1843                                 break;
1844                         }
1845                 }
1846         }
1847
1848         /* If we don't have as many objects free on the OST as inodes
1849          * on the MDS, we reduce the total number of inodes to
1850          * compensate, so that the "inodes in use" number is correct.
1851          * Matches ll_statfs_internal() so the results are consistent. */
1852         if (ost_ffree < sum.os_ffree) {
1853                 sum.os_files = (sum.os_files - sum.os_ffree) + ost_ffree;
1854                 sum.os_ffree = ost_ffree;
1855         }
1856         printf("\n");
1857         showdf(mntdir, &sum, "filesystem summary:", ishow, cooked, NULL, 0, 0);
1858         printf("\n");
1859         return 0;
1860 }
1861
1862 static int lfs_df(int argc, char **argv)
1863 {
1864         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
1865         int ishow = 0, cooked = 0;
1866         int lazy = 0;
1867         int c, rc = 0, index = 0;
1868         char fsname[PATH_MAX] = "", *pool_name = NULL;
1869         struct option long_opts[] = {
1870                 {"pool", required_argument, 0, 'p'},
1871                 {"lazy", 0, 0, 'l'},
1872                 {0, 0, 0, 0}
1873         };
1874
1875         optind = 0;
1876         while ((c = getopt_long(argc, argv, "hilp:", long_opts, NULL)) != -1) {
1877                 switch (c) {
1878                 case 'i':
1879                         ishow = 1;
1880                         break;
1881                 case 'h':
1882                         cooked = 1;
1883                         break;
1884                 case 'l':
1885                         lazy = 1;
1886                         break;
1887                 case 'p':
1888                         pool_name = optarg;
1889                         break;
1890                 default:
1891                         return CMD_HELP;
1892                 }
1893         }
1894         if (optind < argc && !realpath(argv[optind], path)) {
1895                 rc = -errno;
1896                 fprintf(stderr, "error: invalid path '%s': %s\n",
1897                         argv[optind], strerror(-rc));
1898                 return rc;
1899         }
1900
1901         while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
1902                 /* Check if we have a mount point */
1903                 if (mntdir[0] == '\0')
1904                         continue;
1905
1906                 rc = mntdf(mntdir, fsname, pool_name, ishow, cooked, lazy);
1907                 if (rc || path[0] != '\0')
1908                         break;
1909                 fsname[0] = '\0'; /* avoid matching in next loop */
1910                 mntdir[0] = '\0'; /* avoid matching in next loop */
1911         }
1912
1913         return rc;
1914 }
1915
1916 static int lfs_getname(int argc, char **argv)
1917 {
1918         char mntdir[PATH_MAX] = "", path[PATH_MAX] = "", fsname[PATH_MAX] = "";
1919         int rc = 0, index = 0, c;
1920         char buf[sizeof(struct obd_uuid)];
1921
1922         optind = 0;
1923         while ((c = getopt(argc, argv, "h")) != -1)
1924                 return CMD_HELP;
1925
1926         if (optind == argc) { /* no paths specified, get all paths. */
1927                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
1928                         rc = llapi_getname(mntdir, buf, sizeof(buf));
1929                         if (rc < 0) {
1930                                 fprintf(stderr,
1931                                         "cannot get name for `%s': %s\n",
1932                                         mntdir, strerror(-rc));
1933                                 break;
1934                         }
1935
1936                         printf("%s %s\n", buf, mntdir);
1937
1938                         path[0] = fsname[0] = mntdir[0] = 0;
1939                 }
1940         } else { /* paths specified, only attempt to search these. */
1941                 for (; optind < argc; optind++) {
1942                         rc = llapi_getname(argv[optind], buf, sizeof(buf));
1943                         if (rc < 0) {
1944                                 fprintf(stderr,
1945                                         "cannot get name for `%s': %s\n",
1946                                         argv[optind], strerror(-rc));
1947                                 break;
1948                         }
1949
1950                         printf("%s %s\n", buf, argv[optind]);
1951                 }
1952         }
1953         return rc;
1954 }
1955
1956 static int lfs_check(int argc, char **argv)
1957 {
1958         int rc;
1959         char mntdir[PATH_MAX] = {'\0'};
1960         int num_types = 1;
1961         char *obd_types[2];
1962         char obd_type1[4];
1963         char obd_type2[4];
1964
1965         if (argc != 2)
1966                 return CMD_HELP;
1967
1968         obd_types[0] = obd_type1;
1969         obd_types[1] = obd_type2;
1970
1971         if (strcmp(argv[1], "osts") == 0) {
1972                 strcpy(obd_types[0], "osc");
1973         } else if (strcmp(argv[1], "mds") == 0) {
1974                 strcpy(obd_types[0], "mdc");
1975         } else if (strcmp(argv[1], "servers") == 0) {
1976                 num_types = 2;
1977                 strcpy(obd_types[0], "osc");
1978                 strcpy(obd_types[1], "mdc");
1979         } else {
1980                 fprintf(stderr, "error: %s: option '%s' unrecognized\n",
1981                                 argv[0], argv[1]);
1982                         return CMD_HELP;
1983         }
1984
1985         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
1986         if (rc < 0 || mntdir[0] == '\0') {
1987                 fprintf(stderr, "No suitable Lustre mount found\n");
1988                 return rc;
1989         }
1990
1991         rc = llapi_target_iterate(num_types, obd_types,
1992                                   mntdir, llapi_ping_target);
1993
1994         if (rc)
1995                 fprintf(stderr, "error: %s: %s status failed\n",
1996                                 argv[0],argv[1]);
1997
1998         return rc;
1999
2000 }
2001
2002 static int lfs_join(int argc, char **argv)
2003 {
2004         fprintf(stderr, "join two lustre files into one.\n"
2005                         "obsolete, HEAD does not support it anymore.\n");
2006         return 0;
2007 }
2008
2009 #ifdef HAVE_SYS_QUOTA_H
2010 static int lfs_quotacheck(int argc, char **argv)
2011 {
2012         int c, check_type = 0;
2013         char *mnt;
2014         struct if_quotacheck qchk;
2015         struct if_quotactl qctl;
2016         char *obd_type = (char *)qchk.obd_type;
2017         int rc;
2018
2019         memset(&qchk, 0, sizeof(qchk));
2020
2021         optind = 0;
2022         while ((c = getopt(argc, argv, "gu")) != -1) {
2023                 switch (c) {
2024                 case 'u':
2025                         check_type |= 0x01;
2026                         break;
2027                 case 'g':
2028                         check_type |= 0x02;
2029                         break;
2030                 default:
2031                         fprintf(stderr, "error: %s: option '-%c' "
2032                                         "unrecognized\n", argv[0], c);
2033                         return CMD_HELP;
2034                 }
2035         }
2036
2037         if (check_type)
2038                 check_type--;
2039         else    /* do quotacheck for both user & group quota by default */
2040                 check_type = 0x02;
2041
2042         if (argc == optind)
2043                 return CMD_HELP;
2044
2045         mnt = argv[optind];
2046
2047         rc = llapi_quotacheck(mnt, check_type);
2048         if (rc == -EOPNOTSUPP) {
2049                 fprintf(stderr, "error: quotacheck not supported by the quota "
2050                         "master.\nPlease note that quotacheck is deprecated as "
2051                         "of lustre 2.4.0 since space accounting is always "
2052                         "enabled.\nFilesystems not formatted with 2.4 utils or "
2053                         "beyond can be upgraded with tunefs.lustre --quota.\n");
2054                 return rc;
2055         } else if (rc) {
2056                 fprintf(stderr, "quotacheck failed: %s\n", strerror(-rc));
2057                 return rc;
2058         }
2059
2060         rc = llapi_poll_quotacheck(mnt, &qchk);
2061         if (rc) {
2062                 if (*obd_type)
2063                         fprintf(stderr, "%s %s ", obd_type,
2064                                 obd_uuid2str(&qchk.obd_uuid));
2065                 fprintf(stderr, "quota check failed: %s\n", strerror(-rc));
2066                 return rc;
2067         }
2068
2069         memset(&qctl, 0, sizeof(qctl));
2070         qctl.qc_cmd = LUSTRE_Q_QUOTAON;
2071         qctl.qc_type = check_type;
2072         rc = llapi_quotactl(mnt, &qctl);
2073         if (rc && rc != -EALREADY) {
2074                 if (*obd_type)
2075                         fprintf(stderr, "%s %s ", (char *)qctl.obd_type,
2076                                 obd_uuid2str(&qctl.obd_uuid));
2077                 fprintf(stderr, "%s turn on quota failed: %s\n",
2078                         argv[0], strerror(-rc));
2079                 return rc;
2080         }
2081
2082         return 0;
2083 }
2084
2085 static int lfs_quotaon(int argc, char **argv)
2086 {
2087         int c;
2088         char *mnt;
2089         struct if_quotactl qctl;
2090         char *obd_type = (char *)qctl.obd_type;
2091         int rc;
2092
2093         memset(&qctl, 0, sizeof(qctl));
2094         qctl.qc_cmd = LUSTRE_Q_QUOTAON;
2095
2096         optind = 0;
2097         while ((c = getopt(argc, argv, "fgu")) != -1) {
2098                 switch (c) {
2099                 case 'u':
2100                         qctl.qc_type |= 0x01;
2101                         break;
2102                 case 'g':
2103                         qctl.qc_type |= 0x02;
2104                         break;
2105                 case 'f':
2106                         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
2107                         break;
2108                 default:
2109                         fprintf(stderr, "error: %s: option '-%c' "
2110                                         "unrecognized\n", argv[0], c);
2111                         return CMD_HELP;
2112                 }
2113         }
2114
2115         if (qctl.qc_type)
2116                 qctl.qc_type--;
2117         else /* by default, enable quota for both user & group */
2118                 qctl.qc_type = 0x02;
2119
2120         if (argc == optind)
2121                 return CMD_HELP;
2122
2123         mnt = argv[optind];
2124
2125         rc = llapi_quotactl(mnt, &qctl);
2126         if (rc) {
2127                 if (rc == -EOPNOTSUPP) {
2128                         fprintf(stderr, "error: quotaon not supported by the "
2129                                 "quota master.\nPlease note that quotaon/off is"
2130                                 " deprecated as of lustre 2.4.0.\nQuota "
2131                                 "enforcement should now be enabled on the MGS "
2132                                 "via:\nmgs# lctl conf_param ${FSNAME}.quota."
2133                                 "<ost|mdt>=<u|g|ug>\n(ost for block quota, mdt "
2134                                 "for inode quota, u for user and g for group"
2135                                 "\n");
2136                 } else if (rc == -EALREADY) {
2137                         rc = 0;
2138                 } else if (rc == -ENOENT) {
2139                         fprintf(stderr, "error: cannot find quota database, "
2140                                         "make sure you have run quotacheck\n");
2141                 } else {
2142                         if (*obd_type)
2143                                 fprintf(stderr, "%s %s ", obd_type,
2144                                         obd_uuid2str(&qctl.obd_uuid));
2145                         fprintf(stderr, "%s failed: %s\n", argv[0],
2146                                 strerror(-rc));
2147                 }
2148         }
2149
2150         return rc;
2151 }
2152
2153 static int lfs_quotaoff(int argc, char **argv)
2154 {
2155         int c;
2156         char *mnt;
2157         struct if_quotactl qctl;
2158         char *obd_type = (char *)qctl.obd_type;
2159         int rc;
2160
2161         memset(&qctl, 0, sizeof(qctl));
2162         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
2163
2164         optind = 0;
2165         while ((c = getopt(argc, argv, "gu")) != -1) {
2166                 switch (c) {
2167                 case 'u':
2168                         qctl.qc_type |= 0x01;
2169                         break;
2170                 case 'g':
2171                         qctl.qc_type |= 0x02;
2172                         break;
2173                 default:
2174                         fprintf(stderr, "error: %s: option '-%c' "
2175                                         "unrecognized\n", argv[0], c);
2176                         return CMD_HELP;
2177                 }
2178         }
2179
2180         if (qctl.qc_type)
2181                 qctl.qc_type--;
2182         else /* by default, disable quota for both user & group */
2183                 qctl.qc_type = 0x02;
2184
2185         if (argc == optind)
2186                 return CMD_HELP;
2187
2188         mnt = argv[optind];
2189
2190         rc = llapi_quotactl(mnt, &qctl);
2191         if (rc) {
2192                 if (rc == -EOPNOTSUPP) {
2193                         fprintf(stderr, "error: quotaoff not supported by the "
2194                                 "quota master.\nPlease note that quotaon/off is"
2195                                 " deprecated as of lustre 2.4.0.\nQuota "
2196                                 "enforcement can be disabled on the MGS via:\n"
2197                                 "mgs# lctl conf_param ${FSNAME}.quota.<ost|mdt>"
2198                                 "=\"\"\n");
2199                 } else if (rc == -EALREADY) {
2200                         rc = 0;
2201                 } else {
2202                         if (*obd_type)
2203                                 fprintf(stderr, "%s %s ", obd_type,
2204                                         obd_uuid2str(&qctl.obd_uuid));
2205                         fprintf(stderr, "quotaoff failed: %s\n",
2206                                 strerror(-rc));
2207                 }
2208         }
2209
2210         return rc;
2211 }
2212
2213 #define ARG2INT(nr, str, msg)                                           \
2214 do {                                                                    \
2215         char *endp;                                                     \
2216         nr = strtol(str, &endp, 0);                                     \
2217         if (*endp) {                                                    \
2218                 fprintf(stderr, "error: bad %s: %s\n", msg, str);       \
2219                 return CMD_HELP;                                        \
2220         }                                                               \
2221 } while (0)
2222
2223 #define ADD_OVERFLOW(a,b) ((a + b) < a) ? (a = ULONG_MAX) : (a = a + b)
2224
2225 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
2226  * returns the value or ULONG_MAX on integer overflow or incorrect format
2227  * Notes:
2228  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
2229  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
2230  *        3. empty integer value is interpreted as 0
2231  */
2232 static unsigned long str2sec(const char* timestr)
2233 {
2234         const char spec[] = "smhdw";
2235         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
2236         unsigned long val = 0;
2237         char *tail;
2238
2239         if (strpbrk(timestr, spec) == NULL) {
2240                 /* no specifiers inside the time string,
2241                    should treat it as an integer value */
2242                 val = strtoul(timestr, &tail, 10);
2243                 return *tail ? ULONG_MAX : val;
2244         }
2245
2246         /* format string is XXwXXdXXhXXmXXs */
2247         while (*timestr) {
2248                 unsigned long v;
2249                 int ind;
2250                 char* ptr;
2251
2252                 v = strtoul(timestr, &tail, 10);
2253                 if (v == ULONG_MAX || *tail == '\0')
2254                         /* value too large (ULONG_MAX or more)
2255                            or missing specifier */
2256                         goto error;
2257
2258                 ptr = strchr(spec, *tail);
2259                 if (ptr == NULL)
2260                         /* unknown specifier */
2261                         goto error;
2262
2263                 ind = ptr - spec;
2264
2265                 /* check if product will overflow the type */
2266                 if (!(v < ULONG_MAX / mult[ind]))
2267                         goto error;
2268
2269                 ADD_OVERFLOW(val, mult[ind] * v);
2270                 if (val == ULONG_MAX)
2271                         goto error;
2272
2273                 timestr = tail + 1;
2274         }
2275
2276         return val;
2277
2278 error:
2279         return ULONG_MAX;
2280 }
2281
2282 #define ARG2ULL(nr, str, def_units)                                     \
2283 do {                                                                    \
2284         unsigned long long limit, units = def_units;                    \
2285         int rc;                                                         \
2286                                                                         \
2287         rc = llapi_parse_size(str, &limit, &units, 1);                  \
2288         if (rc < 0) {                                                   \
2289                 fprintf(stderr, "error: bad limit value %s\n", str);    \
2290                 return CMD_HELP;                                        \
2291         }                                                               \
2292         nr = limit;                                                     \
2293 } while (0)
2294
2295 static inline int has_times_option(int argc, char **argv)
2296 {
2297         int i;
2298
2299         for (i = 1; i < argc; i++)
2300                 if (!strcmp(argv[i], "-t"))
2301                         return 1;
2302
2303         return 0;
2304 }
2305
2306 int lfs_setquota_times(int argc, char **argv)
2307 {
2308         int c, rc;
2309         struct if_quotactl qctl;
2310         char *mnt, *obd_type = (char *)qctl.obd_type;
2311         struct obd_dqblk *dqb = &qctl.qc_dqblk;
2312         struct obd_dqinfo *dqi = &qctl.qc_dqinfo;
2313         struct option long_opts[] = {
2314                 {"block-grace",     required_argument, 0, 'b'},
2315                 {"group",           no_argument,       0, 'g'},
2316                 {"inode-grace",     required_argument, 0, 'i'},
2317                 {"times",           no_argument,       0, 't'},
2318                 {"user",            no_argument,       0, 'u'},
2319                 {0, 0, 0, 0}
2320         };
2321
2322         memset(&qctl, 0, sizeof(qctl));
2323         qctl.qc_cmd  = LUSTRE_Q_SETINFO;
2324         qctl.qc_type = UGQUOTA;
2325
2326         optind = 0;
2327         while ((c = getopt_long(argc, argv, "b:gi:tu", long_opts, NULL)) != -1) {
2328                 switch (c) {
2329                 case 'u':
2330                 case 'g':
2331                         if (qctl.qc_type != UGQUOTA) {
2332                                 fprintf(stderr, "error: -u and -g can't be used "
2333                                                 "more than once\n");
2334                                 return CMD_HELP;
2335                         }
2336                         qctl.qc_type = (c == 'u') ? USRQUOTA : GRPQUOTA;
2337                         break;
2338                 case 'b':
2339                         if ((dqi->dqi_bgrace = str2sec(optarg)) == ULONG_MAX) {
2340                                 fprintf(stderr, "error: bad block-grace: %s\n",
2341                                         optarg);
2342                                 return CMD_HELP;
2343                         }
2344                         dqb->dqb_valid |= QIF_BTIME;
2345                         break;
2346                 case 'i':
2347                         if ((dqi->dqi_igrace = str2sec(optarg)) == ULONG_MAX) {
2348                                 fprintf(stderr, "error: bad inode-grace: %s\n",
2349                                         optarg);
2350                                 return CMD_HELP;
2351                         }
2352                         dqb->dqb_valid |= QIF_ITIME;
2353                         break;
2354                 case 't': /* Yes, of course! */
2355                         break;
2356                 default: /* getopt prints error message for us when opterr != 0 */
2357                         return CMD_HELP;
2358                 }
2359         }
2360
2361         if (qctl.qc_type == UGQUOTA) {
2362                 fprintf(stderr, "error: neither -u nor -g specified\n");
2363                 return CMD_HELP;
2364         }
2365
2366         if (optind != argc - 1) {
2367                 fprintf(stderr, "error: unexpected parameters encountered\n");
2368                 return CMD_HELP;
2369         }
2370
2371         mnt = argv[optind];
2372         rc = llapi_quotactl(mnt, &qctl);
2373         if (rc) {
2374                 if (*obd_type)
2375                         fprintf(stderr, "%s %s ", obd_type,
2376                                 obd_uuid2str(&qctl.obd_uuid));
2377                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
2378                 return rc;
2379         }
2380
2381         return 0;
2382 }
2383
2384 #define BSLIMIT (1 << 0)
2385 #define BHLIMIT (1 << 1)
2386 #define ISLIMIT (1 << 2)
2387 #define IHLIMIT (1 << 3)
2388
2389 int lfs_setquota(int argc, char **argv)
2390 {
2391         int c, rc;
2392         struct if_quotactl qctl;
2393         char *mnt, *obd_type = (char *)qctl.obd_type;
2394         struct obd_dqblk *dqb = &qctl.qc_dqblk;
2395         struct option long_opts[] = {
2396                 {"block-softlimit", required_argument, 0, 'b'},
2397                 {"block-hardlimit", required_argument, 0, 'B'},
2398                 {"group",           required_argument, 0, 'g'},
2399                 {"inode-softlimit", required_argument, 0, 'i'},
2400                 {"inode-hardlimit", required_argument, 0, 'I'},
2401                 {"user",            required_argument, 0, 'u'},
2402                 {0, 0, 0, 0}
2403         };
2404         unsigned limit_mask = 0;
2405         char *endptr;
2406
2407         if (has_times_option(argc, argv))
2408                 return lfs_setquota_times(argc, argv);
2409
2410         memset(&qctl, 0, sizeof(qctl));
2411         qctl.qc_cmd  = LUSTRE_Q_SETQUOTA;
2412         qctl.qc_type = UGQUOTA; /* UGQUOTA makes no sense for setquota,
2413                                  * so it can be used as a marker that qc_type
2414                                  * isn't reinitialized from command line */
2415
2416         optind = 0;
2417         while ((c = getopt_long(argc, argv, "b:B:g:i:I:u:", long_opts, NULL)) != -1) {
2418                 switch (c) {
2419                 case 'u':
2420                 case 'g':
2421                         if (qctl.qc_type != UGQUOTA) {
2422                                 fprintf(stderr, "error: -u and -g can't be used"
2423                                                 " more than once\n");
2424                                 return CMD_HELP;
2425                         }
2426                         qctl.qc_type = (c == 'u') ? USRQUOTA : GRPQUOTA;
2427                         rc = name2id(&qctl.qc_id, optarg,
2428                                      (qctl.qc_type == USRQUOTA) ? USER : GROUP);
2429                         if (rc) {
2430                                 qctl.qc_id = strtoul(optarg, &endptr, 10);
2431                                 if (*endptr != '\0') {
2432                                         fprintf(stderr, "error: can't find id "
2433                                                 "for name %s\n", optarg);
2434                                         return CMD_HELP;
2435                                 }
2436                         }
2437                         break;
2438                 case 'b':
2439                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
2440                         dqb->dqb_bsoftlimit >>= 10;
2441                         limit_mask |= BSLIMIT;
2442                         if (dqb->dqb_bsoftlimit &&
2443                             dqb->dqb_bsoftlimit <= 1024) /* <= 1M? */
2444                                 fprintf(stderr, "warning: block softlimit is "
2445                                         "smaller than the miminal qunit size, "
2446                                         "please see the help of setquota or "
2447                                         "Lustre manual for details.\n");
2448                         break;
2449                 case 'B':
2450                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
2451                         dqb->dqb_bhardlimit >>= 10;
2452                         limit_mask |= BHLIMIT;
2453                         if (dqb->dqb_bhardlimit &&
2454                             dqb->dqb_bhardlimit <= 1024) /* <= 1M? */
2455                                 fprintf(stderr, "warning: block hardlimit is "
2456                                         "smaller than the miminal qunit size, "
2457                                         "please see the help of setquota or "
2458                                         "Lustre manual for details.\n");
2459                         break;
2460                 case 'i':
2461                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
2462                         limit_mask |= ISLIMIT;
2463                         if (dqb->dqb_isoftlimit &&
2464                             dqb->dqb_isoftlimit <= 1024) /* <= 1K inodes? */
2465                                 fprintf(stderr, "warning: inode softlimit is "
2466                                         "smaller than the miminal qunit size, "
2467                                         "please see the help of setquota or "
2468                                         "Lustre manual for details.\n");
2469                         break;
2470                 case 'I':
2471                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
2472                         limit_mask |= IHLIMIT;
2473                         if (dqb->dqb_ihardlimit &&
2474                             dqb->dqb_ihardlimit <= 1024) /* <= 1K inodes? */
2475                                 fprintf(stderr, "warning: inode hardlimit is "
2476                                         "smaller than the miminal qunit size, "
2477                                         "please see the help of setquota or "
2478                                         "Lustre manual for details.\n");
2479                         break;
2480                 default: /* getopt prints error message for us when opterr != 0 */
2481                         return CMD_HELP;
2482                 }
2483         }
2484
2485         if (qctl.qc_type == UGQUOTA) {
2486                 fprintf(stderr, "error: neither -u nor -g was specified\n");
2487                 return CMD_HELP;
2488         }
2489
2490         if (limit_mask == 0) {
2491                 fprintf(stderr, "error: at least one limit must be specified\n");
2492                 return CMD_HELP;
2493         }
2494
2495         if (optind != argc - 1) {
2496                 fprintf(stderr, "error: unexpected parameters encountered\n");
2497                 return CMD_HELP;
2498         }
2499
2500         mnt = argv[optind];
2501
2502         if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
2503             (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
2504                 /* sigh, we can't just set blimits/ilimits */
2505                 struct if_quotactl tmp_qctl = {.qc_cmd  = LUSTRE_Q_GETQUOTA,
2506                                                .qc_type = qctl.qc_type,
2507                                                .qc_id   = qctl.qc_id};
2508
2509                 rc = llapi_quotactl(mnt, &tmp_qctl);
2510                 if (rc < 0) {
2511                         fprintf(stderr, "error: setquota failed while retrieving"
2512                                         " current quota settings (%s)\n",
2513                                         strerror(-rc));
2514                         return rc;
2515                 }
2516
2517                 if (!(limit_mask & BHLIMIT))
2518                         dqb->dqb_bhardlimit = tmp_qctl.qc_dqblk.dqb_bhardlimit;
2519                 if (!(limit_mask & BSLIMIT))
2520                         dqb->dqb_bsoftlimit = tmp_qctl.qc_dqblk.dqb_bsoftlimit;
2521                 if (!(limit_mask & IHLIMIT))
2522                         dqb->dqb_ihardlimit = tmp_qctl.qc_dqblk.dqb_ihardlimit;
2523                 if (!(limit_mask & ISLIMIT))
2524                         dqb->dqb_isoftlimit = tmp_qctl.qc_dqblk.dqb_isoftlimit;
2525
2526                 /* Keep grace times if we have got no softlimit arguments */
2527                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
2528                         dqb->dqb_valid |= QIF_BTIME;
2529                         dqb->dqb_btime = tmp_qctl.qc_dqblk.dqb_btime;
2530                 }
2531
2532                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
2533                         dqb->dqb_valid |= QIF_ITIME;
2534                         dqb->dqb_itime = tmp_qctl.qc_dqblk.dqb_itime;
2535                 }
2536         }
2537
2538         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
2539         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
2540
2541         rc = llapi_quotactl(mnt, &qctl);
2542         if (rc) {
2543                 if (*obd_type)
2544                         fprintf(stderr, "%s %s ", obd_type,
2545                                 obd_uuid2str(&qctl.obd_uuid));
2546                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
2547                 return rc;
2548         }
2549
2550         return 0;
2551 }
2552
2553 static inline char *type2name(int check_type)
2554 {
2555         if (check_type == USRQUOTA)
2556                 return "user";
2557         else if (check_type == GRPQUOTA)
2558                 return "group";
2559         else
2560                 return "unknown";
2561 }
2562
2563 /* Converts seconds value into format string
2564  * result is returned in buf
2565  * Notes:
2566  *        1. result is in descenting order: 1w2d3h4m5s
2567  *        2. zero fields are not filled (except for p. 3): 5d1s
2568  *        3. zero seconds value is presented as "0s"
2569  */
2570 static char * __sec2str(time_t seconds, char *buf)
2571 {
2572         const char spec[] = "smhdw";
2573         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
2574         unsigned long c;
2575         char *tail = buf;
2576         int i;
2577
2578         for (i = sizeof(mult) / sizeof(mult[0]) - 1 ; i >= 0; i--) {
2579                 c = seconds / mult[i];
2580
2581                 if (c > 0 || (i == 0 && buf == tail))
2582                         tail += snprintf(tail, 40-(tail-buf), "%lu%c", c, spec[i]);
2583
2584                 seconds %= mult[i];
2585         }
2586
2587         return tail;
2588 }
2589
2590 static void sec2str(time_t seconds, char *buf, int rc)
2591 {
2592         char *tail = buf;
2593
2594         if (rc)
2595                 *tail++ = '[';
2596
2597         tail = __sec2str(seconds, tail);
2598
2599         if (rc && tail - buf < 39) {
2600                 *tail++ = ']';
2601                 *tail++ = 0;
2602         }
2603 }
2604
2605 static void diff2str(time_t seconds, char *buf, time_t now)
2606 {
2607
2608         buf[0] = 0;
2609         if (!seconds)
2610                 return;
2611         if (seconds <= now) {
2612                 strcpy(buf, "none");
2613                 return;
2614         }
2615         __sec2str(seconds - now, buf);
2616 }
2617
2618 static void print_quota_title(char *name, struct if_quotactl *qctl,
2619                               bool human_readable)
2620 {
2621         printf("Disk quotas for %s %s (%cid %u):\n",
2622                type2name(qctl->qc_type), name,
2623                *type2name(qctl->qc_type), qctl->qc_id);
2624         printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
2625                "Filesystem", human_readable ? "used" : "kbytes",
2626                "quota", "limit", "grace",
2627                "files", "quota", "limit", "grace");
2628 }
2629
2630 static void kbytes2str(__u64 num, char *buf, bool h)
2631 {
2632         if (!h) {
2633                 sprintf(buf, LPU64, num);
2634         } else {
2635                 if (num >> 30)
2636                         sprintf(buf, LPU64"%s", num >> 30, "T");
2637                 else if (num >> 20)
2638                         sprintf(buf, LPU64"%s", num >> 20, "G");
2639                 else if (num >> 10)
2640                         sprintf(buf, LPU64"%s", num >> 10, "M");
2641                 else
2642                         sprintf(buf, LPU64"%s", num, "K");
2643         }
2644 }
2645
2646 static void print_quota(char *mnt, struct if_quotactl *qctl, int type,
2647                         int rc, bool h)
2648 {
2649         time_t now;
2650
2651         time(&now);
2652
2653         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA) {
2654                 int bover = 0, iover = 0;
2655                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
2656                 char numbuf[3][32];
2657                 char timebuf[40];
2658                 char strbuf[32];
2659
2660                 if (dqb->dqb_bhardlimit &&
2661                     toqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
2662                         bover = 1;
2663                 } else if (dqb->dqb_bsoftlimit && dqb->dqb_btime) {
2664                         if (dqb->dqb_btime > now) {
2665                                 bover = 2;
2666                         } else {
2667                                 bover = 3;
2668                         }
2669                 }
2670
2671                 if (dqb->dqb_ihardlimit &&
2672                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
2673                         iover = 1;
2674                 } else if (dqb->dqb_isoftlimit && dqb->dqb_itime) {
2675                         if (dqb->dqb_itime > now) {
2676                                 iover = 2;
2677                         } else {
2678                                 iover = 3;
2679                         }
2680                 }
2681
2682
2683                 if (strlen(mnt) > 15)
2684                         printf("%s\n%15s", mnt, "");
2685                 else
2686                         printf("%15s", mnt);
2687
2688                 if (bover)
2689                         diff2str(dqb->dqb_btime, timebuf, now);
2690
2691                 kbytes2str(toqb(dqb->dqb_curspace), strbuf, h);
2692                 if (rc == -EREMOTEIO)
2693                         sprintf(numbuf[0], "%s*", strbuf);
2694                 else
2695                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
2696                                 "%s" : "[%s]", strbuf);
2697
2698                 kbytes2str(dqb->dqb_bsoftlimit, strbuf, h);
2699                 if (type == QC_GENERAL)
2700                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS) ?
2701                                 "%s" : "[%s]", strbuf);
2702                 else
2703                         sprintf(numbuf[1], "%s", "-");
2704
2705                 kbytes2str(dqb->dqb_bhardlimit, strbuf, h);
2706                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS) ?
2707                         "%s" : "[%s]", strbuf);
2708
2709                 printf(" %7s%c %6s %7s %7s",
2710                        numbuf[0], bover ? '*' : ' ', numbuf[1],
2711                        numbuf[2], bover > 1 ? timebuf : "-");
2712
2713                 if (iover)
2714                         diff2str(dqb->dqb_itime, timebuf, now);
2715
2716                 sprintf(numbuf[0], (dqb->dqb_valid & QIF_INODES) ?
2717                         LPU64 : "["LPU64"]", dqb->dqb_curinodes);
2718
2719                 if (type == QC_GENERAL)
2720                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS) ?
2721                                 LPU64 : "["LPU64"]", dqb->dqb_isoftlimit);
2722                 else
2723                         sprintf(numbuf[1], "%s", "-");
2724
2725                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
2726                         LPU64 : "["LPU64"]", dqb->dqb_ihardlimit);
2727
2728                 if (type != QC_OSTIDX)
2729                         printf(" %7s%c %6s %7s %7s",
2730                                numbuf[0], iover ? '*' : ' ', numbuf[1],
2731                                numbuf[2], iover > 1 ? timebuf : "-");
2732                 else
2733                         printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
2734                 printf("\n");
2735
2736         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO ||
2737                    qctl->qc_cmd == Q_GETOINFO) {
2738                 char bgtimebuf[40];
2739                 char igtimebuf[40];
2740
2741                 sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
2742                 sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
2743                 printf("Block grace time: %s; Inode grace time: %s\n",
2744                        bgtimebuf, igtimebuf);
2745         }
2746 }
2747
2748 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt,
2749                            bool h, __u64 *total)
2750 {
2751         int rc = 0, rc1 = 0, count = 0;
2752         __u32 valid = qctl->qc_valid;
2753
2754         rc = llapi_get_obd_count(mnt, &count, is_mdt);
2755         if (rc) {
2756                 fprintf(stderr, "can not get %s count: %s\n",
2757                         is_mdt ? "mdt": "ost", strerror(-rc));
2758                 return rc;
2759         }
2760
2761         for (qctl->qc_idx = 0; qctl->qc_idx < count; qctl->qc_idx++) {
2762                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
2763                 rc = llapi_quotactl(mnt, qctl);
2764                 if (rc) {
2765                         /* It is remote client case. */
2766                         if (-rc == EOPNOTSUPP) {
2767                                 rc = 0;
2768                                 goto out;
2769                         }
2770
2771                         if (!rc1)
2772                                 rc1 = rc;
2773                         fprintf(stderr, "quotactl %s%d failed.\n",
2774                                 is_mdt ? "mdt": "ost", qctl->qc_idx);
2775                         continue;
2776                 }
2777
2778                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl,
2779                             qctl->qc_valid, 0, h);
2780                 *total += is_mdt ? qctl->qc_dqblk.dqb_ihardlimit :
2781                                    qctl->qc_dqblk.dqb_bhardlimit;
2782         }
2783 out:
2784         qctl->qc_valid = valid;
2785         return rc ? : rc1;
2786 }
2787
2788 static int lfs_quota(int argc, char **argv)
2789 {
2790         int c;
2791         char *mnt, *name = NULL;
2792         struct if_quotactl qctl = { .qc_cmd = LUSTRE_Q_GETQUOTA,
2793                                     .qc_type = UGQUOTA };
2794         char *obd_type = (char *)qctl.obd_type;
2795         char *obd_uuid = (char *)qctl.obd_uuid.uuid;
2796         int rc, rc1 = 0, rc2 = 0, rc3 = 0,
2797             verbose = 0, pass = 0, quiet = 0, inacc;
2798         char *endptr;
2799         __u32 valid = QC_GENERAL, idx = 0;
2800         __u64 total_ialloc = 0, total_balloc = 0;
2801         bool human_readable = false;
2802
2803         optind = 0;
2804         while ((c = getopt(argc, argv, "gi:I:o:qtuvh")) != -1) {
2805                 switch (c) {
2806                 case 'u':
2807                         if (qctl.qc_type != UGQUOTA) {
2808                                 fprintf(stderr, "error: use either -u or -g\n");
2809                                 return CMD_HELP;
2810                         }
2811                         qctl.qc_type = USRQUOTA;
2812                         break;
2813                 case 'g':
2814                         if (qctl.qc_type != UGQUOTA) {
2815                                 fprintf(stderr, "error: use either -u or -g\n");
2816                                 return CMD_HELP;
2817                         }
2818                         qctl.qc_type = GRPQUOTA;
2819                         break;
2820                 case 't':
2821                         qctl.qc_cmd = LUSTRE_Q_GETINFO;
2822                         break;
2823                 case 'o':
2824                         valid = qctl.qc_valid = QC_UUID;
2825                         strncpy(obd_uuid, optarg, sizeof(qctl.obd_uuid));
2826                         break;
2827                 case 'i':
2828                         valid = qctl.qc_valid = QC_MDTIDX;
2829                         idx = qctl.qc_idx = atoi(optarg);
2830                         break;
2831                 case 'I':
2832                         valid = qctl.qc_valid = QC_OSTIDX;
2833                         idx = qctl.qc_idx = atoi(optarg);
2834                         break;
2835                 case 'v':
2836                         verbose = 1;
2837                         break;
2838                 case 'q':
2839                         quiet = 1;
2840                         break;
2841                 case 'h':
2842                         human_readable = true;
2843                         break;
2844                 default:
2845                         fprintf(stderr, "error: %s: option '-%c' "
2846                                         "unrecognized\n", argv[0], c);
2847                         return CMD_HELP;
2848                 }
2849         }
2850
2851         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
2852         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA && qctl.qc_type == UGQUOTA &&
2853             optind == argc - 1) {
2854 ug_output:
2855                 memset(&qctl, 0, sizeof(qctl)); /* spoiled by print_*_quota */
2856                 qctl.qc_cmd = LUSTRE_Q_GETQUOTA;
2857                 qctl.qc_valid = valid;
2858                 qctl.qc_idx = idx;
2859                 if (pass++ == 0) {
2860                         qctl.qc_type = USRQUOTA;
2861                         qctl.qc_id = geteuid();
2862                 } else {
2863                         qctl.qc_type = GRPQUOTA;
2864                         qctl.qc_id = getegid();
2865                 }
2866                 rc = id2name(&name, qctl.qc_id,
2867                              (qctl.qc_type == USRQUOTA) ? USER : GROUP);
2868                 if (rc)
2869                         name = "<unknown>";
2870         /* lfs quota -u username /path/to/lustre/mount */
2871         } else if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) {
2872                 /* options should be followed by u/g-name and mntpoint */
2873                 if (optind + 2 != argc || qctl.qc_type == UGQUOTA) {
2874                         fprintf(stderr, "error: missing quota argument(s)\n");
2875                         return CMD_HELP;
2876                 }
2877
2878                 name = argv[optind++];
2879                 rc = name2id(&qctl.qc_id, name,
2880                              (qctl.qc_type == USRQUOTA) ? USER : GROUP);
2881                 if (rc) {
2882                         qctl.qc_id = strtoul(name, &endptr, 10);
2883                         if (*endptr != '\0') {
2884                                 fprintf(stderr, "error: can't find id for name "
2885                                         "%s\n", name);
2886                                 return CMD_HELP;
2887                         }
2888                 }
2889         } else if (optind + 1 != argc || qctl.qc_type == UGQUOTA) {
2890                 fprintf(stderr, "error: missing quota info argument(s)\n");
2891                 return CMD_HELP;
2892         }
2893
2894         mnt = argv[optind];
2895
2896         rc1 = llapi_quotactl(mnt, &qctl);
2897         if (rc1 < 0) {
2898                 switch (rc1) {
2899                 case -ESRCH:
2900                         fprintf(stderr, "%s quotas are not enabled.\n",
2901                                 qctl.qc_type == USRQUOTA ? "user" : "group");
2902                         goto out;
2903                 case -EPERM:
2904                         fprintf(stderr, "Permission denied.\n");
2905                 case -ENOENT:
2906                         /* We already got a "No such file..." message. */
2907                         goto out;
2908                 default:
2909                         fprintf(stderr, "Unexpected quotactl error: %s\n",
2910                                 strerror(-rc1));
2911                 }
2912         }
2913
2914         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA && !quiet)
2915                 print_quota_title(name, &qctl, human_readable);
2916
2917         if (rc1 && *obd_type)
2918                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
2919
2920         if (qctl.qc_valid != QC_GENERAL)
2921                 mnt = "";
2922
2923         inacc = (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) &&
2924                 ((qctl.qc_dqblk.dqb_valid & (QIF_LIMITS|QIF_USAGE)) !=
2925                  (QIF_LIMITS|QIF_USAGE));
2926
2927         print_quota(mnt, &qctl, QC_GENERAL, rc1, human_readable);
2928
2929         if (qctl.qc_valid == QC_GENERAL && qctl.qc_cmd != LUSTRE_Q_GETINFO &&
2930             verbose) {
2931                 char strbuf[32];
2932
2933                 kbytes2str(total_balloc, strbuf, human_readable);
2934                 rc2 = print_obd_quota(mnt, &qctl, 1, human_readable,
2935                                       &total_ialloc);
2936                 rc3 = print_obd_quota(mnt, &qctl, 0, human_readable,
2937                                       &total_balloc);
2938                 printf("Total allocated inode limit: "LPU64", total "
2939                        "allocated block limit: %s\n", total_ialloc, strbuf);
2940         }
2941
2942         if (rc1 || rc2 || rc3 || inacc)
2943                 printf("Some errors happened when getting quota info. "
2944                        "Some devices may be not working or deactivated. "
2945                        "The data in \"[]\" is inaccurate.\n");
2946
2947 out:
2948         if (pass == 1)
2949                 goto ug_output;
2950
2951         return rc1;
2952 }
2953 #endif /* HAVE_SYS_QUOTA_H! */
2954
2955 static int flushctx_ioctl(char *mp)
2956 {
2957         int fd, rc;
2958
2959         fd = open(mp, O_RDONLY);
2960         if (fd == -1) {
2961                 fprintf(stderr, "flushctx: error open %s: %s\n",
2962                         mp, strerror(errno));
2963                 return -1;
2964         }
2965
2966         rc = ioctl(fd, LL_IOC_FLUSHCTX);
2967         if (rc == -1)
2968                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
2969                         mp, strerror(errno));
2970
2971         close(fd);
2972         return rc;
2973 }
2974
2975 static int lfs_flushctx(int argc, char **argv)
2976 {
2977         int     kdestroy = 0, c;
2978         FILE   *proc = NULL;
2979         char    procline[PATH_MAX], *line;
2980         int     rc = 0;
2981
2982         optind = 0;
2983         while ((c = getopt(argc, argv, "k")) != -1) {
2984                 switch (c) {
2985                 case 'k':
2986                         kdestroy = 1;
2987                         break;
2988                 default:
2989                         fprintf(stderr, "error: %s: option '-%c' "
2990                                         "unrecognized\n", argv[0], c);
2991                         return CMD_HELP;
2992                 }
2993         }
2994
2995         if (kdestroy) {
2996             int rc;
2997             if ((rc = system("kdestroy > /dev/null")) != 0) {
2998                 rc = WEXITSTATUS(rc);
2999                 fprintf(stderr, "error destroying tickets: %d, continuing\n", rc);
3000             }
3001         }
3002
3003         if (optind >= argc) {
3004                 /* flush for all mounted lustre fs. */
3005                 proc = fopen("/proc/mounts", "r");
3006                 if (!proc) {
3007                         fprintf(stderr, "error: %s: can't open /proc/mounts\n",
3008                                 argv[0]);
3009                         return -1;
3010                 }
3011
3012                 while ((line = fgets(procline, PATH_MAX, proc)) != NULL) {
3013                         char dev[PATH_MAX];
3014                         char mp[PATH_MAX];
3015                         char fs[PATH_MAX];
3016
3017                         if (sscanf(line, "%s %s %s", dev, mp, fs) != 3) {
3018                                 fprintf(stderr, "%s: unexpected format in "
3019                                                 "/proc/mounts\n",
3020                                         argv[0]);
3021                                 rc = -1;
3022                                 goto out;
3023                         }
3024
3025                         if (strcmp(fs, "lustre") != 0)
3026                                 continue;
3027                         /* we use '@' to determine it's a client. are there
3028                          * any other better way?
3029                          */
3030                         if (strchr(dev, '@') == NULL)
3031                                 continue;
3032
3033                         if (flushctx_ioctl(mp))
3034                                 rc = -1;
3035                 }
3036         } else {
3037                 /* flush fs as specified */
3038                 while (optind < argc) {
3039                         if (flushctx_ioctl(argv[optind++]))
3040                                 rc = -1;
3041                 }
3042         }
3043
3044 out:
3045         if (proc != NULL)
3046                 fclose(proc);
3047         return rc;
3048 }
3049
3050 static int lfs_lsetfacl(int argc, char **argv)
3051 {
3052         argv[0]++;
3053         return(llapi_lsetfacl(argc, argv));
3054 }
3055
3056 static int lfs_lgetfacl(int argc, char **argv)
3057 {
3058         argv[0]++;
3059         return(llapi_lgetfacl(argc, argv));
3060 }
3061
3062 static int lfs_rsetfacl(int argc, char **argv)
3063 {
3064         argv[0]++;
3065         return(llapi_rsetfacl(argc, argv));
3066 }
3067
3068 static int lfs_rgetfacl(int argc, char **argv)
3069 {
3070         argv[0]++;
3071         return(llapi_rgetfacl(argc, argv));
3072 }
3073
3074 static int lfs_cp(int argc, char **argv)
3075 {
3076         return(llapi_cp(argc, argv));
3077 }
3078
3079 static int lfs_ls(int argc, char **argv)
3080 {
3081         return(llapi_ls(argc, argv));
3082 }
3083
3084 static int lfs_changelog(int argc, char **argv)
3085 {
3086         void *changelog_priv;
3087         struct changelog_ext_rec *rec;
3088         long long startrec = 0, endrec = 0;
3089         char *mdd;
3090         struct option long_opts[] = {
3091                 {"follow", no_argument, 0, 'f'},
3092                 {0, 0, 0, 0}
3093         };
3094         char short_opts[] = "f";
3095         int rc, follow = 0;
3096
3097         optind = 0;
3098         while ((rc = getopt_long(argc, argv, short_opts,
3099                                 long_opts, NULL)) != -1) {
3100                 switch (rc) {
3101                 case 'f':
3102                         follow++;
3103                         break;
3104                 case '?':
3105                         return CMD_HELP;
3106                 default:
3107                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
3108                                 argv[0], argv[optind - 1]);
3109                         return CMD_HELP;
3110                 }
3111         }
3112         if (optind >= argc)
3113                 return CMD_HELP;
3114
3115         mdd = argv[optind++];
3116         if (argc > optind)
3117                 startrec = strtoll(argv[optind++], NULL, 10);
3118         if (argc > optind)
3119                 endrec = strtoll(argv[optind++], NULL, 10);
3120
3121         rc = llapi_changelog_start(&changelog_priv,
3122                                    CHANGELOG_FLAG_BLOCK |
3123                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
3124                                    mdd, startrec);
3125         if (rc < 0) {
3126                 fprintf(stderr, "Can't start changelog: %s\n",
3127                         strerror(errno = -rc));
3128                 return rc;
3129         }
3130
3131         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
3132                 time_t secs;
3133                 struct tm ts;
3134
3135                 if (endrec && rec->cr_index > endrec) {
3136                         llapi_changelog_free(&rec);
3137                         break;
3138                 }
3139                 if (rec->cr_index < startrec) {
3140                         llapi_changelog_free(&rec);
3141                         continue;
3142                 }
3143
3144                 secs = rec->cr_time >> 30;
3145                 gmtime_r(&secs, &ts);
3146                 printf(LPU64" %02d%-5s %02d:%02d:%02d.%06d %04d.%02d.%02d "
3147                        "0x%x t="DFID, rec->cr_index, rec->cr_type,
3148                        changelog_type2str(rec->cr_type),
3149                        ts.tm_hour, ts.tm_min, ts.tm_sec,
3150                        (int)(rec->cr_time & ((1<<30) - 1)),
3151                        ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday,
3152                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
3153                 if (rec->cr_namelen)
3154                         /* namespace rec includes parent and filename */
3155                         printf(" p="DFID" %.*s", PFID(&rec->cr_pfid),
3156                                 rec->cr_namelen, rec->cr_name);
3157                 if (fid_is_sane(&rec->cr_sfid))
3158                         printf(" s="DFID" sp="DFID" %.*s",
3159                                 PFID(&rec->cr_sfid), PFID(&rec->cr_spfid),
3160                                 changelog_rec_snamelen(rec),
3161                                 changelog_rec_sname(rec));
3162                 printf("\n");
3163
3164                 llapi_changelog_free(&rec);
3165         }
3166
3167         llapi_changelog_fini(&changelog_priv);
3168
3169         if (rc < 0)
3170                 fprintf(stderr, "Changelog: %s\n", strerror(errno = -rc));
3171
3172         return (rc == 1 ? 0 : rc);
3173 }
3174
3175 static int lfs_changelog_clear(int argc, char **argv)
3176 {
3177         long long endrec;
3178         int rc;
3179
3180         if (argc != 4)
3181                 return CMD_HELP;
3182
3183         endrec = strtoll(argv[3], NULL, 10);
3184
3185         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
3186         if (rc)
3187                 fprintf(stderr, "%s error: %s\n", argv[0],
3188                         strerror(errno = -rc));
3189         return rc;
3190 }
3191
3192 static int lfs_fid2path(int argc, char **argv)
3193 {
3194         struct option long_opts[] = {
3195                 {"cur", no_argument, 0, 'c'},
3196                 {"link", required_argument, 0, 'l'},
3197                 {"rec", required_argument, 0, 'r'},
3198                 {0, 0, 0, 0}
3199         };
3200         char  short_opts[] = "cl:r:";
3201         char *device, *fid, *path;
3202         long long recno = -1;
3203         int linkno = -1;
3204         int lnktmp;
3205         int printcur = 0;
3206         int rc = 0;
3207
3208         optind = 0;
3209
3210         while ((rc = getopt_long(argc, argv, short_opts,
3211                                 long_opts, NULL)) != -1) {
3212                 switch (rc) {
3213                 case 'c':
3214                         printcur++;
3215                         break;
3216                 case 'l':
3217                         linkno = strtol(optarg, NULL, 10);
3218                         break;
3219                 case 'r':
3220                         recno = strtoll(optarg, NULL, 10);
3221                         break;
3222                 case '?':
3223                         return CMD_HELP;
3224                 default:
3225                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
3226                                 argv[0], argv[optind - 1]);
3227                         return CMD_HELP;
3228                 }
3229         }
3230
3231         if (argc < 3)
3232                 return CMD_HELP;
3233
3234         device = argv[optind++];
3235         path = calloc(1, PATH_MAX);
3236
3237         rc = 0;
3238         while (optind < argc) {
3239                 fid = argv[optind++];
3240
3241                 lnktmp = (linkno >= 0) ? linkno : 0;
3242                 while (1) {
3243                         int oldtmp = lnktmp;
3244                         long long rectmp = recno;
3245                         int rc2;
3246                         rc2 = llapi_fid2path(device, fid, path, PATH_MAX,
3247                                              &rectmp, &lnktmp);
3248                         if (rc2 < 0) {
3249                                 fprintf(stderr, "%s: error on FID %s: %s\n",
3250                                         argv[0], fid, strerror(errno = -rc2));
3251                                 if (rc == 0)
3252                                         rc = rc2;
3253                                 break;
3254                         }
3255
3256                         if (printcur)
3257                                 fprintf(stdout, "%lld ", rectmp);
3258                         if (device[0] == '/') {
3259                                 fprintf(stdout, "%s", device);
3260                                 if (device[strlen(device) - 1] != '/')
3261                                         fprintf(stdout, "/");
3262                         } else if (path[0] == '\0') {
3263                                 fprintf(stdout, "/");
3264                         }
3265                         fprintf(stdout, "%s\n", path);
3266
3267                         if (linkno >= 0)
3268                                 /* specified linkno */
3269                                 break;
3270                         if (oldtmp == lnktmp)
3271                                 /* no more links */
3272                                 break;
3273                 }
3274         }
3275
3276         free(path);
3277         return rc;
3278 }
3279
3280 static int lfs_path2fid(int argc, char **argv)
3281 {
3282         char **path;
3283         const char *sep = "";
3284         lustre_fid fid;
3285         int rc = 0;
3286
3287         if (argc < 2)
3288                 return CMD_HELP;
3289         else if (argc > 2)
3290                 sep = ": ";
3291
3292         path = argv + 1;
3293         while (*path != NULL) {
3294                 int err = llapi_path2fid(*path, &fid);
3295
3296                 if (err) {
3297                         fprintf(stderr, "%s: can't get fid for %s: %s\n",
3298                                 argv[0], *path, strerror(-err));
3299                         if (rc == 0) {
3300                                 rc = err;
3301                                 errno = -err;
3302                         }
3303                         goto out;
3304                 }
3305                 printf("%s%s"DFID"\n", *sep != '\0' ? *path : "", sep,
3306                        PFID(&fid));
3307 out:
3308                 path++;
3309         }
3310
3311         return rc;
3312 }
3313
3314 static int lfs_data_version(int argc, char **argv)
3315 {
3316         char *path;
3317         __u64 data_version;
3318         int fd;
3319         int rc;
3320         int c;
3321         int data_version_flags = LL_DV_RD_FLUSH; /* Read by default */
3322
3323         if (argc < 2)
3324                 return CMD_HELP;
3325
3326         optind = 0;
3327         while ((c = getopt(argc, argv, "nrw")) != -1) {
3328                 switch (c) {
3329                 case 'n':
3330                         data_version_flags = 0;
3331                         break;
3332                 case 'r':
3333                         data_version_flags |= LL_DV_RD_FLUSH;
3334                         break;
3335                 case 'w':
3336                         data_version_flags |= LL_DV_WR_FLUSH;
3337                         break;
3338                 default:
3339                         return CMD_HELP;
3340                 }
3341         }
3342         if (optind == argc)
3343                 return CMD_HELP;
3344
3345         path = argv[optind];
3346         fd = open(path, O_RDONLY);
3347         if (fd < 0)
3348                 err(errno, "cannot open file %s", path);
3349
3350         rc = llapi_get_data_version(fd, &data_version, data_version_flags);
3351         if (rc < 0)
3352                 err(errno, "cannot get version for %s", path);
3353         else
3354                 printf(LPU64 "\n", data_version);
3355
3356         close(fd);
3357         return rc;
3358 }
3359
3360 static int lfs_hsm_state(int argc, char **argv)
3361 {
3362         int rc;
3363         int i = 1;
3364         char *path;
3365         struct hsm_user_state hus;
3366
3367         if (argc < 2)
3368                 return CMD_HELP;
3369
3370         do {
3371                 path = argv[i];
3372
3373                 rc = llapi_hsm_state_get(path, &hus);
3374                 if (rc) {
3375                         fprintf(stderr, "can't get hsm state for %s: %s\n",
3376                                 path, strerror(errno = -rc));
3377                         return rc;
3378                 }
3379
3380                 /* Display path name and status flags */
3381                 printf("%s: (0x%08x)", path, hus.hus_states);
3382
3383                 if (hus.hus_states & HS_RELEASED)
3384                         printf(" released");
3385                 if (hus.hus_states & HS_EXISTS)
3386                         printf(" exists");
3387                 if (hus.hus_states & HS_DIRTY)
3388                         printf(" dirty");
3389                 if (hus.hus_states & HS_ARCHIVED)
3390                         printf(" archived");
3391                 /* Display user-settable flags */
3392                 if (hus.hus_states & HS_NORELEASE)
3393                         printf(" never_release");
3394                 if (hus.hus_states & HS_NOARCHIVE)
3395                         printf(" never_archive");
3396                 if (hus.hus_states & HS_LOST)
3397                         printf(" lost_from_hsm");
3398
3399                 if (hus.hus_archive_id != 0)
3400                         printf(", archive_id:%d", hus.hus_archive_id);
3401                 printf("\n");
3402
3403         } while (++i < argc);
3404
3405         return 0;
3406 }
3407
3408 #define LFS_HSM_SET   0
3409 #define LFS_HSM_CLEAR 1
3410
3411 /**
3412  * Generic function to set or clear HSM flags.
3413  * Used by hsm_set and hsm_clear.
3414  *
3415  * @mode  if LFS_HSM_SET, set the flags, if LFS_HSM_CLEAR, clear the flags.
3416  */
3417 static int lfs_hsm_change_flags(int argc, char **argv, int mode)
3418 {
3419         struct option long_opts[] = {
3420                 {"lost", 0, 0, 'l'},
3421                 {"norelease", 0, 0, 'r'},
3422                 {"noarchive", 0, 0, 'a'},
3423                 {"archived", 0, 0, 'A'},
3424                 {"dirty", 0, 0, 'd'},
3425                 {"exists", 0, 0, 'e'},
3426                 {0, 0, 0, 0}
3427         };
3428         char short_opts[] = "lraAde";
3429         __u64 mask = 0;
3430         int c, rc;
3431         char *path;
3432
3433         if (argc < 3)
3434                 return CMD_HELP;
3435
3436         optind = 0;
3437         while ((c = getopt_long(argc, argv, short_opts,
3438                                 long_opts, NULL)) != -1) {
3439                 switch (c) {
3440                 case 'l':
3441                         mask |= HS_LOST;
3442                         break;
3443                 case 'a':
3444                         mask |= HS_NOARCHIVE;
3445                         break;
3446                 case 'A':
3447                         mask |= HS_ARCHIVED;
3448                         break;
3449                 case 'r':
3450                         mask |= HS_NORELEASE;
3451                         break;
3452                 case 'd':
3453                         mask |= HS_DIRTY;
3454                         break;
3455                 case 'e':
3456                         mask |= HS_EXISTS;
3457                         break;
3458                 case '?':
3459                         return CMD_HELP;
3460                 default:
3461                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
3462                                 argv[0], argv[optind - 1]);
3463                         return CMD_HELP;
3464                 }
3465         }
3466
3467         /* User should have specified a flag */
3468         if (mask == 0)
3469                 return CMD_HELP;
3470
3471         while (optind < argc) {
3472
3473                 path = argv[optind];
3474
3475                 /* If mode == 0, this means we apply the mask. */
3476                 if (mode == LFS_HSM_SET)
3477                         rc = llapi_hsm_state_set(path, mask, 0, 0);
3478                 else
3479                         rc = llapi_hsm_state_set(path, 0, mask, 0);
3480
3481                 if (rc != 0) {
3482                         fprintf(stderr, "Can't change hsm flags for %s: %s\n",
3483                                 path, strerror(errno = -rc));
3484                         return rc;
3485                 }
3486                 optind++;
3487         }
3488
3489         return 0;
3490 }
3491
3492 static int lfs_hsm_action(int argc, char **argv)
3493 {
3494         int                              rc;
3495         int                              i = 1;
3496         char                            *path;
3497         struct hsm_current_action        hca;
3498         struct hsm_extent                he;
3499         enum hsm_user_action             hua;
3500         enum hsm_progress_states         hps;
3501
3502         if (argc < 2)
3503                 return CMD_HELP;
3504
3505         do {
3506                 path = argv[i];
3507
3508                 rc = llapi_hsm_current_action(path, &hca);
3509                 if (rc) {
3510                         fprintf(stderr, "can't get hsm action for %s: %s\n",
3511                                 path, strerror(errno = -rc));
3512                         return rc;
3513                 }
3514                 he = hca.hca_location;
3515                 hua = hca.hca_action;
3516                 hps = hca.hca_state;
3517
3518                 printf("%s: %s", path, hsm_user_action2name(hua));
3519
3520                 /* Skip file without action */
3521                 if (hca.hca_action == HUA_NONE) {
3522                         printf("\n");
3523                         continue;
3524                 }
3525
3526                 printf(" %s ", hsm_progress_state2name(hps));
3527
3528                 if ((hps == HPS_RUNNING) &&
3529                     (hua == HUA_ARCHIVE || hua == HUA_RESTORE))
3530                         printf("("LPX64 " bytes moved)\n", he.length);
3531                 else if ((he.offset + he.length) == OBD_OBJECT_EOF)
3532                         printf("(from "LPX64 " to EOF)\n", he.offset);
3533                 else
3534                         printf("(from "LPX64 " to "LPX64")\n",
3535                                he.offset, he.offset + he.length);
3536
3537         } while (++i < argc);
3538
3539         return 0;
3540 }
3541
3542 static int lfs_hsm_set(int argc, char **argv)
3543 {
3544         return lfs_hsm_change_flags(argc, argv, LFS_HSM_SET);
3545 }
3546
3547 static int lfs_hsm_clear(int argc, char **argv)
3548 {
3549         return lfs_hsm_change_flags(argc, argv, LFS_HSM_CLEAR);
3550 }
3551
3552 /**
3553  * Check file state and return its fid, to be used by lfs_hsm_request().
3554  *
3555  * \param[in]     file      Path to file to check
3556  * \param[in,out] fid       Pointer to allocated lu_fid struct.
3557  * \param[in,out] last_dev  Pointer to last device id used.
3558  *
3559  * \return 0 on success.
3560  */
3561 static int lfs_hsm_prepare_file(char *file, struct lu_fid *fid,
3562                                 dev_t *last_dev)
3563 {
3564         struct stat     st;
3565         int             rc;
3566
3567         rc = lstat(file, &st);
3568         if (rc) {
3569                 fprintf(stderr, "Cannot stat %s: %s\n", file, strerror(errno));
3570                 return -errno;
3571         }
3572         /* A request should be ... */
3573         if (*last_dev != st.st_dev && *last_dev != 0) {
3574                 fprintf(stderr, "All files should be "
3575                         "on the same filesystem: %s\n", file);
3576                 return -EINVAL;
3577         }
3578         *last_dev = st.st_dev;
3579
3580         rc = llapi_path2fid(file, fid);
3581         if (rc) {
3582                 fprintf(stderr, "Cannot read FID of %s: %s\n",
3583                         file, strerror(-rc));
3584                 return rc;
3585         }
3586         return 0;
3587 }
3588
3589 static int lfs_hsm_request(int argc, char **argv, int action)
3590 {
3591         struct option            long_opts[] = {
3592                 {"filelist", 1, 0, 'l'},
3593                 {"data", 1, 0, 'D'},
3594                 {"archive", 1, 0, 'a'},
3595                 {0, 0, 0, 0}
3596         };
3597         dev_t                    last_dev = 0;
3598         char                     short_opts[] = "l:D:a:";
3599         struct hsm_user_request *hur, *oldhur;
3600         int                      c, i;
3601         size_t                   len;
3602         int                      nbfile;
3603         char                    *line = NULL;
3604         char                    *filelist = NULL;
3605         char                     fullpath[PATH_MAX];
3606         char                    *opaque = NULL;
3607         int                      opaque_len = 0;
3608         int                      archive_id = 0;
3609         FILE                    *fp;
3610         int                      nbfile_alloc = 0;
3611         char                     some_file[PATH_MAX+1] = "";
3612         int                      rc;
3613
3614         if (argc < 2)
3615                 return CMD_HELP;
3616
3617         optind = 0;
3618         while ((c = getopt_long(argc, argv, short_opts,
3619                                 long_opts, NULL)) != -1) {
3620                 switch (c) {
3621                 case 'l':
3622                         filelist = optarg;
3623                         break;
3624                 case 'D':
3625                         opaque = optarg;
3626                         break;
3627                 case 'a':
3628                         if (action != HUA_ARCHIVE) {
3629                                 fprintf(stderr,
3630                                         "error: -a is supported only "
3631                                         "when archiving\n");
3632                                 return CMD_HELP;
3633                         }
3634                         archive_id = atoi(optarg);
3635                         break;
3636                 case '?':
3637                         return CMD_HELP;
3638                 default:
3639                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
3640                                 argv[0], argv[optind - 1]);
3641                         return CMD_HELP;
3642                 }
3643         }
3644
3645         /* All remaining args are files, so we have at least nbfile */
3646         nbfile = argc - optind;
3647
3648         if ((nbfile == 0) && (filelist == NULL))
3649                 return CMD_HELP;
3650
3651         if (opaque != NULL)
3652                 opaque_len = strlen(opaque);
3653
3654         /* Alloc the request structure with enough place to store all files
3655          * from command line. */
3656         hur = llapi_hsm_user_request_alloc(nbfile, opaque_len);
3657         if (hur == NULL) {
3658                 fprintf(stderr, "Cannot create the request: %s\n",
3659                         strerror(errno));
3660                 return errno;
3661         }
3662         nbfile_alloc = nbfile;
3663
3664         hur->hur_request.hr_action = action;
3665         hur->hur_request.hr_archive_id = archive_id;
3666         hur->hur_request.hr_flags = 0;
3667
3668         /* All remaining args are files, add them */
3669         if (nbfile != 0) {
3670                 if (strlen(argv[optind]) > sizeof(some_file)-1) {
3671                         free(hur);
3672                         return -E2BIG;
3673                 }
3674                 strncpy(some_file, argv[optind], sizeof(some_file));
3675         }
3676
3677         for (i = 0; i < nbfile; i++) {
3678                 hur->hur_user_item[i].hui_extent.length = -1;
3679                 rc = lfs_hsm_prepare_file(argv[optind + i],
3680                                           &hur->hur_user_item[i].hui_fid,
3681                                           &last_dev);
3682                 hur->hur_request.hr_itemcount++;
3683                 if (rc)
3684                         goto out_free;
3685         }
3686
3687         /* from here stop using nb_file, use hur->hur_request.hr_itemcount */
3688
3689         /* If a filelist was specified, read the filelist from it. */
3690         if (filelist != NULL) {
3691                 fp = fopen(filelist, "r");
3692                 if (fp == NULL) {
3693                         fprintf(stderr, "Cannot read the file list %s: %s\n",
3694                                 filelist, strerror(errno));
3695                         rc = -errno;
3696                         goto out_free;
3697                 }
3698
3699                 while ((rc = getline(&line, &len, fp)) != -1) {
3700                         struct hsm_user_item *hui;
3701
3702                         /* If allocated buffer was too small, gets something
3703                          * bigger */
3704                         if (nbfile_alloc <= hur->hur_request.hr_itemcount) {
3705                                 nbfile_alloc = nbfile_alloc * 2 + 1;
3706                                 oldhur = hur;
3707                                 hur = llapi_hsm_user_request_alloc(nbfile_alloc,
3708                                                                    opaque_len);
3709                                 if (hur == NULL) {
3710                                         fprintf(stderr, "Cannot allocate "
3711                                                 "the request: %s\n",
3712                                                 strerror(errno));
3713                                         hur = oldhur;
3714                                         rc = -errno;
3715                                         fclose(fp);
3716                                         goto out_free;
3717                                 }
3718                                 memcpy(hur, oldhur, hur_len(oldhur));
3719                                 free(oldhur);
3720                         }
3721
3722                         /* Chop CR */
3723                         if (line[strlen(line) - 1] == '\n')
3724                                 line[strlen(line) - 1] = '\0';
3725
3726                         hui =
3727                              &hur->hur_user_item[hur->hur_request.hr_itemcount];
3728                         hui->hui_extent.length = -1;
3729                         rc = lfs_hsm_prepare_file(line, &hui->hui_fid,
3730                                                   &last_dev);
3731                         hur->hur_request.hr_itemcount++;
3732                         if (rc) {
3733                                 fclose(fp);
3734                                 goto out_free;
3735                         }
3736
3737                         if ((some_file[0] == '\0') &&
3738                             (strlen(line) < sizeof(some_file)))
3739                                 strcpy(some_file, line);
3740                 }
3741
3742                 rc = fclose(fp);
3743                 if (line)
3744                         free(line);
3745         }
3746
3747         /* If a --data was used, add it to the request */
3748         hur->hur_request.hr_data_len = opaque_len;
3749         if (opaque != NULL)
3750                 memcpy(hur_data(hur), opaque, opaque_len);
3751
3752         /* Send the HSM request */
3753         if (realpath(some_file, fullpath) == NULL) {
3754                 fprintf(stderr, "Could not find path '%s': %s\n",
3755                         some_file, strerror(errno));
3756         }
3757         rc = llapi_hsm_request(fullpath, hur);
3758         if (rc) {
3759                 fprintf(stderr, "Cannot send HSM request (use of %s): %s\n",
3760                         some_file, strerror(-rc));
3761                 goto out_free;
3762         }
3763
3764 out_free:
3765         free(hur);
3766         return rc;
3767 }
3768
3769 static int lfs_hsm_archive(int argc, char **argv)
3770 {
3771         return lfs_hsm_request(argc, argv, HUA_ARCHIVE);
3772 }
3773
3774 static int lfs_hsm_restore(int argc, char **argv)
3775 {
3776         return lfs_hsm_request(argc, argv, HUA_RESTORE);
3777 }
3778
3779 static int lfs_hsm_release(int argc, char **argv)
3780 {
3781         return lfs_hsm_request(argc, argv, HUA_RELEASE);
3782 }
3783
3784 static int lfs_hsm_remove(int argc, char **argv)
3785 {
3786         return lfs_hsm_request(argc, argv, HUA_REMOVE);
3787 }
3788
3789 static int lfs_hsm_cancel(int argc, char **argv)
3790 {
3791         return lfs_hsm_request(argc, argv, HUA_CANCEL);
3792 }
3793
3794 static int lfs_swap_layouts(int argc, char **argv)
3795 {
3796         if (argc != 3)
3797                 return CMD_HELP;
3798
3799         return llapi_swap_layouts(argv[1], argv[2], 0, 0,
3800                                   SWAP_LAYOUTS_KEEP_MTIME |
3801                                   SWAP_LAYOUTS_KEEP_ATIME);
3802 }
3803
3804 int main(int argc, char **argv)
3805 {
3806         int rc;
3807
3808         setlinebuf(stdout);
3809
3810         ptl_initialize(argc, argv);
3811         if (obd_initialize(argc, argv) < 0)
3812                 exit(2);
3813
3814         Parser_init("lfs > ", cmdlist);
3815
3816         if (argc > 1) {
3817                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
3818         } else {
3819                 rc = Parser_commands();
3820         }
3821
3822         obd_finalize(argc, argv);
3823         return rc < 0 ? -rc : rc;
3824 }
3825