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