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