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