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