Whamcloud - gitweb
LU-5065 utils: uninclude lustre_idl.h from lfs
[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/quota.h>
58 #include <sys/types.h>
59 #include <sys/stat.h>
60 #include <fcntl.h>
61 #include <dirent.h>
62 #include <time.h>
63 #include <ctype.h>
64 #ifdef HAVE_SYS_QUOTA_H
65 # include <sys/quota.h>
66 #endif
67
68 #include <libcfs/libcfs.h>
69 #include <libcfs/libcfsutil.h>
70 #include <lnet/lnetctl.h>
71 #include <lustre/lustreapi.h>
72 #include <lustre_ver.h>
73 #include "obdctl.h"
74
75 /* all functions */
76 static int lfs_setstripe(int argc, char **argv);
77 static int lfs_find(int argc, char **argv);
78 static int lfs_getstripe(int argc, char **argv);
79 static int lfs_getdirstripe(int argc, char **argv);
80 static int lfs_setdirstripe(int argc, char **argv);
81 static int lfs_rmentry(int argc, char **argv);
82 static int lfs_osts(int argc, char **argv);
83 static int lfs_mdts(int argc, char **argv);
84 static int lfs_df(int argc, char **argv);
85 static int lfs_getname(int argc, char **argv);
86 static int lfs_check(int argc, char **argv);
87 #ifdef HAVE_SYS_QUOTA_H
88 static int lfs_quotacheck(int argc, char **argv);
89 static int lfs_quotaon(int argc, char **argv);
90 static int lfs_quotaoff(int argc, char **argv);
91 static int lfs_setquota(int argc, char **argv);
92 static int lfs_quota(int argc, char **argv);
93 #endif
94 static int lfs_flushctx(int argc, char **argv);
95 static int lfs_join(int argc, char **argv);
96 static int lfs_lsetfacl(int argc, char **argv);
97 static int lfs_lgetfacl(int argc, char **argv);
98 static int lfs_rsetfacl(int argc, char **argv);
99 static int lfs_rgetfacl(int argc, char **argv);
100 static int lfs_cp(int argc, char **argv);
101 static int lfs_ls(int argc, char **argv);
102 static int lfs_poollist(int argc, char **argv);
103 static int lfs_changelog(int argc, char **argv);
104 static int lfs_changelog_clear(int argc, char **argv);
105 static int lfs_fid2path(int argc, char **argv);
106 static int lfs_path2fid(int argc, char **argv);
107 static int lfs_data_version(int argc, char **argv);
108 static int lfs_hsm_state(int argc, char **argv);
109 static int lfs_hsm_set(int argc, char **argv);
110 static int lfs_hsm_clear(int argc, char **argv);
111 static int lfs_hsm_action(int argc, char **argv);
112 static int lfs_hsm_archive(int argc, char **argv);
113 static int lfs_hsm_restore(int argc, char **argv);
114 static int lfs_hsm_release(int argc, char **argv);
115 static int lfs_hsm_remove(int argc, char **argv);
116 static int lfs_hsm_cancel(int argc, char **argv);
117 static int lfs_swap_layouts(int argc, char **argv);
118 static int lfs_mv(int argc, char **argv);
119
120 #define SETSTRIPE_USAGE(_cmd, _tgt) \
121         "usage: "_cmd" [--stripe-count|-c <stripe_count>]\n"\
122         "                 [--stripe-index|-i <start_ost_idx>]\n"\
123         "                 [--stripe-size|-S <stripe_size>]\n"\
124         "                 [--pool|-p <pool_name>]\n"\
125         "                 [--block|-b] "_tgt"\n"\
126         "\tstripe_size:  Number of bytes on each OST (0 filesystem default)\n"\
127         "\t              Can be specified with k, m or g (in KB, MB and GB\n"\
128         "\t              respectively)\n"\
129         "\tstart_ost_idx: OST index of first stripe (-1 default)\n"\
130         "\tstripe_count: Number of OSTs to stripe over (0 default, -1 all)\n"\
131         "\tpool_name:    Name of OST pool to use (default none)\n"\
132         "\tblock:        Block file access during data migration"
133
134 /* all avaialable commands */
135 command_t cmdlist[] = {
136         {"setstripe", lfs_setstripe, 0,
137          "Create a new file with a specific striping pattern or\n"
138          "set the default striping pattern on an existing directory or\n"
139          "delete the default striping pattern from an existing directory\n"
140          "usage: setstripe -d <directory>   (to delete default striping)\n"\
141          " or\n"
142          SETSTRIPE_USAGE("setstripe", "<directory|filename>")},
143         {"getstripe", lfs_getstripe, 0,
144          "To list the striping info for a given file or files in a\n"
145          "directory or recursively for all files in a directory tree.\n"
146          "usage: getstripe [--ost|-O <uuid>] [--quiet | -q] [--verbose | -v]\n"
147          "                 [--stripe-count|-c] [--stripe-index|-i]\n"
148          "                 [--pool|-p] [--stripe-size|-S] [--directory|-d]\n"
149          "                 [--mdt-index|-M] [--recursive|-r] [--raw|-R]\n"
150          "                 [--layout|-L]\n"
151          "                 <directory|filename> ..."},
152         {"setdirstripe", lfs_setdirstripe, 0,
153          "To create a remote directory on a specified MDT.\n"
154          "usage: setdirstripe <--count|-c stripe_count>\n"
155          "[--index|-i mdt_index] [--hash-type|-t hash_type]\n"
156          "[--default_stripe|-D ] <dir>\n"
157          "\tstripe_count: stripe count of the striped directory\n"
158          "\tmdt_index:  MDT index of first stripe\n"
159          "\thash_type:  hash type of the striped directory\n"
160          "\tdefault_stripe: set default dirstripe of the directory\n"},
161         {"getdirstripe", lfs_getdirstripe, 0,
162          "To list the striping info for a given directory\n"
163          "or recursively for all directories in a directory tree.\n"
164          "usage: getdirstripe [--obd|-O <uuid>] [--quiet|-q] [--verbose|-v]\n"
165          "               [--count|-c ] [--index|-i ] [--raw|-R]\n"
166          "               [--recursive | -r] [ --default_stripe | -D ] <dir> "},
167         {"mkdir", lfs_setdirstripe, 0,
168          "To create a remote directory on a specified MDT. And this can only\n"
169          "be done on MDT0 by administrator.\n"
170          "usage: mkdir <--index|-i mdt_index> <dir>\n"
171          "\tmdt_index:    MDT index of the remote directory.\n"},
172         {"rm_entry", lfs_rmentry, 0,
173          "To remove the name entry of the remote directory. Note: This\n"
174          "command will only delete the name entry, i.e. the remote directory\n"
175          "will become inaccessable after this command. This can only be done\n"
176          "by the administrator\n"
177          "usage: rm_entry <dir>\n"},
178         {"pool_list", lfs_poollist, 0,
179          "List pools or pool OSTs\n"
180          "usage: pool_list <fsname>[.<pool>] | <pathname>\n"},
181         {"find", lfs_find, 0,
182          "find files matching given attributes recursively in directory tree.\n"
183          "usage: find <directory|filename> ...\n"
184          "     [[!] --atime|-A [+-]N] [[!] --ctime|-C [+-]N]\n"
185          "     [[!] --mtime|-M [+-]N] [[!] --mdt|-m <uuid|index,...>]\n"
186          "     [--maxdepth|-D N] [[!] --name|-n <pattern>]\n"
187          "     [[!] --ost|-O <uuid|index,...>] [--print|-p] [--print0|-P]\n"
188          "     [[!] --size|-s [+-]N[bkMGTPE]]\n"
189          "     [[!] --stripe-count|-c [+-]<stripes>]\n"
190          "     [[!] --stripe-index|-i <index,...>]\n"
191          "     [[!] --stripe-size|-S [+-]N[kMGT]] [[!] --type|-t <filetype>]\n"
192          "     [[!] --gid|-g|--group|-G <gid>|<gname>]\n"
193          "     [[!] --uid|-u|--user|-U <uid>|<uname>] [[!] --pool <pool>]\n"
194          "     [[!] --layout|-L released,raid0]\n"
195          "\t !: used before an option indicates 'NOT' requested attribute\n"
196          "\t -: used before a value indicates 'AT MOST' requested value\n"
197          "\t +: used before a value indicates 'AT LEAST' requested value\n"},
198         {"check", lfs_check, 0,
199          "Display the status of MDS or OSTs (as specified in the command)\n"
200          "or all the servers (MDS and OSTs).\n"
201          "usage: check <osts|mds|servers>"},
202         {"join", lfs_join, 0,
203          "join two lustre files into one.\n"
204          "obsolete, HEAD does not support it anymore.\n"},
205         {"osts", lfs_osts, 0, "list OSTs connected to client "
206          "[for specified path only]\n" "usage: osts [path]"},
207         {"mdts", lfs_mdts, 0, "list MDTs connected to client "
208          "[for specified path only]\n" "usage: mdts [path]"},
209         {"df", lfs_df, 0,
210          "report filesystem disk space usage or inodes usage"
211          "of each MDS and all OSDs or a batch belonging to a specific pool .\n"
212          "Usage: df [-i] [-h] [--lazy|-l] [--pool|-p <fsname>[.<pool>] [path]"},
213         {"getname", lfs_getname, 0, "list instances and specified mount points "
214          "[for specified path only]\n"
215          "Usage: getname [-h]|[path ...] "},
216 #ifdef HAVE_SYS_QUOTA_H
217         {"quotacheck", lfs_quotacheck, 0,
218          "Scan the specified filesystem for disk usage, and create,\n"
219          "or update quota files. Deprecated as of 2.4.0.\n"
220          "usage: quotacheck [ -ug ] <filesystem>"},
221         {"quotaon", lfs_quotaon, 0, "Turn filesystem"
222          " quotas on. Deprecated as of 2.4.0.\n"
223          "usage: quotaon [ -ugf ] <filesystem>"},
224         {"quotaoff", lfs_quotaoff, 0, "Turn filesystem"
225          " quotas off. Deprecated as of 2.4.0.\n"
226          "usage: quotaoff [ -ug ] <filesystem>"},
227         {"setquota", lfs_setquota, 0, "Set filesystem quotas.\n"
228          "usage: setquota <-u|-g> <uname>|<uid>|<gname>|<gid>\n"
229          "                -b <block-softlimit> -B <block-hardlimit>\n"
230          "                -i <inode-softlimit> -I <inode-hardlimit> <filesystem>\n"
231          "       setquota <-u|--user|-g|--group> <uname>|<uid>|<gname>|<gid>\n"
232          "                [--block-softlimit <block-softlimit>]\n"
233          "                [--block-hardlimit <block-hardlimit>]\n"
234          "                [--inode-softlimit <inode-softlimit>]\n"
235          "                [--inode-hardlimit <inode-hardlimit>] <filesystem>\n"
236          "       setquota [-t] <-u|--user|-g|--group>\n"
237          "                [--block-grace <block-grace>]\n"
238          "                [--inode-grace <inode-grace>] <filesystem>\n"
239          "       -b can be used instead of --block-softlimit/--block-grace\n"
240          "       -B can be used instead of --block-hardlimit\n"
241          "       -i can be used instead of --inode-softlimit/--inode-grace\n"
242          "       -I can be used instead of --inode-hardlimit\n\n"
243          "Note: The total quota space will be split into many qunits and\n"
244          "      balanced over all server targets, the minimal qunit size is\n"
245          "      1M bytes for block space and 1K inodes for inode space.\n\n"
246          "      Quota space rebalancing process will stop when this mininum\n"
247          "      value is reached. As a result, quota exceeded can be returned\n"
248          "      while many targets still have 1MB or 1K inodes of spare\n"
249          "      quota space."},
250         {"quota", lfs_quota, 0, "Display disk usage and limits.\n"
251          "usage: quota [-q] [-v] [-h] [-o <obd_uuid>|-i <mdt_idx>|-I "
252                        "<ost_idx>]\n"
253          "             [<-u|-g> <uname>|<uid>|<gname>|<gid>] <filesystem>\n"
254          "       quota [-o <obd_uuid>|-i <mdt_idx>|-I <ost_idx>] -t <-u|-g> <filesystem>"},
255 #endif
256         {"flushctx", lfs_flushctx, 0, "Flush security context for current user.\n"
257          "usage: flushctx [-k] [mountpoint...]"},
258         {"lsetfacl", lfs_lsetfacl, 0,
259          "Remote user setfacl for user/group on the same remote client.\n"
260          "usage: lsetfacl [-bkndRLPvh] [{-m|-x} acl_spec] [{-M|-X} acl_file] file ..."},
261         {"lgetfacl", lfs_lgetfacl, 0,
262          "Remote user getfacl for user/group on the same remote client.\n"
263          "usage: lgetfacl [-dRLPvh] file ..."},
264         {"rsetfacl", lfs_rsetfacl, 0,
265          "Remote user setfacl for user/group on other clients.\n"
266          "usage: rsetfacl [-bkndRLPvh] [{-m|-x} acl_spec] [{-M|-X} acl_file] file ..."},
267         {"rgetfacl", lfs_rgetfacl, 0,
268          "Remote user getfacl for user/group on other clients.\n"
269          "usage: rgetfacl [-dRLPvh] file ..."},
270         {"cp", lfs_cp, 0,
271          "Remote user copy files and directories.\n"
272          "usage: cp [OPTION]... [-T] SOURCE DEST\n\tcp [OPTION]... SOURCE... DIRECTORY\n\tcp [OPTION]... -t DIRECTORY SOURCE..."},
273         {"ls", lfs_ls, 0,
274          "Remote user list directory contents.\n"
275          "usage: ls [OPTION]... [FILE]..."},
276         {"changelog", lfs_changelog, 0,
277          "Show the metadata changes on an MDT."
278          "\nusage: changelog <mdtname> [startrec [endrec]]"},
279         {"changelog_clear", lfs_changelog_clear, 0,
280          "Indicate that old changelog records up to <endrec> are no longer of "
281          "interest to consumer <id>, allowing the system to free up space.\n"
282          "An <endrec> of 0 means all records.\n"
283          "usage: changelog_clear <mdtname> <id> <endrec>"},
284         {"fid2path", lfs_fid2path, 0,
285          "Resolve the full path(s) for given FID(s). For a specific hardlink "
286          "specify link number <linkno>.\n"
287         /* "For a historical link name, specify changelog record <recno>.\n" */
288          "usage: fid2path [--link <linkno>] <fsname|rootpath> <fid> ..."
289                 /* [ --rec <recno> ] */ },
290         {"path2fid", lfs_path2fid, 0, "Display the fid(s) for a given path(s).\n"
291          "usage: path2fid <path> ..."},
292         {"data_version", lfs_data_version, 0, "Display file data version for "
293          "a given path.\n" "usage: data_version -[n|r|w] <path>"},
294         {"hsm_state", lfs_hsm_state, 0, "Display the HSM information (states, "
295          "undergoing actions) for given files.\n usage: hsm_state <file> ..."},
296         {"hsm_set", lfs_hsm_set, 0, "Set HSM user flag on specified files.\n"
297          "usage: hsm_set [--norelease] [--noarchive] [--dirty] [--exists] "
298          "[--archived] [--lost] <file> ..."},
299         {"hsm_clear", lfs_hsm_clear, 0, "Clear HSM user flag on specified "
300          "files.\n"
301          "usage: hsm_clear [--norelease] [--noarchive] [--dirty] [--exists] "
302          "[--archived] [--lost] <file> ..."},
303         {"hsm_action", lfs_hsm_action, 0, "Display current HSM request for "
304          "given files.\n" "usage: hsm_action <file> ..."},
305         {"hsm_archive", lfs_hsm_archive, 0,
306          "Archive file to external storage.\n"
307          "usage: hsm_archive [--filelist FILELIST] [--data DATA] [--archive NUM] "
308          "<file> ..."},
309         {"hsm_restore", lfs_hsm_restore, 0,
310          "Restore file from external storage.\n"
311          "usage: hsm_restore [--filelist FILELIST] [--data DATA] <file> ..."},
312         {"hsm_release", lfs_hsm_release, 0,
313          "Release files from Lustre.\n"
314          "usage: hsm_release [--filelist FILELIST] [--data DATA] <file> ..."},
315         {"hsm_remove", lfs_hsm_remove, 0,
316          "Remove file copy from external storage.\n"
317          "usage: hsm_remove [--filelist FILELIST] [--data DATA] <file> ..."},
318         {"hsm_cancel", lfs_hsm_cancel, 0,
319          "Cancel requests related to specified files.\n"
320          "usage: hsm_cancel [--filelist FILELIST] [--data DATA] <file> ..."},
321         {"swap_layouts", lfs_swap_layouts, 0, "Swap layouts between 2 files.\n"
322          "usage: swap_layouts <path1> <path2>"},
323         {"migrate", lfs_setstripe, 0, "migrate file from one OST layout to "
324          "another (may be not safe with concurent writes).\n"
325          SETSTRIPE_USAGE("migrate  ", "<filename>")},
326         {"mv", lfs_mv, 0,
327          "To move directories between MDTs.\n"
328          "usage: mv <directory|filename> [--mdt-index|-M] <mdt_index> "
329          "[--verbose|-v]\n"},
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 = {
886                 .fp_max_depth = -1,
887                 .quiet = 1,
888         };
889         struct option long_opts[] = {
890                 {"atime",        required_argument, 0, 'A'},
891                 {"stripe-count", required_argument, 0, 'c'},
892                 {"stripe_count", required_argument, 0, 'c'},
893                 {"ctime",        required_argument, 0, 'C'},
894                 {"maxdepth",     required_argument, 0, 'D'},
895                 {"gid",          required_argument, 0, 'g'},
896                 {"group",        required_argument, 0, 'G'},
897                 {"stripe-index", required_argument, 0, 'i'},
898                 {"stripe_index", required_argument, 0, 'i'},
899                 {"layout",       required_argument, 0, 'L'},
900                 {"mdt",          required_argument, 0, 'm'},
901                 {"mtime",        required_argument, 0, 'M'},
902                 {"name",         required_argument, 0, 'n'},
903      /* reserve {"or",           no_argument,     , 0, 'o'}, to match find(1) */
904                 {"obd",          required_argument, 0, 'O'},
905                 {"ost",          required_argument, 0, 'O'},
906                 /* no short option for pool, p/P already used */
907                 {"pool",         required_argument, 0, FIND_POOL_OPT},
908                 {"print0",       no_argument,       0, 'p'},
909                 {"print",        no_argument,       0, 'P'},
910                 {"size",         required_argument, 0, 's'},
911                 {"stripe-size",  required_argument, 0, 'S'},
912                 {"stripe_size",  required_argument, 0, 'S'},
913                 {"type",         required_argument, 0, 't'},
914                 {"uid",          required_argument, 0, 'u'},
915                 {"user",         required_argument, 0, 'U'},
916                 {0, 0, 0, 0}
917         };
918         int pathstart = -1;
919         int pathend = -1;
920         int neg_opt = 0;
921         time_t *xtime;
922         int *xsign;
923         int isoption;
924         char *endptr;
925
926         time(&t);
927
928         optind = 0;
929         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
930         while ((c = getopt_long_only(argc, argv,
931                                      "-A:c:C:D:g:G:i:L:m:M:n:O:Ppqrs:S:t:u:U:v",
932                                      long_opts, NULL)) >= 0) {
933                 xtime = NULL;
934                 xsign = NULL;
935                 if (neg_opt)
936                         --neg_opt;
937                 /* '!' is part of option */
938                 /* when getopt_long_only() finds a string which is not
939                  * an option nor a known option argument it returns 1
940                  * in that case if we already have found pathstart and pathend
941                  * (i.e. we have the list of pathnames),
942                  * the only supported value is "!"
943                  */
944                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
945                 if (!isoption && pathend != -1) {
946                         fprintf(stderr, "err: %s: filename|dirname must either "
947                                         "precede options or follow options\n",
948                                         argv[0]);
949                         ret = CMD_HELP;
950                         goto err;
951                 }
952                 if (!isoption && pathstart == -1)
953                         pathstart = optind - 1;
954                 if (isoption && pathstart != -1 && pathend == -1)
955                         pathend = optind - 2;
956                 switch (c) {
957                 case 0:
958                         /* Long options. */
959                         break;
960                 case 1:
961                         /* unknown; opt is "!" or path component,
962                          * checking done above.
963                          */
964                         if (strcmp(optarg, "!") == 0)
965                                 neg_opt = 2;
966                         break;
967                 case 'A':
968                         xtime = &param.fp_atime;
969                         xsign = &param.fp_asign;
970                         param.fp_exclude_atime = !!neg_opt;
971                         /* no break, this falls through to 'C' for ctime */
972                 case 'C':
973                         if (c == 'C') {
974                                 xtime = &param.fp_ctime;
975                                 xsign = &param.fp_csign;
976                                 param.fp_exclude_ctime = !!neg_opt;
977                         }
978                         /* no break, this falls through to 'M' for mtime */
979                 case 'M':
980                         if (c == 'M') {
981                                 xtime = &param.fp_mtime;
982                                 xsign = &param.fp_msign;
983                                 param.fp_exclude_mtime = !!neg_opt;
984                         }
985                         ret = set_time(&t, xtime, optarg);
986                         if (ret == INT_MAX) {
987                                 ret = -1;
988                                 goto err;
989                         }
990                         if (ret)
991                                 *xsign = ret;
992                         break;
993                 case 'c':
994                         if (optarg[0] == '+') {
995                                 param.stripecount_sign = -1;
996                                 optarg++;
997                         } else if (optarg[0] == '-') {
998                                 param.stripecount_sign =  1;
999                                 optarg++;
1000                         }
1001
1002                         param.stripecount = strtoul(optarg, &endptr, 0);
1003                         if (*endptr != '\0') {
1004                                 fprintf(stderr,"error: bad stripe_count '%s'\n",
1005                                         optarg);
1006                                 ret = -1;
1007                                 goto err;
1008                         }
1009                         param.check_stripecount = 1;
1010                         param.exclude_stripecount = !!neg_opt;
1011                         break;
1012                 case 'D':
1013                         param.fp_max_depth = strtol(optarg, 0, 0);
1014                         break;
1015                 case 'g':
1016                 case 'G':
1017                         ret = name2id(&param.fp_gid, optarg, GROUP);
1018                         if (ret) {
1019                                 param.fp_gid = strtoul(optarg, &endptr, 10);
1020                                 if (*endptr != '\0') {
1021                                         fprintf(stderr, "Group/GID: %s cannot "
1022                                                 "be found.\n", optarg);
1023                                         ret = -1;
1024                                         goto err;
1025                                 }
1026                         }
1027                         param.fp_exclude_gid = !!neg_opt;
1028                         param.fp_check_gid = 1;
1029                         break;
1030                 case 'L':
1031                         ret = name2layout(&param.layout, optarg);
1032                         if (ret)
1033                                 goto err;
1034                         param.exclude_layout = !!neg_opt;
1035                         param.check_layout = 1;
1036                         break;
1037                 case 'u':
1038                 case 'U':
1039                         ret = name2id(&param.fp_uid, optarg, USER);
1040                         if (ret) {
1041                                 param.fp_uid = strtoul(optarg, &endptr, 10);
1042                                 if (*endptr != '\0') {
1043                                         fprintf(stderr, "User/UID: %s cannot "
1044                                                 "be found.\n", optarg);
1045                                         ret = -1;
1046                                         goto err;
1047                                 }
1048                         }
1049                         param.fp_exclude_uid = !!neg_opt;
1050                         param.fp_check_uid = 1;
1051                         break;
1052                 case FIND_POOL_OPT:
1053                         if (strlen(optarg) > LOV_MAXPOOLNAME) {
1054                                 fprintf(stderr,
1055                                         "Pool name %s is too long"
1056                                         " (max is %d)\n", optarg,
1057                                         LOV_MAXPOOLNAME);
1058                                 ret = -1;
1059                                 goto err;
1060                         }
1061                         /* we do check for empty pool because empty pool
1062                          * is used to find V1 lov attributes */
1063                         strncpy(param.poolname, optarg, LOV_MAXPOOLNAME);
1064                         param.poolname[LOV_MAXPOOLNAME] = '\0';
1065                         param.exclude_pool = !!neg_opt;
1066                         param.check_pool = 1;
1067                         break;
1068                 case 'n':
1069                         param.pattern = (char *)optarg;
1070                         param.exclude_pattern = !!neg_opt;
1071                         break;
1072                 case 'm':
1073                 case 'i':
1074                 case 'O': {
1075                         char *buf, *token, *next, *p;
1076                         int len = 1;
1077                         void *tmp;
1078
1079                         buf = strdup(optarg);
1080                         if (buf == NULL) {
1081                                 ret = -ENOMEM;
1082                                 goto err;
1083                         }
1084
1085                         param.exclude_obd = !!neg_opt;
1086
1087                         token = buf;
1088                         while (token && *token) {
1089                                 token = strchr(token, ',');
1090                                 if (token) {
1091                                         len++;
1092                                         token++;
1093                                 }
1094                         }
1095                         if (c == 'm') {
1096                                 param.exclude_mdt = !!neg_opt;
1097                                 param.num_alloc_mdts += len;
1098                                 tmp = realloc(param.mdtuuid,
1099                                               param.num_alloc_mdts *
1100                                               sizeof(*param.mdtuuid));
1101                                 if (tmp == NULL)
1102                                         GOTO(err_free, ret = -ENOMEM);
1103                                 param.mdtuuid = tmp;
1104                         } else {
1105                                 param.exclude_obd = !!neg_opt;
1106                                 param.num_alloc_obds += len;
1107                                 tmp = realloc(param.obduuid,
1108                                               param.num_alloc_obds *
1109                                               sizeof(*param.obduuid));
1110                                 if (tmp == NULL)
1111                                         GOTO(err_free, ret = -ENOMEM);
1112                                 param.obduuid = tmp;
1113                         }
1114                         for (token = buf; token && *token; token = next) {
1115                                 struct obd_uuid *puuid;
1116                                 if (c == 'm') {
1117                                         puuid =
1118                                           &param.mdtuuid[param.num_mdts++];
1119                                 } else {
1120                                         puuid =
1121                                           &param.obduuid[param.num_obds++];
1122                                 }
1123                                 p = strchr(token, ',');
1124                                 next = 0;
1125                                 if (p) {
1126                                         *p = 0;
1127                                         next = p+1;
1128                                 }
1129                                 if (strlen(token) > sizeof(puuid->uuid)-1)
1130                                         GOTO(err_free, ret = -E2BIG);
1131                                 strncpy(puuid->uuid, token,
1132                                         sizeof(puuid->uuid));
1133                         }
1134 err_free:
1135                         if (buf)
1136                                 free(buf);
1137                         break;
1138                 }
1139                 case 'p':
1140                         param.zeroend = 1;
1141                         break;
1142                 case 'P':
1143                         break;
1144                 case 's':
1145                         if (optarg[0] == '+') {
1146                                 param.size_sign = -1;
1147                                 optarg++;
1148                         } else if (optarg[0] == '-') {
1149                                 param.size_sign =  1;
1150                                 optarg++;
1151                         }
1152
1153                         ret = llapi_parse_size(optarg, &param.size,
1154                                                &param.size_units, 0);
1155                         if (ret) {
1156                                 fprintf(stderr, "error: bad file size '%s'\n",
1157                                         optarg);
1158                                 goto err;
1159                         }
1160                         param.check_size = 1;
1161                         param.exclude_size = !!neg_opt;
1162                         break;
1163                 case 'S':
1164                         if (optarg[0] == '+') {
1165                                 param.stripesize_sign = -1;
1166                                 optarg++;
1167                         } else if (optarg[0] == '-') {
1168                                 param.stripesize_sign =  1;
1169                                 optarg++;
1170                         }
1171
1172                         ret = llapi_parse_size(optarg, &param.stripesize,
1173                                                &param.stripesize_units, 0);
1174                         if (ret) {
1175                                 fprintf(stderr, "error: bad stripe_size '%s'\n",
1176                                         optarg);
1177                                 goto err;
1178                         }
1179                         param.check_stripesize = 1;
1180                         param.exclude_stripesize = !!neg_opt;
1181                         break;
1182                 case 't':
1183                         param.fp_exclude_type = !!neg_opt;
1184                         switch (optarg[0]) {
1185                         case 'b':
1186                                 param.fp_type = S_IFBLK;
1187                                 break;
1188                         case 'c':
1189                                 param.fp_type = S_IFCHR;
1190                                 break;
1191                         case 'd':
1192                                 param.fp_type = S_IFDIR;
1193                                 break;
1194                         case 'f':
1195                                 param.fp_type = S_IFREG;
1196                                 break;
1197                         case 'l':
1198                                 param.fp_type = S_IFLNK;
1199                                 break;
1200                         case 'p':
1201                                 param.fp_type = S_IFIFO;
1202                                 break;
1203                         case 's':
1204                                 param.fp_type = S_IFSOCK;
1205                                 break;
1206                         default:
1207                                 fprintf(stderr, "error: %s: bad type '%s'\n",
1208                                         argv[0], optarg);
1209                                 ret = CMD_HELP;
1210                                 goto err;
1211                         };
1212                         break;
1213                 default:
1214                         ret = CMD_HELP;
1215                         goto err;
1216                 };
1217         }
1218
1219         if (pathstart == -1) {
1220                 fprintf(stderr, "error: %s: no filename|pathname\n",
1221                         argv[0]);
1222                 ret = CMD_HELP;
1223                 goto err;
1224         } else if (pathend == -1) {
1225                 /* no options */
1226                 pathend = argc;
1227         }
1228
1229         do {
1230                 ret = llapi_find(argv[pathstart], &param);
1231         } while (++pathstart < pathend && !ret);
1232
1233         if (ret)
1234                 fprintf(stderr, "error: %s failed for %s.\n",
1235                         argv[0], argv[optind - 1]);
1236 err:
1237         if (param.obduuid && param.num_alloc_obds)
1238                 free(param.obduuid);
1239
1240         if (param.mdtuuid && param.num_alloc_mdts)
1241                 free(param.mdtuuid);
1242
1243         return ret;
1244 }
1245
1246 static int lfs_getstripe_internal(int argc, char **argv,
1247                                   struct find_param *param)
1248 {
1249         struct option long_opts[] = {
1250 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1251                 /* This formerly implied "stripe-count", but was explicitly
1252                  * made "stripe-count" for consistency with other options,
1253                  * and to separate it from "mdt-count" when DNE arrives. */
1254                 {"count",               no_argument,            0, 'c'},
1255 #endif
1256                 {"stripe-count",        no_argument,            0, 'c'},
1257                 {"stripe_count",        no_argument,            0, 'c'},
1258                 {"directory",           no_argument,            0, 'd'},
1259                 {"default",             no_argument,            0, 'D'},
1260                 {"generation",          no_argument,            0, 'g'},
1261 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1262                 /* This formerly implied "stripe-index", but was explicitly
1263                  * made "stripe-index" for consistency with other options,
1264                  * and to separate it from "mdt-index" when DNE arrives. */
1265                 {"index",               no_argument,            0, 'i'},
1266 #endif
1267                 {"stripe-index",        no_argument,            0, 'i'},
1268                 {"stripe_index",        no_argument,            0, 'i'},
1269                 {"layout",              no_argument,            0, 'L'},
1270                 {"mdt-index",           no_argument,            0, 'M'},
1271                 {"mdt_index",           no_argument,            0, 'M'},
1272 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1273                 /* This formerly implied "stripe-index", but was confusing
1274                  * with "file offset" (which will eventually be needed for
1275                  * with different layouts by offset), so deprecate it. */
1276                 {"offset",              no_argument,            0, 'o'},
1277 #endif
1278                 {"obd",                 required_argument,      0, 'O'},
1279                 {"ost",                 required_argument,      0, 'O'},
1280                 {"pool",                no_argument,            0, 'p'},
1281                 {"quiet",               no_argument,            0, 'q'},
1282                 {"recursive",           no_argument,            0, 'r'},
1283                 {"raw",                 no_argument,            0, 'R'},
1284 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1285                 /* This formerly implied "--stripe-size", but was confusing
1286                  * with "lfs find --size|-s", which means "file size", so use
1287                  * the consistent "--stripe-size|-S" for all commands. */
1288                 {"size",                no_argument,            0, 's'},
1289 #endif
1290                 {"stripe-size",         no_argument,            0, 'S'},
1291                 {"stripe_size",         no_argument,            0, 'S'},
1292                 {"verbose",             no_argument,            0, 'v'},
1293                 {0, 0, 0, 0}
1294         };
1295         int c, rc;
1296
1297         param->fp_max_depth = 1;
1298         optind = 0;
1299         while ((c = getopt_long(argc, argv, "cdDghiLMoO:pqrRsSv",
1300                                 long_opts, NULL)) != -1) {
1301                 switch (c) {
1302                 case 'O':
1303                         if (param->obduuid) {
1304                                 fprintf(stderr,
1305                                         "error: %s: only one obduuid allowed",
1306                                         argv[0]);
1307                                 return CMD_HELP;
1308                         }
1309                         param->obduuid = (struct obd_uuid *)optarg;
1310                         break;
1311                 case 'q':
1312                         param->quiet++;
1313                         break;
1314                 case 'd':
1315                         param->fp_max_depth = 0;
1316                         break;
1317                 case 'D':
1318                         param->get_default_lmv = 1;
1319                         break;
1320                 case 'r':
1321                         param->recursive = 1;
1322                         break;
1323                 case 'v':
1324                         param->verbose = VERBOSE_ALL | VERBOSE_DETAIL;
1325                         break;
1326                 case 'c':
1327 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 6, 53, 0)
1328                         if (strcmp(argv[optind - 1], "--count") == 0)
1329                                 fprintf(stderr, "warning: '--count' deprecated,"
1330                                         " use '--stripe-count' instead\n");
1331 #endif
1332                         if (!(param->verbose & VERBOSE_DETAIL)) {
1333                                 param->verbose |= VERBOSE_COUNT;
1334                                 param->fp_max_depth = 0;
1335                         }
1336                         break;
1337 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1338                 case 's':
1339 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 6, 53, 0)
1340                         fprintf(stderr, "warning: '--size|-s' deprecated, "
1341                                 "use '--stripe-size|-S' instead\n");
1342 #endif
1343 #endif /* LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0) */
1344                 case 'S':
1345                         if (!(param->verbose & VERBOSE_DETAIL)) {
1346                                 param->verbose |= VERBOSE_SIZE;
1347                                 param->fp_max_depth = 0;
1348                         }
1349                         break;
1350 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1351                 case 'o':
1352                         fprintf(stderr, "warning: '--offset|-o' deprecated, "
1353                                 "use '--stripe-index|-i' instead\n");
1354 #endif
1355                 case 'i':
1356 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 6, 53, 0)
1357                         if (strcmp(argv[optind - 1], "--index") == 0)
1358                                 fprintf(stderr, "warning: '--index' deprecated"
1359                                         ", use '--stripe-index' instead\n");
1360 #endif
1361                         if (!(param->verbose & VERBOSE_DETAIL)) {
1362                                 param->verbose |= VERBOSE_OFFSET;
1363                                 param->fp_max_depth = 0;
1364                         }
1365                         break;
1366                 case 'p':
1367                         if (!(param->verbose & VERBOSE_DETAIL)) {
1368                                 param->verbose |= VERBOSE_POOL;
1369                                 param->fp_max_depth = 0;
1370                         }
1371                         break;
1372                 case 'g':
1373                         if (!(param->verbose & VERBOSE_DETAIL)) {
1374                                 param->verbose |= VERBOSE_GENERATION;
1375                                 param->fp_max_depth = 0;
1376                         }
1377                         break;
1378                 case 'L':
1379                         if (!(param->verbose & VERBOSE_DETAIL)) {
1380                                 param->verbose |= VERBOSE_LAYOUT;
1381                                 param->fp_max_depth = 0;
1382                         }
1383                         break;
1384                 case 'M':
1385                         if (!(param->verbose & VERBOSE_DETAIL))
1386                                 param->fp_max_depth = 0;
1387                         param->verbose |= VERBOSE_MDTINDEX;
1388                         break;
1389                 case 'R':
1390                         param->raw = 1;
1391                         break;
1392                 default:
1393                         return CMD_HELP;
1394                 }
1395         }
1396
1397         if (optind >= argc)
1398                 return CMD_HELP;
1399
1400         if (param->recursive)
1401                 param->fp_max_depth = -1;
1402
1403         if (!param->verbose)
1404                 param->verbose = VERBOSE_ALL;
1405         if (param->quiet)
1406                 param->verbose = VERBOSE_OBJID;
1407
1408         do {
1409                 rc = llapi_getstripe(argv[optind], param);
1410         } while (++optind < argc && !rc);
1411
1412         if (rc)
1413                 fprintf(stderr, "error: %s failed for %s.\n",
1414                         argv[0], argv[optind - 1]);
1415         return rc;
1416 }
1417
1418 static int lfs_tgts(int argc, char **argv)
1419 {
1420         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
1421         struct find_param param;
1422         int index = 0, rc=0;
1423
1424         if (argc > 2)
1425                 return CMD_HELP;
1426
1427         if (argc == 2 && !realpath(argv[1], path)) {
1428                 rc = -errno;
1429                 fprintf(stderr, "error: invalid path '%s': %s\n",
1430                         argv[1], strerror(-rc));
1431                 return rc;
1432         }
1433
1434         while (!llapi_search_mounts(path, index++, mntdir, NULL)) {
1435                 /* Check if we have a mount point */
1436                 if (mntdir[0] == '\0')
1437                         continue;
1438
1439                 memset(&param, 0, sizeof(param));
1440                 if (!strcmp(argv[0], "mdts"))
1441                         param.get_lmv = 1;
1442
1443                 rc = llapi_ostlist(mntdir, &param);
1444                 if (rc) {
1445                         fprintf(stderr, "error: %s: failed on %s\n",
1446                                 argv[0], mntdir);
1447                 }
1448                 if (path[0] != '\0')
1449                         break;
1450                 memset(mntdir, 0, PATH_MAX);
1451         }
1452
1453         return rc;
1454 }
1455
1456 static int lfs_getstripe(int argc, char **argv)
1457 {
1458         struct find_param param = { 0 };
1459         return lfs_getstripe_internal(argc, argv, &param);
1460 }
1461
1462 /* functions */
1463 static int lfs_getdirstripe(int argc, char **argv)
1464 {
1465         struct find_param param = { 0 };
1466
1467         param.get_lmv = 1;
1468         return lfs_getstripe_internal(argc, argv, &param);
1469 }
1470
1471 /* functions */
1472 static int lfs_setdirstripe(int argc, char **argv)
1473 {
1474         char                    *dname;
1475         int                     result;
1476         unsigned int            stripe_offset = -1;
1477         unsigned int            stripe_count = 1;
1478         enum lmv_hash_type      hash_type;
1479         char                    *end;
1480         int                     c;
1481         char                    *stripe_offset_opt = NULL;
1482         char                    *stripe_count_opt = NULL;
1483         char                    *stripe_hash_opt = NULL;
1484         int                     default_stripe = 0;
1485
1486         struct option long_opts[] = {
1487                 {"count",       required_argument, 0, 'c'},
1488                 {"index",       required_argument, 0, 'i'},
1489                 {"hash-type",   required_argument, 0, 't'},
1490                 {"default_stripe", required_argument, 0, 'D'},
1491                 {0, 0, 0, 0}
1492         };
1493
1494         optind = 0;
1495
1496         while ((c = getopt_long(argc, argv, "c:Di:t:", long_opts, NULL)) >= 0) {
1497                 switch (c) {
1498                 case 0:
1499                         /* Long options. */
1500                         break;
1501                 case 'c':
1502                         stripe_count_opt = optarg;
1503                         break;
1504                 case 'D':
1505                         default_stripe = 1;
1506                         break;
1507                 case 'i':
1508                         stripe_offset_opt = optarg;
1509                         break;
1510                 case 't':
1511                         stripe_hash_opt = optarg;
1512                         break;
1513                 default:
1514                         fprintf(stderr, "error: %s: option '%s' "
1515                                         "unrecognized\n",
1516                                         argv[0], argv[optind - 1]);
1517                         return CMD_HELP;
1518                 }
1519         }
1520
1521         if (optind == argc) {
1522                 fprintf(stderr, "error: %s: missing dirname\n",
1523                         argv[0]);
1524                 return CMD_HELP;
1525         }
1526
1527         if (stripe_offset_opt == NULL && stripe_count_opt == NULL) {
1528                 fprintf(stderr, "error: %s: missing stripe offset and count.\n",
1529                         argv[0]);
1530                 return CMD_HELP;
1531         }
1532
1533         if (stripe_offset_opt != NULL) {
1534                 /* get the stripe offset */
1535                 stripe_offset = strtoul(stripe_offset_opt, &end, 0);
1536                 if (*end != '\0') {
1537                         fprintf(stderr, "error: %s: bad stripe offset '%s'\n",
1538                                 argv[0], stripe_offset_opt);
1539                         return CMD_HELP;
1540                 }
1541         }
1542
1543         if (stripe_hash_opt == NULL ||
1544             strcmp(stripe_hash_opt, LMV_HASH_NAME_FNV_1A_64) == 0) {
1545                 hash_type = LMV_HASH_TYPE_FNV_1A_64;
1546         } else if (strcmp(stripe_hash_opt, LMV_HASH_NAME_ALL_CHARS) == 0) {
1547                 hash_type = LMV_HASH_TYPE_ALL_CHARS;
1548         } else {
1549                 fprintf(stderr, "error: %s: bad stripe hash type '%s'\n",
1550                         argv[0], stripe_hash_opt);
1551                 return CMD_HELP;
1552         }
1553
1554         /* get the stripe count */
1555         if (stripe_count_opt != NULL) {
1556                 stripe_count = strtoul(stripe_count_opt, &end, 0);
1557                 if (*end != '\0') {
1558                         fprintf(stderr, "error: %s: bad stripe count '%s'\n",
1559                                 argv[0], stripe_count_opt);
1560                         return CMD_HELP;
1561                 }
1562         }
1563
1564         dname = argv[optind];
1565         do {
1566                 if (default_stripe == 1) {
1567                         result = llapi_dir_set_default_lmv_stripe(dname,
1568                                                     stripe_offset, stripe_count,
1569                                                     hash_type, NULL);
1570                 } else {
1571                         result = llapi_dir_create_pool(dname, 0, stripe_offset,
1572                                                        stripe_count, hash_type,
1573                                                        NULL);
1574                 }
1575
1576                 if (result) {
1577                         fprintf(stderr, "error: %s: create stripe dir '%s' "
1578                                 "failed\n", argv[0], dname);
1579                         break;
1580                 }
1581                 dname = argv[++optind];
1582         } while (dname != NULL);
1583
1584         return result;
1585 }
1586
1587 /* functions */
1588 static int lfs_rmentry(int argc, char **argv)
1589 {
1590         char *dname;
1591         int   index;
1592         int   result = 0;
1593
1594         if (argc <= 1) {
1595                 fprintf(stderr, "error: %s: missing dirname\n",
1596                         argv[0]);
1597                 return CMD_HELP;
1598         }
1599
1600         index = 1;
1601         dname = argv[index];
1602         while (dname != NULL) {
1603                 result = llapi_direntry_remove(dname);
1604                 if (result) {
1605                         fprintf(stderr, "error: %s: remove dir entry '%s' "
1606                                 "failed\n", argv[0], dname);
1607                         break;
1608                 }
1609                 dname = argv[++index];
1610         }
1611         return result;
1612 }
1613
1614 static int lfs_mv(int argc, char **argv)
1615 {
1616         struct  find_param param = {
1617                 .fp_max_depth = -1,
1618                 .mdtindex = -1,
1619         };
1620         char   *end;
1621         int     c;
1622         int     rc = 0;
1623         struct option long_opts[] = {
1624                 {"--mdt-index", required_argument, 0, 'M'},
1625                 {"verbose",     no_argument,       0, 'v'},
1626                 {0, 0, 0, 0}
1627         };
1628
1629         while ((c = getopt_long(argc, argv, "M:v", long_opts, NULL)) != -1) {
1630                 switch (c) {
1631                 case 'M': {
1632                         param.mdtindex = strtoul(optarg, &end, 0);
1633                         if (*end != '\0') {
1634                                 fprintf(stderr, "%s: invalid MDT index'%s'\n",
1635                                         argv[0], optarg);
1636                                 return CMD_HELP;
1637                         }
1638                         break;
1639                 }
1640                 case 'v': {
1641                         param.verbose = VERBOSE_DETAIL;
1642                         break;
1643                 }
1644                 default:
1645                         fprintf(stderr, "error: %s: unrecognized option '%s'\n",
1646                                 argv[0], argv[optind - 1]);
1647                         return CMD_HELP;
1648                 }
1649         }
1650
1651         if (param.mdtindex == -1) {
1652                 fprintf(stderr, "%s MDT index must be indicated\n", argv[0]);
1653                 return CMD_HELP;
1654         }
1655
1656         if (optind >= argc) {
1657                 fprintf(stderr, "%s missing operand path\n", argv[0]);
1658                 return CMD_HELP;
1659         }
1660
1661         param.migrate = 1;
1662         rc = llapi_mv(argv[optind], &param);
1663         if (rc != 0)
1664                 fprintf(stderr, "cannot migrate '%s' to MDT%04x: %s\n",
1665                         argv[optind], param.mdtindex, strerror(-rc));
1666         return rc;
1667 }
1668
1669 static int lfs_osts(int argc, char **argv)
1670 {
1671         return lfs_tgts(argc, argv);
1672 }
1673
1674 static int lfs_mdts(int argc, char **argv)
1675 {
1676         return lfs_tgts(argc, argv);
1677 }
1678
1679 #define COOK(value)                                                     \
1680 ({                                                                      \
1681         int radix = 0;                                                  \
1682         while (value > 1024) {                                          \
1683                 value /= 1024;                                          \
1684                 radix++;                                                \
1685         }                                                               \
1686         radix;                                                          \
1687 })
1688 #define UUF     "%-20s"
1689 #define CSF     "%11s"
1690 #define CDF     "%11llu"
1691 #define HDF     "%8.1f%c"
1692 #define RSF     "%4s"
1693 #define RDF     "%3d%%"
1694
1695 static int showdf(char *mntdir, struct obd_statfs *stat,
1696                   char *uuid, int ishow, int cooked,
1697                   char *type, int index, int rc)
1698 {
1699         long long avail, used, total;
1700         double ratio = 0;
1701         char *suffix = "KMGTPEZY";
1702         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
1703         char tbuf[20], ubuf[20], abuf[20], rbuf[20];
1704
1705         if (!uuid || !stat)
1706                 return -EINVAL;
1707
1708         switch (rc) {
1709         case 0:
1710                 if (ishow) {
1711                         avail = stat->os_ffree;
1712                         used = stat->os_files - stat->os_ffree;
1713                         total = stat->os_files;
1714                 } else {
1715                         int shift = cooked ? 0 : 10;
1716
1717                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
1718                         used  = ((stat->os_blocks - stat->os_bfree) *
1719                                  stat->os_bsize) >> shift;
1720                         total = (stat->os_blocks * stat->os_bsize) >> shift;
1721                 }
1722
1723                 if ((used + avail) > 0)
1724                         ratio = (double)used / (double)(used + avail);
1725
1726                 if (cooked) {
1727                         int i;
1728                         double cook_val;
1729
1730                         cook_val = (double)total;
1731                         i = COOK(cook_val);
1732                         if (i > 0)
1733                                 sprintf(tbuf, HDF, cook_val, suffix[i - 1]);
1734                         else
1735                                 sprintf(tbuf, CDF, total);
1736
1737                         cook_val = (double)used;
1738                         i = COOK(cook_val);
1739                         if (i > 0)
1740                                 sprintf(ubuf, HDF, cook_val, suffix[i - 1]);
1741                         else
1742                                 sprintf(ubuf, CDF, used);
1743
1744                         cook_val = (double)avail;
1745                         i = COOK(cook_val);
1746                         if (i > 0)
1747                                 sprintf(abuf, HDF, cook_val, suffix[i - 1]);
1748                         else
1749                                 sprintf(abuf, CDF, avail);
1750                 } else {
1751                         sprintf(tbuf, CDF, total);
1752                         sprintf(ubuf, CDF, used);
1753                         sprintf(abuf, CDF, avail);
1754                 }
1755
1756                 sprintf(rbuf, RDF, (int)(ratio * 100 + 0.5));
1757                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
1758                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
1759                 if (type)
1760                         printf("[%s:%d]\n", type, index);
1761                 else
1762                         printf("\n");
1763
1764                 break;
1765         case -ENODATA:
1766                 printf(UUF": inactive device\n", uuid);
1767                 break;
1768         default:
1769                 printf(UUF": %s\n", uuid, strerror(-rc));
1770                 break;
1771         }
1772
1773         return 0;
1774 }
1775
1776 struct ll_stat_type {
1777         int   st_op;
1778         char *st_name;
1779 };
1780
1781 static int mntdf(char *mntdir, char *fsname, char *pool, int ishow,
1782                 int cooked, int lazy)
1783 {
1784         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
1785         struct obd_uuid uuid_buf;
1786         char *poolname = NULL;
1787         struct ll_stat_type types[] = { { LL_STATFS_LMV, "MDT" },
1788                                         { LL_STATFS_LOV, "OST" },
1789                                         { 0, NULL } };
1790         struct ll_stat_type *tp;
1791         __u64 ost_ffree = 0;
1792         __u32 index;
1793         __u32 type;
1794         int rc;
1795
1796         if (pool) {
1797                 poolname = strchr(pool, '.');
1798                 if (poolname != NULL) {
1799                         if (strncmp(fsname, pool, strlen(fsname))) {
1800                                 fprintf(stderr, "filesystem name incorrect\n");
1801                                 return -ENODEV;
1802                         }
1803                         poolname++;
1804                 } else
1805                         poolname = pool;
1806         }
1807
1808         if (ishow)
1809                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
1810                        "UUID", "Inodes", "IUsed", "IFree",
1811                        "IUse%", "Mounted on");
1812         else
1813                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
1814                        "UUID", cooked ? "bytes" : "1K-blocks",
1815                        "Used", "Available", "Use%", "Mounted on");
1816
1817         for (tp = types; tp->st_name != NULL; tp++) {
1818                 for (index = 0; ; index++) {
1819                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
1820                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
1821                         type = lazy ? tp->st_op | LL_STATFS_NODELAY : tp->st_op;
1822                         rc = llapi_obd_statfs(mntdir, type, index,
1823                                               &stat_buf, &uuid_buf);
1824                         if (rc == -ENODEV)
1825                                 break;
1826
1827                         if (poolname && tp->st_op == LL_STATFS_LOV &&
1828                             llapi_search_ost(fsname, poolname,
1829                                              obd_uuid2str(&uuid_buf)) != 1)
1830                                 continue;
1831
1832                         /* the llapi_obd_statfs() call may have returned with
1833                          * an error, but if it filled in uuid_buf we will at
1834                          * lease use that to print out a message for that OBD.
1835                          * If we didn't get anything in the uuid_buf, then fill
1836                          * it in so that we can print an error message. */
1837                         if (uuid_buf.uuid[0] == '\0')
1838                                 sprintf(uuid_buf.uuid, "%s%04x",
1839                                         tp->st_name, index);
1840                         showdf(mntdir, &stat_buf, obd_uuid2str(&uuid_buf),
1841                                ishow, cooked, tp->st_name, index, rc);
1842
1843                         if (rc == 0) {
1844                                 if (tp->st_op == LL_STATFS_LMV) {
1845                                         sum.os_ffree += stat_buf.os_ffree;
1846                                         sum.os_files += stat_buf.os_files;
1847                                 } else /* if (tp->st_op == LL_STATFS_LOV) */ {
1848                                         sum.os_blocks += stat_buf.os_blocks *
1849                                                 stat_buf.os_bsize;
1850                                         sum.os_bfree  += stat_buf.os_bfree *
1851                                                 stat_buf.os_bsize;
1852                                         sum.os_bavail += stat_buf.os_bavail *
1853                                                 stat_buf.os_bsize;
1854                                         ost_ffree += stat_buf.os_ffree;
1855                                 }
1856                         } else if (rc == -EINVAL || rc == -EFAULT) {
1857                                 break;
1858                         }
1859                 }
1860         }
1861
1862         /* If we don't have as many objects free on the OST as inodes
1863          * on the MDS, we reduce the total number of inodes to
1864          * compensate, so that the "inodes in use" number is correct.
1865          * Matches ll_statfs_internal() so the results are consistent. */
1866         if (ost_ffree < sum.os_ffree) {
1867                 sum.os_files = (sum.os_files - sum.os_ffree) + ost_ffree;
1868                 sum.os_ffree = ost_ffree;
1869         }
1870         printf("\n");
1871         showdf(mntdir, &sum, "filesystem summary:", ishow, cooked, NULL, 0, 0);
1872         printf("\n");
1873         return 0;
1874 }
1875
1876 static int lfs_df(int argc, char **argv)
1877 {
1878         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
1879         int ishow = 0, cooked = 0;
1880         int lazy = 0;
1881         int c, rc = 0, index = 0;
1882         char fsname[PATH_MAX] = "", *pool_name = NULL;
1883         struct option long_opts[] = {
1884                 {"pool", required_argument, 0, 'p'},
1885                 {"lazy", 0, 0, 'l'},
1886                 {0, 0, 0, 0}
1887         };
1888
1889         optind = 0;
1890         while ((c = getopt_long(argc, argv, "hilp:", long_opts, NULL)) != -1) {
1891                 switch (c) {
1892                 case 'i':
1893                         ishow = 1;
1894                         break;
1895                 case 'h':
1896                         cooked = 1;
1897                         break;
1898                 case 'l':
1899                         lazy = 1;
1900                         break;
1901                 case 'p':
1902                         pool_name = optarg;
1903                         break;
1904                 default:
1905                         return CMD_HELP;
1906                 }
1907         }
1908         if (optind < argc && !realpath(argv[optind], path)) {
1909                 rc = -errno;
1910                 fprintf(stderr, "error: invalid path '%s': %s\n",
1911                         argv[optind], strerror(-rc));
1912                 return rc;
1913         }
1914
1915         while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
1916                 /* Check if we have a mount point */
1917                 if (mntdir[0] == '\0')
1918                         continue;
1919
1920                 rc = mntdf(mntdir, fsname, pool_name, ishow, cooked, lazy);
1921                 if (rc || path[0] != '\0')
1922                         break;
1923                 fsname[0] = '\0'; /* avoid matching in next loop */
1924                 mntdir[0] = '\0'; /* avoid matching in next loop */
1925         }
1926
1927         return rc;
1928 }
1929
1930 static int lfs_getname(int argc, char **argv)
1931 {
1932         char mntdir[PATH_MAX] = "", path[PATH_MAX] = "", fsname[PATH_MAX] = "";
1933         int rc = 0, index = 0, c;
1934         char buf[sizeof(struct obd_uuid)];
1935
1936         optind = 0;
1937         while ((c = getopt(argc, argv, "h")) != -1)
1938                 return CMD_HELP;
1939
1940         if (optind == argc) { /* no paths specified, get all paths. */
1941                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
1942                         rc = llapi_getname(mntdir, buf, sizeof(buf));
1943                         if (rc < 0) {
1944                                 fprintf(stderr,
1945                                         "cannot get name for `%s': %s\n",
1946                                         mntdir, strerror(-rc));
1947                                 break;
1948                         }
1949
1950                         printf("%s %s\n", buf, mntdir);
1951
1952                         path[0] = fsname[0] = mntdir[0] = 0;
1953                 }
1954         } else { /* paths specified, only attempt to search these. */
1955                 for (; optind < argc; optind++) {
1956                         rc = llapi_getname(argv[optind], buf, sizeof(buf));
1957                         if (rc < 0) {
1958                                 fprintf(stderr,
1959                                         "cannot get name for `%s': %s\n",
1960                                         argv[optind], strerror(-rc));
1961                                 break;
1962                         }
1963
1964                         printf("%s %s\n", buf, argv[optind]);
1965                 }
1966         }
1967         return rc;
1968 }
1969
1970 static int lfs_check(int argc, char **argv)
1971 {
1972         int rc;
1973         char mntdir[PATH_MAX] = {'\0'};
1974         int num_types = 1;
1975         char *obd_types[2];
1976         char obd_type1[4];
1977         char obd_type2[4];
1978
1979         if (argc != 2)
1980                 return CMD_HELP;
1981
1982         obd_types[0] = obd_type1;
1983         obd_types[1] = obd_type2;
1984
1985         if (strcmp(argv[1], "osts") == 0) {
1986                 strcpy(obd_types[0], "osc");
1987         } else if (strcmp(argv[1], "mds") == 0) {
1988                 strcpy(obd_types[0], "mdc");
1989         } else if (strcmp(argv[1], "servers") == 0) {
1990                 num_types = 2;
1991                 strcpy(obd_types[0], "osc");
1992                 strcpy(obd_types[1], "mdc");
1993         } else {
1994                 fprintf(stderr, "error: %s: option '%s' unrecognized\n",
1995                                 argv[0], argv[1]);
1996                         return CMD_HELP;
1997         }
1998
1999         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
2000         if (rc < 0 || mntdir[0] == '\0') {
2001                 fprintf(stderr, "No suitable Lustre mount found\n");
2002                 return rc;
2003         }
2004
2005         rc = llapi_target_iterate(num_types, obd_types,
2006                                   mntdir, llapi_ping_target);
2007
2008         if (rc)
2009                 fprintf(stderr, "error: %s: %s status failed\n",
2010                                 argv[0],argv[1]);
2011
2012         return rc;
2013
2014 }
2015
2016 static int lfs_join(int argc, char **argv)
2017 {
2018         fprintf(stderr, "join two lustre files into one.\n"
2019                         "obsolete, HEAD does not support it anymore.\n");
2020         return 0;
2021 }
2022
2023 #ifdef HAVE_SYS_QUOTA_H
2024 static int lfs_quotacheck(int argc, char **argv)
2025 {
2026         int c, check_type = 0;
2027         char *mnt;
2028         struct if_quotacheck qchk;
2029         struct if_quotactl qctl;
2030         char *obd_type = (char *)qchk.obd_type;
2031         int rc;
2032
2033         memset(&qchk, 0, sizeof(qchk));
2034
2035         optind = 0;
2036         while ((c = getopt(argc, argv, "gu")) != -1) {
2037                 switch (c) {
2038                 case 'u':
2039                         check_type |= 0x01;
2040                         break;
2041                 case 'g':
2042                         check_type |= 0x02;
2043                         break;
2044                 default:
2045                         fprintf(stderr, "error: %s: option '-%c' "
2046                                         "unrecognized\n", argv[0], c);
2047                         return CMD_HELP;
2048                 }
2049         }
2050
2051         if (check_type)
2052                 check_type--;
2053         else    /* do quotacheck for both user & group quota by default */
2054                 check_type = 0x02;
2055
2056         if (argc == optind)
2057                 return CMD_HELP;
2058
2059         mnt = argv[optind];
2060
2061         rc = llapi_quotacheck(mnt, check_type);
2062         if (rc == -EOPNOTSUPP) {
2063                 fprintf(stderr, "error: quotacheck not supported by the quota "
2064                         "master.\nPlease note that quotacheck is deprecated as "
2065                         "of lustre 2.4.0 since space accounting is always "
2066                         "enabled.\nFilesystems not formatted with 2.4 utils or "
2067                         "beyond can be upgraded with tunefs.lustre --quota.\n");
2068                 return rc;
2069         } else if (rc) {
2070                 fprintf(stderr, "quotacheck failed: %s\n", strerror(-rc));
2071                 return rc;
2072         }
2073
2074         rc = llapi_poll_quotacheck(mnt, &qchk);
2075         if (rc) {
2076                 if (*obd_type)
2077                         fprintf(stderr, "%s %s ", obd_type,
2078                                 obd_uuid2str(&qchk.obd_uuid));
2079                 fprintf(stderr, "quota check failed: %s\n", strerror(-rc));
2080                 return rc;
2081         }
2082
2083         memset(&qctl, 0, sizeof(qctl));
2084         qctl.qc_cmd = LUSTRE_Q_QUOTAON;
2085         qctl.qc_type = check_type;
2086         rc = llapi_quotactl(mnt, &qctl);
2087         if (rc && rc != -EALREADY) {
2088                 if (*obd_type)
2089                         fprintf(stderr, "%s %s ", (char *)qctl.obd_type,
2090                                 obd_uuid2str(&qctl.obd_uuid));
2091                 fprintf(stderr, "%s turn on quota failed: %s\n",
2092                         argv[0], strerror(-rc));
2093                 return rc;
2094         }
2095
2096         return 0;
2097 }
2098
2099 static int lfs_quotaon(int argc, char **argv)
2100 {
2101         int c;
2102         char *mnt;
2103         struct if_quotactl qctl;
2104         char *obd_type = (char *)qctl.obd_type;
2105         int rc;
2106
2107         memset(&qctl, 0, sizeof(qctl));
2108         qctl.qc_cmd = LUSTRE_Q_QUOTAON;
2109
2110         optind = 0;
2111         while ((c = getopt(argc, argv, "fgu")) != -1) {
2112                 switch (c) {
2113                 case 'u':
2114                         qctl.qc_type |= 0x01;
2115                         break;
2116                 case 'g':
2117                         qctl.qc_type |= 0x02;
2118                         break;
2119                 case 'f':
2120                         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
2121                         break;
2122                 default:
2123                         fprintf(stderr, "error: %s: option '-%c' "
2124                                         "unrecognized\n", argv[0], c);
2125                         return CMD_HELP;
2126                 }
2127         }
2128
2129         if (qctl.qc_type)
2130                 qctl.qc_type--;
2131         else /* by default, enable quota for both user & group */
2132                 qctl.qc_type = 0x02;
2133
2134         if (argc == optind)
2135                 return CMD_HELP;
2136
2137         mnt = argv[optind];
2138
2139         rc = llapi_quotactl(mnt, &qctl);
2140         if (rc) {
2141                 if (rc == -EOPNOTSUPP) {
2142                         fprintf(stderr, "error: quotaon not supported by the "
2143                                 "quota master.\nPlease note that quotaon/off is"
2144                                 " deprecated as of lustre 2.4.0.\nQuota "
2145                                 "enforcement should now be enabled on the MGS "
2146                                 "via:\nmgs# lctl conf_param ${FSNAME}.quota."
2147                                 "<ost|mdt>=<u|g|ug>\n(ost for block quota, mdt "
2148                                 "for inode quota, u for user and g for group"
2149                                 "\n");
2150                 } else if (rc == -EALREADY) {
2151                         rc = 0;
2152                 } else if (rc == -ENOENT) {
2153                         fprintf(stderr, "error: cannot find quota database, "
2154                                         "make sure you have run quotacheck\n");
2155                 } else {
2156                         if (*obd_type)
2157                                 fprintf(stderr, "%s %s ", obd_type,
2158                                         obd_uuid2str(&qctl.obd_uuid));
2159                         fprintf(stderr, "%s failed: %s\n", argv[0],
2160                                 strerror(-rc));
2161                 }
2162         }
2163
2164         return rc;
2165 }
2166
2167 static int lfs_quotaoff(int argc, char **argv)
2168 {
2169         int c;
2170         char *mnt;
2171         struct if_quotactl qctl;
2172         char *obd_type = (char *)qctl.obd_type;
2173         int rc;
2174
2175         memset(&qctl, 0, sizeof(qctl));
2176         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
2177
2178         optind = 0;
2179         while ((c = getopt(argc, argv, "gu")) != -1) {
2180                 switch (c) {
2181                 case 'u':
2182                         qctl.qc_type |= 0x01;
2183                         break;
2184                 case 'g':
2185                         qctl.qc_type |= 0x02;
2186                         break;
2187                 default:
2188                         fprintf(stderr, "error: %s: option '-%c' "
2189                                         "unrecognized\n", argv[0], c);
2190                         return CMD_HELP;
2191                 }
2192         }
2193
2194         if (qctl.qc_type)
2195                 qctl.qc_type--;
2196         else /* by default, disable quota for both user & group */
2197                 qctl.qc_type = 0x02;
2198
2199         if (argc == optind)
2200                 return CMD_HELP;
2201
2202         mnt = argv[optind];
2203
2204         rc = llapi_quotactl(mnt, &qctl);
2205         if (rc) {
2206                 if (rc == -EOPNOTSUPP) {
2207                         fprintf(stderr, "error: quotaoff not supported by the "
2208                                 "quota master.\nPlease note that quotaon/off is"
2209                                 " deprecated as of lustre 2.4.0.\nQuota "
2210                                 "enforcement can be disabled on the MGS via:\n"
2211                                 "mgs# lctl conf_param ${FSNAME}.quota.<ost|mdt>"
2212                                 "=\"\"\n");
2213                 } else if (rc == -EALREADY) {
2214                         rc = 0;
2215                 } else {
2216                         if (*obd_type)
2217                                 fprintf(stderr, "%s %s ", obd_type,
2218                                         obd_uuid2str(&qctl.obd_uuid));
2219                         fprintf(stderr, "quotaoff failed: %s\n",
2220                                 strerror(-rc));
2221                 }
2222         }
2223
2224         return rc;
2225 }
2226
2227 #define ARG2INT(nr, str, msg)                                           \
2228 do {                                                                    \
2229         char *endp;                                                     \
2230         nr = strtol(str, &endp, 0);                                     \
2231         if (*endp) {                                                    \
2232                 fprintf(stderr, "error: bad %s: %s\n", msg, str);       \
2233                 return CMD_HELP;                                        \
2234         }                                                               \
2235 } while (0)
2236
2237 #define ADD_OVERFLOW(a,b) ((a + b) < a) ? (a = ULONG_MAX) : (a = a + b)
2238
2239 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
2240  * returns the value or ULONG_MAX on integer overflow or incorrect format
2241  * Notes:
2242  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
2243  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
2244  *        3. empty integer value is interpreted as 0
2245  */
2246 static unsigned long str2sec(const char* timestr)
2247 {
2248         const char spec[] = "smhdw";
2249         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
2250         unsigned long val = 0;
2251         char *tail;
2252
2253         if (strpbrk(timestr, spec) == NULL) {
2254                 /* no specifiers inside the time string,
2255                    should treat it as an integer value */
2256                 val = strtoul(timestr, &tail, 10);
2257                 return *tail ? ULONG_MAX : val;
2258         }
2259
2260         /* format string is XXwXXdXXhXXmXXs */
2261         while (*timestr) {
2262                 unsigned long v;
2263                 int ind;
2264                 char* ptr;
2265
2266                 v = strtoul(timestr, &tail, 10);
2267                 if (v == ULONG_MAX || *tail == '\0')
2268                         /* value too large (ULONG_MAX or more)
2269                            or missing specifier */
2270                         goto error;
2271
2272                 ptr = strchr(spec, *tail);
2273                 if (ptr == NULL)
2274                         /* unknown specifier */
2275                         goto error;
2276
2277                 ind = ptr - spec;
2278
2279                 /* check if product will overflow the type */
2280                 if (!(v < ULONG_MAX / mult[ind]))
2281                         goto error;
2282
2283                 ADD_OVERFLOW(val, mult[ind] * v);
2284                 if (val == ULONG_MAX)
2285                         goto error;
2286
2287                 timestr = tail + 1;
2288         }
2289
2290         return val;
2291
2292 error:
2293         return ULONG_MAX;
2294 }
2295
2296 #define ARG2ULL(nr, str, def_units)                                     \
2297 do {                                                                    \
2298         unsigned long long limit, units = def_units;                    \
2299         int rc;                                                         \
2300                                                                         \
2301         rc = llapi_parse_size(str, &limit, &units, 1);                  \
2302         if (rc < 0) {                                                   \
2303                 fprintf(stderr, "error: bad limit value %s\n", str);    \
2304                 return CMD_HELP;                                        \
2305         }                                                               \
2306         nr = limit;                                                     \
2307 } while (0)
2308
2309 static inline int has_times_option(int argc, char **argv)
2310 {
2311         int i;
2312
2313         for (i = 1; i < argc; i++)
2314                 if (!strcmp(argv[i], "-t"))
2315                         return 1;
2316
2317         return 0;
2318 }
2319
2320 int lfs_setquota_times(int argc, char **argv)
2321 {
2322         int c, rc;
2323         struct if_quotactl qctl;
2324         char *mnt, *obd_type = (char *)qctl.obd_type;
2325         struct obd_dqblk *dqb = &qctl.qc_dqblk;
2326         struct obd_dqinfo *dqi = &qctl.qc_dqinfo;
2327         struct option long_opts[] = {
2328                 {"block-grace",     required_argument, 0, 'b'},
2329                 {"group",           no_argument,       0, 'g'},
2330                 {"inode-grace",     required_argument, 0, 'i'},
2331                 {"times",           no_argument,       0, 't'},
2332                 {"user",            no_argument,       0, 'u'},
2333                 {0, 0, 0, 0}
2334         };
2335
2336         memset(&qctl, 0, sizeof(qctl));
2337         qctl.qc_cmd  = LUSTRE_Q_SETINFO;
2338         qctl.qc_type = UGQUOTA;
2339
2340         optind = 0;
2341         while ((c = getopt_long(argc, argv, "b:gi:tu", long_opts, NULL)) != -1) {
2342                 switch (c) {
2343                 case 'u':
2344                 case 'g':
2345                         if (qctl.qc_type != UGQUOTA) {
2346                                 fprintf(stderr, "error: -u and -g can't be used "
2347                                                 "more than once\n");
2348                                 return CMD_HELP;
2349                         }
2350                         qctl.qc_type = (c == 'u') ? USRQUOTA : GRPQUOTA;
2351                         break;
2352                 case 'b':
2353                         if ((dqi->dqi_bgrace = str2sec(optarg)) == ULONG_MAX) {
2354                                 fprintf(stderr, "error: bad block-grace: %s\n",
2355                                         optarg);
2356                                 return CMD_HELP;
2357                         }
2358                         dqb->dqb_valid |= QIF_BTIME;
2359                         break;
2360                 case 'i':
2361                         if ((dqi->dqi_igrace = str2sec(optarg)) == ULONG_MAX) {
2362                                 fprintf(stderr, "error: bad inode-grace: %s\n",
2363                                         optarg);
2364                                 return CMD_HELP;
2365                         }
2366                         dqb->dqb_valid |= QIF_ITIME;
2367                         break;
2368                 case 't': /* Yes, of course! */
2369                         break;
2370                 default: /* getopt prints error message for us when opterr != 0 */
2371                         return CMD_HELP;
2372                 }
2373         }
2374
2375         if (qctl.qc_type == UGQUOTA) {
2376                 fprintf(stderr, "error: neither -u nor -g specified\n");
2377                 return CMD_HELP;
2378         }
2379
2380         if (optind != argc - 1) {
2381                 fprintf(stderr, "error: unexpected parameters encountered\n");
2382                 return CMD_HELP;
2383         }
2384
2385         mnt = argv[optind];
2386         rc = llapi_quotactl(mnt, &qctl);
2387         if (rc) {
2388                 if (*obd_type)
2389                         fprintf(stderr, "%s %s ", obd_type,
2390                                 obd_uuid2str(&qctl.obd_uuid));
2391                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
2392                 return rc;
2393         }
2394
2395         return 0;
2396 }
2397
2398 #define BSLIMIT (1 << 0)
2399 #define BHLIMIT (1 << 1)
2400 #define ISLIMIT (1 << 2)
2401 #define IHLIMIT (1 << 3)
2402
2403 int lfs_setquota(int argc, char **argv)
2404 {
2405         int c, rc;
2406         struct if_quotactl qctl;
2407         char *mnt, *obd_type = (char *)qctl.obd_type;
2408         struct obd_dqblk *dqb = &qctl.qc_dqblk;
2409         struct option long_opts[] = {
2410                 {"block-softlimit", required_argument, 0, 'b'},
2411                 {"block-hardlimit", required_argument, 0, 'B'},
2412                 {"group",           required_argument, 0, 'g'},
2413                 {"inode-softlimit", required_argument, 0, 'i'},
2414                 {"inode-hardlimit", required_argument, 0, 'I'},
2415                 {"user",            required_argument, 0, 'u'},
2416                 {0, 0, 0, 0}
2417         };
2418         unsigned limit_mask = 0;
2419         char *endptr;
2420
2421         if (has_times_option(argc, argv))
2422                 return lfs_setquota_times(argc, argv);
2423
2424         memset(&qctl, 0, sizeof(qctl));
2425         qctl.qc_cmd  = LUSTRE_Q_SETQUOTA;
2426         qctl.qc_type = UGQUOTA; /* UGQUOTA makes no sense for setquota,
2427                                  * so it can be used as a marker that qc_type
2428                                  * isn't reinitialized from command line */
2429
2430         optind = 0;
2431         while ((c = getopt_long(argc, argv, "b:B:g:i:I:u:", long_opts, NULL)) != -1) {
2432                 switch (c) {
2433                 case 'u':
2434                 case 'g':
2435                         if (qctl.qc_type != UGQUOTA) {
2436                                 fprintf(stderr, "error: -u and -g can't be used"
2437                                                 " more than once\n");
2438                                 return CMD_HELP;
2439                         }
2440                         qctl.qc_type = (c == 'u') ? USRQUOTA : GRPQUOTA;
2441                         rc = name2id(&qctl.qc_id, optarg,
2442                                      (qctl.qc_type == USRQUOTA) ? USER : GROUP);
2443                         if (rc) {
2444                                 qctl.qc_id = strtoul(optarg, &endptr, 10);
2445                                 if (*endptr != '\0') {
2446                                         fprintf(stderr, "error: can't find id "
2447                                                 "for name %s\n", optarg);
2448                                         return CMD_HELP;
2449                                 }
2450                         }
2451                         break;
2452                 case 'b':
2453                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
2454                         dqb->dqb_bsoftlimit >>= 10;
2455                         limit_mask |= BSLIMIT;
2456                         if (dqb->dqb_bsoftlimit &&
2457                             dqb->dqb_bsoftlimit <= 1024) /* <= 1M? */
2458                                 fprintf(stderr, "warning: block softlimit is "
2459                                         "smaller than the miminal qunit size, "
2460                                         "please see the help of setquota or "
2461                                         "Lustre manual for details.\n");
2462                         break;
2463                 case 'B':
2464                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
2465                         dqb->dqb_bhardlimit >>= 10;
2466                         limit_mask |= BHLIMIT;
2467                         if (dqb->dqb_bhardlimit &&
2468                             dqb->dqb_bhardlimit <= 1024) /* <= 1M? */
2469                                 fprintf(stderr, "warning: block hardlimit is "
2470                                         "smaller than the miminal qunit size, "
2471                                         "please see the help of setquota or "
2472                                         "Lustre manual for details.\n");
2473                         break;
2474                 case 'i':
2475                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
2476                         limit_mask |= ISLIMIT;
2477                         if (dqb->dqb_isoftlimit &&
2478                             dqb->dqb_isoftlimit <= 1024) /* <= 1K inodes? */
2479                                 fprintf(stderr, "warning: inode softlimit is "
2480                                         "smaller than the miminal qunit size, "
2481                                         "please see the help of setquota or "
2482                                         "Lustre manual for details.\n");
2483                         break;
2484                 case 'I':
2485                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
2486                         limit_mask |= IHLIMIT;
2487                         if (dqb->dqb_ihardlimit &&
2488                             dqb->dqb_ihardlimit <= 1024) /* <= 1K inodes? */
2489                                 fprintf(stderr, "warning: inode hardlimit is "
2490                                         "smaller than the miminal qunit size, "
2491                                         "please see the help of setquota or "
2492                                         "Lustre manual for details.\n");
2493                         break;
2494                 default: /* getopt prints error message for us when opterr != 0 */
2495                         return CMD_HELP;
2496                 }
2497         }
2498
2499         if (qctl.qc_type == UGQUOTA) {
2500                 fprintf(stderr, "error: neither -u nor -g was specified\n");
2501                 return CMD_HELP;
2502         }
2503
2504         if (limit_mask == 0) {
2505                 fprintf(stderr, "error: at least one limit must be specified\n");
2506                 return CMD_HELP;
2507         }
2508
2509         if (optind != argc - 1) {
2510                 fprintf(stderr, "error: unexpected parameters encountered\n");
2511                 return CMD_HELP;
2512         }
2513
2514         mnt = argv[optind];
2515
2516         if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
2517             (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
2518                 /* sigh, we can't just set blimits/ilimits */
2519                 struct if_quotactl tmp_qctl = {.qc_cmd  = LUSTRE_Q_GETQUOTA,
2520                                                .qc_type = qctl.qc_type,
2521                                                .qc_id   = qctl.qc_id};
2522
2523                 rc = llapi_quotactl(mnt, &tmp_qctl);
2524                 if (rc < 0) {
2525                         fprintf(stderr, "error: setquota failed while retrieving"
2526                                         " current quota settings (%s)\n",
2527                                         strerror(-rc));
2528                         return rc;
2529                 }
2530
2531                 if (!(limit_mask & BHLIMIT))
2532                         dqb->dqb_bhardlimit = tmp_qctl.qc_dqblk.dqb_bhardlimit;
2533                 if (!(limit_mask & BSLIMIT))
2534                         dqb->dqb_bsoftlimit = tmp_qctl.qc_dqblk.dqb_bsoftlimit;
2535                 if (!(limit_mask & IHLIMIT))
2536                         dqb->dqb_ihardlimit = tmp_qctl.qc_dqblk.dqb_ihardlimit;
2537                 if (!(limit_mask & ISLIMIT))
2538                         dqb->dqb_isoftlimit = tmp_qctl.qc_dqblk.dqb_isoftlimit;
2539
2540                 /* Keep grace times if we have got no softlimit arguments */
2541                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
2542                         dqb->dqb_valid |= QIF_BTIME;
2543                         dqb->dqb_btime = tmp_qctl.qc_dqblk.dqb_btime;
2544                 }
2545
2546                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
2547                         dqb->dqb_valid |= QIF_ITIME;
2548                         dqb->dqb_itime = tmp_qctl.qc_dqblk.dqb_itime;
2549                 }
2550         }
2551
2552         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
2553         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
2554
2555         rc = llapi_quotactl(mnt, &qctl);
2556         if (rc) {
2557                 if (*obd_type)
2558                         fprintf(stderr, "%s %s ", obd_type,
2559                                 obd_uuid2str(&qctl.obd_uuid));
2560                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
2561                 return rc;
2562         }
2563
2564         return 0;
2565 }
2566
2567 static inline char *type2name(int check_type)
2568 {
2569         if (check_type == USRQUOTA)
2570                 return "user";
2571         else if (check_type == GRPQUOTA)
2572                 return "group";
2573         else
2574                 return "unknown";
2575 }
2576
2577 /* Converts seconds value into format string
2578  * result is returned in buf
2579  * Notes:
2580  *        1. result is in descenting order: 1w2d3h4m5s
2581  *        2. zero fields are not filled (except for p. 3): 5d1s
2582  *        3. zero seconds value is presented as "0s"
2583  */
2584 static char * __sec2str(time_t seconds, char *buf)
2585 {
2586         const char spec[] = "smhdw";
2587         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
2588         unsigned long c;
2589         char *tail = buf;
2590         int i;
2591
2592         for (i = sizeof(mult) / sizeof(mult[0]) - 1 ; i >= 0; i--) {
2593                 c = seconds / mult[i];
2594
2595                 if (c > 0 || (i == 0 && buf == tail))
2596                         tail += snprintf(tail, 40-(tail-buf), "%lu%c", c, spec[i]);
2597
2598                 seconds %= mult[i];
2599         }
2600
2601         return tail;
2602 }
2603
2604 static void sec2str(time_t seconds, char *buf, int rc)
2605 {
2606         char *tail = buf;
2607
2608         if (rc)
2609                 *tail++ = '[';
2610
2611         tail = __sec2str(seconds, tail);
2612
2613         if (rc && tail - buf < 39) {
2614                 *tail++ = ']';
2615                 *tail++ = 0;
2616         }
2617 }
2618
2619 static void diff2str(time_t seconds, char *buf, time_t now)
2620 {
2621
2622         buf[0] = 0;
2623         if (!seconds)
2624                 return;
2625         if (seconds <= now) {
2626                 strcpy(buf, "none");
2627                 return;
2628         }
2629         __sec2str(seconds - now, buf);
2630 }
2631
2632 static void print_quota_title(char *name, struct if_quotactl *qctl,
2633                               bool human_readable)
2634 {
2635         printf("Disk quotas for %s %s (%cid %u):\n",
2636                type2name(qctl->qc_type), name,
2637                *type2name(qctl->qc_type), qctl->qc_id);
2638         printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
2639                "Filesystem", human_readable ? "used" : "kbytes",
2640                "quota", "limit", "grace",
2641                "files", "quota", "limit", "grace");
2642 }
2643
2644 static void kbytes2str(__u64 num, char *buf, bool h)
2645 {
2646         if (!h) {
2647                 sprintf(buf, LPU64, num);
2648         } else {
2649                 if (num >> 30)
2650                         sprintf(buf, "%5.4gT", (double)num / (1 << 30));
2651                 else if (num >> 20)
2652                         sprintf(buf, "%5.4gG", (double)num / (1 << 20));
2653                 else if (num >> 10)
2654                         sprintf(buf, "%5.4gM", (double)num / (1 << 10));
2655                 else
2656                         sprintf(buf, LPU64"%s", num, "k");
2657         }
2658 }
2659
2660 static void print_quota(char *mnt, struct if_quotactl *qctl, int type,
2661                         int rc, bool h)
2662 {
2663         time_t now;
2664
2665         time(&now);
2666
2667         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA) {
2668                 int bover = 0, iover = 0;
2669                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
2670                 char numbuf[3][32];
2671                 char timebuf[40];
2672                 char strbuf[32];
2673
2674                 if (dqb->dqb_bhardlimit &&
2675                     lustre_stoqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
2676                         bover = 1;
2677                 } else if (dqb->dqb_bsoftlimit && dqb->dqb_btime) {
2678                         if (dqb->dqb_btime > now) {
2679                                 bover = 2;
2680                         } else {
2681                                 bover = 3;
2682                         }
2683                 }
2684
2685                 if (dqb->dqb_ihardlimit &&
2686                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
2687                         iover = 1;
2688                 } else if (dqb->dqb_isoftlimit && dqb->dqb_itime) {
2689                         if (dqb->dqb_itime > now) {
2690                                 iover = 2;
2691                         } else {
2692                                 iover = 3;
2693                         }
2694                 }
2695
2696
2697                 if (strlen(mnt) > 15)
2698                         printf("%s\n%15s", mnt, "");
2699                 else
2700                         printf("%15s", mnt);
2701
2702                 if (bover)
2703                         diff2str(dqb->dqb_btime, timebuf, now);
2704
2705                 kbytes2str(lustre_stoqb(dqb->dqb_curspace), strbuf, h);
2706                 if (rc == -EREMOTEIO)
2707                         sprintf(numbuf[0], "%s*", strbuf);
2708                 else
2709                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
2710                                 "%s" : "[%s]", strbuf);
2711
2712                 kbytes2str(dqb->dqb_bsoftlimit, strbuf, h);
2713                 if (type == QC_GENERAL)
2714                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS) ?
2715                                 "%s" : "[%s]", strbuf);
2716                 else
2717                         sprintf(numbuf[1], "%s", "-");
2718
2719                 kbytes2str(dqb->dqb_bhardlimit, strbuf, h);
2720                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS) ?
2721                         "%s" : "[%s]", strbuf);
2722
2723                 printf(" %7s%c %6s %7s %7s",
2724                        numbuf[0], bover ? '*' : ' ', numbuf[1],
2725                        numbuf[2], bover > 1 ? timebuf : "-");
2726
2727                 if (iover)
2728                         diff2str(dqb->dqb_itime, timebuf, now);
2729
2730                 sprintf(numbuf[0], (dqb->dqb_valid & QIF_INODES) ?
2731                         LPU64 : "["LPU64"]", dqb->dqb_curinodes);
2732
2733                 if (type == QC_GENERAL)
2734                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS) ?
2735                                 LPU64 : "["LPU64"]", dqb->dqb_isoftlimit);
2736                 else
2737                         sprintf(numbuf[1], "%s", "-");
2738
2739                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
2740                         LPU64 : "["LPU64"]", dqb->dqb_ihardlimit);
2741
2742                 if (type != QC_OSTIDX)
2743                         printf(" %7s%c %6s %7s %7s",
2744                                numbuf[0], iover ? '*' : ' ', numbuf[1],
2745                                numbuf[2], iover > 1 ? timebuf : "-");
2746                 else
2747                         printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
2748                 printf("\n");
2749
2750         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO ||
2751                    qctl->qc_cmd == Q_GETOINFO) {
2752                 char bgtimebuf[40];
2753                 char igtimebuf[40];
2754
2755                 sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
2756                 sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
2757                 printf("Block grace time: %s; Inode grace time: %s\n",
2758                        bgtimebuf, igtimebuf);
2759         }
2760 }
2761
2762 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt,
2763                            bool h, __u64 *total)
2764 {
2765         int rc = 0, rc1 = 0, count = 0;
2766         __u32 valid = qctl->qc_valid;
2767
2768         rc = llapi_get_obd_count(mnt, &count, is_mdt);
2769         if (rc) {
2770                 fprintf(stderr, "can not get %s count: %s\n",
2771                         is_mdt ? "mdt": "ost", strerror(-rc));
2772                 return rc;
2773         }
2774
2775         for (qctl->qc_idx = 0; qctl->qc_idx < count; qctl->qc_idx++) {
2776                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
2777                 rc = llapi_quotactl(mnt, qctl);
2778                 if (rc) {
2779                         /* It is remote client case. */
2780                         if (-rc == EOPNOTSUPP) {
2781                                 rc = 0;
2782                                 goto out;
2783                         }
2784
2785                         if (!rc1)
2786                                 rc1 = rc;
2787                         fprintf(stderr, "quotactl %s%d failed.\n",
2788                                 is_mdt ? "mdt": "ost", qctl->qc_idx);
2789                         continue;
2790                 }
2791
2792                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl,
2793                             qctl->qc_valid, 0, h);
2794                 *total += is_mdt ? qctl->qc_dqblk.dqb_ihardlimit :
2795                                    qctl->qc_dqblk.dqb_bhardlimit;
2796         }
2797 out:
2798         qctl->qc_valid = valid;
2799         return rc ? : rc1;
2800 }
2801
2802 static int lfs_quota(int argc, char **argv)
2803 {
2804         int c;
2805         char *mnt, *name = NULL;
2806         struct if_quotactl qctl = { .qc_cmd = LUSTRE_Q_GETQUOTA,
2807                                     .qc_type = UGQUOTA };
2808         char *obd_type = (char *)qctl.obd_type;
2809         char *obd_uuid = (char *)qctl.obd_uuid.uuid;
2810         int rc, rc1 = 0, rc2 = 0, rc3 = 0,
2811             verbose = 0, pass = 0, quiet = 0, inacc;
2812         char *endptr;
2813         __u32 valid = QC_GENERAL, idx = 0;
2814         __u64 total_ialloc = 0, total_balloc = 0;
2815         bool human_readable = false;
2816
2817         optind = 0;
2818         while ((c = getopt(argc, argv, "gi:I:o:qtuvh")) != -1) {
2819                 switch (c) {
2820                 case 'u':
2821                         if (qctl.qc_type != UGQUOTA) {
2822                                 fprintf(stderr, "error: use either -u or -g\n");
2823                                 return CMD_HELP;
2824                         }
2825                         qctl.qc_type = USRQUOTA;
2826                         break;
2827                 case 'g':
2828                         if (qctl.qc_type != UGQUOTA) {
2829                                 fprintf(stderr, "error: use either -u or -g\n");
2830                                 return CMD_HELP;
2831                         }
2832                         qctl.qc_type = GRPQUOTA;
2833                         break;
2834                 case 't':
2835                         qctl.qc_cmd = LUSTRE_Q_GETINFO;
2836                         break;
2837                 case 'o':
2838                         valid = qctl.qc_valid = QC_UUID;
2839                         strncpy(obd_uuid, optarg, sizeof(qctl.obd_uuid));
2840                         break;
2841                 case 'i':
2842                         valid = qctl.qc_valid = QC_MDTIDX;
2843                         idx = qctl.qc_idx = atoi(optarg);
2844                         break;
2845                 case 'I':
2846                         valid = qctl.qc_valid = QC_OSTIDX;
2847                         idx = qctl.qc_idx = atoi(optarg);
2848                         break;
2849                 case 'v':
2850                         verbose = 1;
2851                         break;
2852                 case 'q':
2853                         quiet = 1;
2854                         break;
2855                 case 'h':
2856                         human_readable = true;
2857                         break;
2858                 default:
2859                         fprintf(stderr, "error: %s: option '-%c' "
2860                                         "unrecognized\n", argv[0], c);
2861                         return CMD_HELP;
2862                 }
2863         }
2864
2865         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
2866         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA && qctl.qc_type == UGQUOTA &&
2867             optind == argc - 1) {
2868 ug_output:
2869                 memset(&qctl, 0, sizeof(qctl)); /* spoiled by print_*_quota */
2870                 qctl.qc_cmd = LUSTRE_Q_GETQUOTA;
2871                 qctl.qc_valid = valid;
2872                 qctl.qc_idx = idx;
2873                 if (pass++ == 0) {
2874                         qctl.qc_type = USRQUOTA;
2875                         qctl.qc_id = geteuid();
2876                 } else {
2877                         qctl.qc_type = GRPQUOTA;
2878                         qctl.qc_id = getegid();
2879                 }
2880                 rc = id2name(&name, qctl.qc_id,
2881                              (qctl.qc_type == USRQUOTA) ? USER : GROUP);
2882                 if (rc)
2883                         name = "<unknown>";
2884         /* lfs quota -u username /path/to/lustre/mount */
2885         } else if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) {
2886                 /* options should be followed by u/g-name and mntpoint */
2887                 if (optind + 2 != argc || qctl.qc_type == UGQUOTA) {
2888                         fprintf(stderr, "error: missing quota argument(s)\n");
2889                         return CMD_HELP;
2890                 }
2891
2892                 name = argv[optind++];
2893                 rc = name2id(&qctl.qc_id, name,
2894                              (qctl.qc_type == USRQUOTA) ? USER : GROUP);
2895                 if (rc) {
2896                         qctl.qc_id = strtoul(name, &endptr, 10);
2897                         if (*endptr != '\0') {
2898                                 fprintf(stderr, "error: can't find id for name "
2899                                         "%s\n", name);
2900                                 return CMD_HELP;
2901                         }
2902                 }
2903         } else if (optind + 1 != argc || qctl.qc_type == UGQUOTA) {
2904                 fprintf(stderr, "error: missing quota info argument(s)\n");
2905                 return CMD_HELP;
2906         }
2907
2908         mnt = argv[optind];
2909
2910         rc1 = llapi_quotactl(mnt, &qctl);
2911         if (rc1 < 0) {
2912                 switch (rc1) {
2913                 case -ESRCH:
2914                         fprintf(stderr, "%s quotas are not enabled.\n",
2915                                 qctl.qc_type == USRQUOTA ? "user" : "group");
2916                         goto out;
2917                 case -EPERM:
2918                         fprintf(stderr, "Permission denied.\n");
2919                 case -ENOENT:
2920                         /* We already got a "No such file..." message. */
2921                         goto out;
2922                 default:
2923                         fprintf(stderr, "Unexpected quotactl error: %s\n",
2924                                 strerror(-rc1));
2925                 }
2926         }
2927
2928         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA && !quiet)
2929                 print_quota_title(name, &qctl, human_readable);
2930
2931         if (rc1 && *obd_type)
2932                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
2933
2934         if (qctl.qc_valid != QC_GENERAL)
2935                 mnt = "";
2936
2937         inacc = (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) &&
2938                 ((qctl.qc_dqblk.dqb_valid & (QIF_LIMITS|QIF_USAGE)) !=
2939                  (QIF_LIMITS|QIF_USAGE));
2940
2941         print_quota(mnt, &qctl, QC_GENERAL, rc1, human_readable);
2942
2943         if (qctl.qc_valid == QC_GENERAL && qctl.qc_cmd != LUSTRE_Q_GETINFO &&
2944             verbose) {
2945                 char strbuf[32];
2946
2947                 rc2 = print_obd_quota(mnt, &qctl, 1, human_readable,
2948                                       &total_ialloc);
2949                 rc3 = print_obd_quota(mnt, &qctl, 0, human_readable,
2950                                       &total_balloc);
2951                 kbytes2str(total_balloc, strbuf, human_readable);
2952                 printf("Total allocated inode limit: "LPU64", total "
2953                        "allocated block limit: %s\n", total_ialloc, strbuf);
2954         }
2955
2956         if (rc1 || rc2 || rc3 || inacc)
2957                 printf("Some errors happened when getting quota info. "
2958                        "Some devices may be not working or deactivated. "
2959                        "The data in \"[]\" is inaccurate.\n");
2960
2961 out:
2962         if (pass == 1)
2963                 goto ug_output;
2964
2965         return rc1;
2966 }
2967 #endif /* HAVE_SYS_QUOTA_H! */
2968
2969 static int flushctx_ioctl(char *mp)
2970 {
2971         int fd, rc;
2972
2973         fd = open(mp, O_RDONLY);
2974         if (fd == -1) {
2975                 fprintf(stderr, "flushctx: error open %s: %s\n",
2976                         mp, strerror(errno));
2977                 return -1;
2978         }
2979
2980         rc = ioctl(fd, LL_IOC_FLUSHCTX);
2981         if (rc == -1)
2982                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
2983                         mp, strerror(errno));
2984
2985         close(fd);
2986         return rc;
2987 }
2988
2989 static int lfs_flushctx(int argc, char **argv)
2990 {
2991         int     kdestroy = 0, c;
2992         FILE   *proc = NULL;
2993         char    procline[PATH_MAX], *line;
2994         int     rc = 0;
2995
2996         optind = 0;
2997         while ((c = getopt(argc, argv, "k")) != -1) {
2998                 switch (c) {
2999                 case 'k':
3000                         kdestroy = 1;
3001                         break;
3002                 default: