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