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