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