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