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