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