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