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