Whamcloud - gitweb
LU-4929 llite: use the correct mode for striped directory
[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, ret;
886         time_t t;
887         struct find_param param = {
888                 .fp_max_depth = -1,
889                 .quiet = 1,
890         };
891         struct option long_opts[] = {
892                 {"atime",        required_argument, 0, 'A'},
893                 {"stripe-count", required_argument, 0, 'c'},
894                 {"stripe_count", required_argument, 0, 'c'},
895                 {"ctime",        required_argument, 0, 'C'},
896                 {"maxdepth",     required_argument, 0, 'D'},
897                 {"gid",          required_argument, 0, 'g'},
898                 {"group",        required_argument, 0, 'G'},
899                 {"stripe-index", required_argument, 0, 'i'},
900                 {"stripe_index", required_argument, 0, 'i'},
901                 {"layout",       required_argument, 0, 'L'},
902                 {"mdt",          required_argument, 0, 'm'},
903                 {"mtime",        required_argument, 0, 'M'},
904                 {"name",         required_argument, 0, 'n'},
905      /* reserve {"or",           no_argument,     , 0, 'o'}, to match find(1) */
906                 {"obd",          required_argument, 0, 'O'},
907                 {"ost",          required_argument, 0, 'O'},
908                 /* no short option for pool, p/P already used */
909                 {"pool",         required_argument, 0, FIND_POOL_OPT},
910                 {"print0",       no_argument,       0, 'p'},
911                 {"print",        no_argument,       0, 'P'},
912                 {"size",         required_argument, 0, 's'},
913                 {"stripe-size",  required_argument, 0, 'S'},
914                 {"stripe_size",  required_argument, 0, 'S'},
915                 {"type",         required_argument, 0, 't'},
916                 {"uid",          required_argument, 0, 'u'},
917                 {"user",         required_argument, 0, 'U'},
918                 {0, 0, 0, 0}
919         };
920         int pathstart = -1;
921         int pathend = -1;
922         int neg_opt = 0;
923         time_t *xtime;
924         int *xsign;
925         int isoption;
926         char *endptr;
927
928         time(&t);
929
930         optind = 0;
931         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
932         while ((c = getopt_long_only(argc, argv,
933                                      "-A:c:C:D:g:G:i:L:m:M:n:O:Ppqrs:S:t:u:U:v",
934                                      long_opts, NULL)) >= 0) {
935                 xtime = NULL;
936                 xsign = NULL;
937                 if (neg_opt)
938                         --neg_opt;
939                 /* '!' is part of option */
940                 /* when getopt_long_only() finds a string which is not
941                  * an option nor a known option argument it returns 1
942                  * in that case if we already have found pathstart and pathend
943                  * (i.e. we have the list of pathnames),
944                  * the only supported value is "!"
945                  */
946                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
947                 if (!isoption && pathend != -1) {
948                         fprintf(stderr, "err: %s: filename|dirname must either "
949                                         "precede options or follow options\n",
950                                         argv[0]);
951                         ret = CMD_HELP;
952                         goto err;
953                 }
954                 if (!isoption && pathstart == -1)
955                         pathstart = optind - 1;
956                 if (isoption && pathstart != -1 && pathend == -1)
957                         pathend = optind - 2;
958                 switch (c) {
959                 case 0:
960                         /* Long options. */
961                         break;
962                 case 1:
963                         /* unknown; opt is "!" or path component,
964                          * checking done above.
965                          */
966                         if (strcmp(optarg, "!") == 0)
967                                 neg_opt = 2;
968                         break;
969                 case 'A':
970                         xtime = &param.fp_atime;
971                         xsign = &param.fp_asign;
972                         param.fp_exclude_atime = !!neg_opt;
973                         /* no break, this falls through to 'C' for ctime */
974                 case 'C':
975                         if (c == 'C') {
976                                 xtime = &param.fp_ctime;
977                                 xsign = &param.fp_csign;
978                                 param.fp_exclude_ctime = !!neg_opt;
979                         }
980                         /* no break, this falls through to 'M' for mtime */
981                 case 'M':
982                         if (c == 'M') {
983                                 xtime = &param.fp_mtime;
984                                 xsign = &param.fp_msign;
985                                 param.fp_exclude_mtime = !!neg_opt;
986                         }
987                         ret = set_time(&t, xtime, optarg);
988                         if (ret == INT_MAX) {
989                                 ret = -1;
990                                 goto err;
991                         }
992                         if (ret)
993                                 *xsign = ret;
994                         break;
995                 case 'c':
996                         if (optarg[0] == '+') {
997                                 param.stripecount_sign = -1;
998                                 optarg++;
999                         } else if (optarg[0] == '-') {
1000                                 param.stripecount_sign =  1;
1001                                 optarg++;
1002                         }
1003
1004                         param.stripecount = strtoul(optarg, &endptr, 0);
1005                         if (*endptr != '\0') {
1006                                 fprintf(stderr,"error: bad stripe_count '%s'\n",
1007                                         optarg);
1008                                 ret = -1;
1009                                 goto err;
1010                         }
1011                         param.check_stripecount = 1;
1012                         param.exclude_stripecount = !!neg_opt;
1013                         break;
1014                 case 'D':
1015                         param.fp_max_depth = strtol(optarg, 0, 0);
1016                         break;
1017                 case 'g':
1018                 case 'G':
1019                         ret = name2id(&param.fp_gid, optarg, GROUP);
1020                         if (ret) {
1021                                 param.fp_gid = strtoul(optarg, &endptr, 10);
1022                                 if (*endptr != '\0') {
1023                                         fprintf(stderr, "Group/GID: %s cannot "
1024                                                 "be found.\n", optarg);
1025                                         ret = -1;
1026                                         goto err;
1027                                 }
1028                         }
1029                         param.fp_exclude_gid = !!neg_opt;
1030                         param.fp_check_gid = 1;
1031                         break;
1032                 case 'L':
1033                         ret = name2layout(&param.layout, optarg);
1034                         if (ret)
1035                                 goto err;
1036                         param.exclude_layout = !!neg_opt;
1037                         param.check_layout = 1;
1038                         break;
1039                 case 'u':
1040                 case 'U':
1041                         ret = name2id(&param.fp_uid, optarg, USER);
1042                         if (ret) {
1043                                 param.fp_uid = strtoul(optarg, &endptr, 10);
1044                                 if (*endptr != '\0') {
1045                                         fprintf(stderr, "User/UID: %s cannot "
1046                                                 "be found.\n", optarg);
1047                                         ret = -1;
1048                                         goto err;
1049                                 }
1050                         }
1051                         param.fp_exclude_uid = !!neg_opt;
1052                         param.fp_check_uid = 1;
1053                         break;
1054                 case FIND_POOL_OPT:
1055                         if (strlen(optarg) > LOV_MAXPOOLNAME) {
1056                                 fprintf(stderr,
1057                                         "Pool name %s is too long"
1058                                         " (max is %d)\n", optarg,
1059                                         LOV_MAXPOOLNAME);
1060                                 ret = -1;
1061                                 goto err;
1062                         }
1063                         /* we do check for empty pool because empty pool
1064                          * is used to find V1 lov attributes */
1065                         strncpy(param.poolname, optarg, LOV_MAXPOOLNAME);
1066                         param.poolname[LOV_MAXPOOLNAME] = '\0';
1067                         param.exclude_pool = !!neg_opt;
1068                         param.check_pool = 1;
1069                         break;
1070                 case 'n':
1071                         param.pattern = (char *)optarg;
1072                         param.exclude_pattern = !!neg_opt;
1073                         break;
1074                 case 'm':
1075                 case 'i':
1076                 case 'O': {
1077                         char *buf, *token, *next, *p;
1078                         int len = 1;
1079                         void *tmp;
1080
1081                         buf = strdup(optarg);
1082                         if (buf == NULL) {
1083                                 ret = -ENOMEM;
1084                                 goto err;
1085                         }
1086
1087                         param.exclude_obd = !!neg_opt;
1088
1089                         token = buf;
1090                         while (token && *token) {
1091                                 token = strchr(token, ',');
1092                                 if (token) {
1093                                         len++;
1094                                         token++;
1095                                 }
1096                         }
1097                         if (c == 'm') {
1098                                 param.exclude_mdt = !!neg_opt;
1099                                 param.num_alloc_mdts += len;
1100                                 tmp = realloc(param.mdtuuid,
1101                                               param.num_alloc_mdts *
1102                                               sizeof(*param.mdtuuid));
1103                                 if (tmp == NULL)
1104                                         GOTO(err_free, ret = -ENOMEM);
1105                                 param.mdtuuid = tmp;
1106                         } else {
1107                                 param.exclude_obd = !!neg_opt;
1108                                 param.num_alloc_obds += len;
1109                                 tmp = realloc(param.obduuid,
1110                                               param.num_alloc_obds *
1111                                               sizeof(*param.obduuid));
1112                                 if (tmp == NULL)
1113                                         GOTO(err_free, ret = -ENOMEM);
1114                                 param.obduuid = tmp;
1115                         }
1116                         for (token = buf; token && *token; token = next) {
1117                                 struct obd_uuid *puuid;
1118                                 if (c == 'm') {
1119                                         puuid =
1120                                           &param.mdtuuid[param.num_mdts++];
1121                                 } else {
1122                                         puuid =
1123                                           &param.obduuid[param.num_obds++];
1124                                 }
1125                                 p = strchr(token, ',');
1126                                 next = 0;
1127                                 if (p) {
1128                                         *p = 0;
1129                                         next = p+1;
1130                                 }
1131                                 if (strlen(token) > sizeof(puuid->uuid)-1)
1132                                         GOTO(err_free, ret = -E2BIG);
1133                                 strncpy(puuid->uuid, token,
1134                                         sizeof(puuid->uuid));
1135                         }
1136 err_free:
1137                         if (buf)
1138                                 free(buf);
1139                         break;
1140                 }
1141                 case 'p':
1142                         param.zeroend = 1;
1143                         break;
1144                 case 'P':
1145                         break;
1146                 case 's':
1147                         if (optarg[0] == '+') {
1148                                 param.size_sign = -1;
1149                                 optarg++;
1150                         } else if (optarg[0] == '-') {
1151                                 param.size_sign =  1;
1152                                 optarg++;
1153                         }
1154
1155                         ret = llapi_parse_size(optarg, &param.size,
1156                                                &param.size_units, 0);
1157                         if (ret) {
1158                                 fprintf(stderr, "error: bad file size '%s'\n",
1159                                         optarg);
1160                                 goto err;
1161                         }
1162                         param.check_size = 1;
1163                         param.exclude_size = !!neg_opt;
1164                         break;
1165                 case 'S':
1166                         if (optarg[0] == '+') {
1167                                 param.stripesize_sign = -1;
1168                                 optarg++;
1169                         } else if (optarg[0] == '-') {
1170                                 param.stripesize_sign =  1;
1171                                 optarg++;
1172                         }
1173
1174                         ret = llapi_parse_size(optarg, &param.stripesize,
1175                                                &param.stripesize_units, 0);
1176                         if (ret) {
1177                                 fprintf(stderr, "error: bad stripe_size '%s'\n",
1178                                         optarg);
1179                                 goto err;
1180                         }
1181                         param.check_stripesize = 1;
1182                         param.exclude_stripesize = !!neg_opt;
1183                         break;
1184                 case 't':
1185                         param.fp_exclude_type = !!neg_opt;
1186                         switch (optarg[0]) {
1187                         case 'b':
1188                                 param.fp_type = S_IFBLK;
1189                                 break;
1190                         case 'c':
1191                                 param.fp_type = S_IFCHR;
1192                                 break;
1193                         case 'd':
1194                                 param.fp_type = S_IFDIR;
1195                                 break;
1196                         case 'f':
1197                                 param.fp_type = S_IFREG;
1198                                 break;
1199                         case 'l':
1200                                 param.fp_type = S_IFLNK;
1201                                 break;
1202                         case 'p':
1203                                 param.fp_type = S_IFIFO;
1204                                 break;
1205                         case 's':
1206                                 param.fp_type = S_IFSOCK;
1207                                 break;
1208                         default:
1209                                 fprintf(stderr, "error: %s: bad type '%s'\n",
1210                                         argv[0], optarg);
1211                                 ret = CMD_HELP;
1212                                 goto err;
1213                         };
1214                         break;
1215                 default:
1216                         ret = CMD_HELP;
1217                         goto err;
1218                 };
1219         }
1220
1221         if (pathstart == -1) {
1222                 fprintf(stderr, "error: %s: no filename|pathname\n",
1223                         argv[0]);
1224                 ret = CMD_HELP;
1225                 goto err;
1226         } else if (pathend == -1) {
1227                 /* no options */
1228                 pathend = argc;
1229         }
1230
1231         do {
1232                 ret = llapi_find(argv[pathstart], &param);
1233         } while (++pathstart < pathend && !ret);
1234
1235         if (ret)
1236                 fprintf(stderr, "error: %s failed for %s.\n",
1237                         argv[0], argv[optind - 1]);
1238 err:
1239         if (param.obduuid && param.num_alloc_obds)
1240                 free(param.obduuid);
1241
1242         if (param.mdtuuid && param.num_alloc_mdts)
1243                 free(param.mdtuuid);
1244
1245         return ret;
1246 }
1247
1248 static int lfs_getstripe_internal(int argc, char **argv,
1249                                   struct find_param *param)
1250 {
1251         struct option long_opts[] = {
1252 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1253                 /* This formerly implied "stripe-count", but was explicitly
1254                  * made "stripe-count" for consistency with other options,
1255                  * and to separate it from "mdt-count" when DNE arrives. */
1256                 {"count",               no_argument,            0, 'c'},
1257 #endif
1258                 {"stripe-count",        no_argument,            0, 'c'},
1259                 {"stripe_count",        no_argument,            0, 'c'},
1260                 {"directory",           no_argument,            0, 'd'},
1261                 {"default",             no_argument,            0, 'D'},
1262                 {"generation",          no_argument,            0, 'g'},
1263 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1264                 /* This formerly implied "stripe-index", but was explicitly
1265                  * made "stripe-index" for consistency with other options,
1266                  * and to separate it from "mdt-index" when DNE arrives. */
1267                 {"index",               no_argument,            0, 'i'},
1268 #endif
1269                 {"stripe-index",        no_argument,            0, 'i'},
1270                 {"stripe_index",        no_argument,            0, 'i'},
1271                 {"layout",              no_argument,            0, 'L'},
1272                 {"mdt-index",           no_argument,            0, 'M'},
1273                 {"mdt_index",           no_argument,            0, 'M'},
1274 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1275                 /* This formerly implied "stripe-index", but was confusing
1276                  * with "file offset" (which will eventually be needed for
1277                  * with different layouts by offset), so deprecate it. */
1278                 {"offset",              no_argument,            0, 'o'},
1279 #endif
1280                 {"obd",                 required_argument,      0, 'O'},
1281                 {"ost",                 required_argument,      0, 'O'},
1282                 {"pool",                no_argument,            0, 'p'},
1283                 {"quiet",               no_argument,            0, 'q'},
1284                 {"recursive",           no_argument,            0, 'r'},
1285                 {"raw",                 no_argument,            0, 'R'},
1286 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1287                 /* This formerly implied "--stripe-size", but was confusing
1288                  * with "lfs find --size|-s", which means "file size", so use
1289                  * the consistent "--stripe-size|-S" for all commands. */
1290                 {"size",                no_argument,            0, 's'},
1291 #endif
1292                 {"stripe-size",         no_argument,            0, 'S'},
1293                 {"stripe_size",         no_argument,            0, 'S'},
1294                 {"verbose",             no_argument,            0, 'v'},
1295                 {0, 0, 0, 0}
1296         };
1297         int c, rc;
1298
1299         param->fp_max_depth = 1;
1300         optind = 0;
1301         while ((c = getopt_long(argc, argv, "cdDghiLMoO:pqrRsSv",
1302                                 long_opts, NULL)) != -1) {
1303                 switch (c) {
1304                 case 'O':
1305                         if (param->obduuid) {
1306                                 fprintf(stderr,
1307                                         "error: %s: only one obduuid allowed",
1308                                         argv[0]);
1309                                 return CMD_HELP;
1310                         }
1311                         param->obduuid = (struct obd_uuid *)optarg;
1312                         break;
1313                 case 'q':
1314                         param->quiet++;
1315                         break;
1316                 case 'd':
1317                         param->fp_max_depth = 0;
1318                         break;
1319                 case 'D':
1320                         param->get_default_lmv = 1;
1321                         break;
1322                 case 'r':
1323                         param->recursive = 1;
1324                         break;
1325                 case 'v':
1326                         param->verbose = VERBOSE_ALL | VERBOSE_DETAIL;
1327                         break;
1328                 case 'c':
1329 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 6, 53, 0)
1330                         if (strcmp(argv[optind - 1], "--count") == 0)
1331                                 fprintf(stderr, "warning: '--count' deprecated,"
1332                                         " use '--stripe-count' instead\n");
1333 #endif
1334                         if (!(param->verbose & VERBOSE_DETAIL)) {
1335                                 param->verbose |= VERBOSE_COUNT;
1336                                 param->fp_max_depth = 0;
1337                         }
1338                         break;
1339 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1340                 case 's':
1341 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 6, 53, 0)
1342                         fprintf(stderr, "warning: '--size|-s' deprecated, "
1343                                 "use '--stripe-size|-S' instead\n");
1344 #endif
1345 #endif /* LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0) */
1346                 case 'S':
1347                         if (!(param->verbose & VERBOSE_DETAIL)) {
1348                                 param->verbose |= VERBOSE_SIZE;
1349                                 param->fp_max_depth = 0;
1350                         }
1351                         break;
1352 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1353                 case 'o':
1354                         fprintf(stderr, "warning: '--offset|-o' deprecated, "
1355                                 "use '--stripe-index|-i' instead\n");
1356 #endif
1357                 case 'i':
1358 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 6, 53, 0)
1359                         if (strcmp(argv[optind - 1], "--index") == 0)
1360                                 fprintf(stderr, "warning: '--index' deprecated"
1361                                         ", use '--stripe-index' instead\n");
1362 #endif
1363                         if (!(param->verbose & VERBOSE_DETAIL)) {
1364                                 param->verbose |= VERBOSE_OFFSET;
1365                                 param->fp_max_depth = 0;
1366                         }
1367                         break;
1368                 case 'p':
1369                         if (!(param->verbose & VERBOSE_DETAIL)) {
1370                                 param->verbose |= VERBOSE_POOL;
1371                                 param->fp_max_depth = 0;
1372                         }
1373                         break;
1374                 case 'g':
1375                         if (!(param->verbose & VERBOSE_DETAIL)) {
1376                                 param->verbose |= VERBOSE_GENERATION;
1377                                 param->fp_max_depth = 0;
1378                         }
1379                         break;
1380                 case 'L':
1381                         if (!(param->verbose & VERBOSE_DETAIL)) {
1382                                 param->verbose |= VERBOSE_LAYOUT;
1383                                 param->fp_max_depth = 0;
1384                         }
1385                         break;
1386                 case 'M':
1387                         if (!(param->verbose & VERBOSE_DETAIL))
1388                                 param->fp_max_depth = 0;
1389                         param->verbose |= VERBOSE_MDTINDEX;
1390                         break;
1391                 case 'R':
1392                         param->raw = 1;
1393                         break;
1394                 default:
1395                         return CMD_HELP;
1396                 }
1397         }
1398
1399         if (optind >= argc)
1400                 return CMD_HELP;
1401
1402         if (param->recursive)
1403                 param->fp_max_depth = -1;
1404
1405         if (!param->verbose)
1406                 param->verbose = VERBOSE_ALL;
1407         if (param->quiet)
1408                 param->verbose = VERBOSE_OBJID;
1409
1410         do {
1411                 rc = llapi_getstripe(argv[optind], param);
1412         } while (++optind < argc && !rc);
1413
1414         if (rc)
1415                 fprintf(stderr, "error: %s failed for %s.\n",
1416                         argv[0], argv[optind - 1]);
1417         return rc;
1418 }
1419
1420 static int lfs_tgts(int argc, char **argv)
1421 {
1422         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
1423         struct find_param param;
1424         int index = 0, rc=0;
1425
1426         if (argc > 2)
1427                 return CMD_HELP;
1428
1429         if (argc == 2 && !realpath(argv[1], path)) {
1430                 rc = -errno;
1431                 fprintf(stderr, "error: invalid path '%s': %s\n",
1432                         argv[1], strerror(-rc));
1433                 return rc;
1434         }
1435
1436         while (!llapi_search_mounts(path, index++, mntdir, NULL)) {
1437                 /* Check if we have a mount point */
1438                 if (mntdir[0] == '\0')
1439                         continue;
1440
1441                 memset(&param, 0, sizeof(param));
1442                 if (!strcmp(argv[0], "mdts"))
1443                         param.get_lmv = 1;
1444
1445                 rc = llapi_ostlist(mntdir, &param);
1446                 if (rc) {
1447                         fprintf(stderr, "error: %s: failed on %s\n",
1448                                 argv[0], mntdir);
1449                 }
1450                 if (path[0] != '\0')
1451                         break;
1452                 memset(mntdir, 0, PATH_MAX);
1453         }
1454
1455         return rc;
1456 }
1457
1458 static int lfs_getstripe(int argc, char **argv)
1459 {
1460         struct find_param param = { 0 };
1461         return lfs_getstripe_internal(argc, argv, &param);
1462 }
1463
1464 /* functions */
1465 static int lfs_getdirstripe(int argc, char **argv)
1466 {
1467         struct find_param param = { 0 };
1468
1469         param.get_lmv = 1;
1470         return lfs_getstripe_internal(argc, argv, &param);
1471 }
1472
1473 /* functions */
1474 static int lfs_setdirstripe(int argc, char **argv)
1475 {
1476         char                    *dname;
1477         int                     result;
1478         unsigned int            stripe_offset = -1;
1479         unsigned int            stripe_count = 1;
1480         enum lmv_hash_type      hash_type;
1481         char                    *end;
1482         int                     c;
1483         char                    *stripe_offset_opt = NULL;
1484         char                    *stripe_count_opt = NULL;
1485         char                    *stripe_hash_opt = NULL;
1486         char                    *mode_opt = NULL;
1487         int                     default_stripe = 0;
1488         mode_t                  mode = S_IRWXU | S_IRWXG | S_IRWXO;
1489         mode_t                  previous_mode = 0;
1490
1491         struct option long_opts[] = {
1492                 {"count",       required_argument, 0, 'c'},
1493                 {"index",       required_argument, 0, 'i'},
1494                 {"mode",        required_argument, 0, 'm'},
1495                 {"hash-type",   required_argument, 0, 't'},
1496                 {"default_stripe", no_argument, 0, 'D'},
1497                 {0, 0, 0, 0}
1498         };
1499
1500         optind = 0;
1501
1502         while ((c = getopt_long(argc, argv, "c:Di:m:t:", long_opts,
1503                                 NULL)) >= 0) {
1504                 switch (c) {
1505                 case 0:
1506                         /* Long options. */
1507                         break;
1508                 case 'c':
1509                         stripe_count_opt = optarg;
1510                         break;
1511                 case 'D':
1512                         default_stripe = 1;
1513                         break;
1514                 case 'i':
1515                         stripe_offset_opt = optarg;
1516                         break;
1517                 case 'm':
1518                         mode_opt = optarg;
1519                         break;
1520                 case 't':
1521                         stripe_hash_opt = optarg;
1522                         break;
1523                 default:
1524                         fprintf(stderr, "error: %s: option '%s' "
1525                                         "unrecognized\n",
1526                                         argv[0], argv[optind - 1]);
1527                         return CMD_HELP;
1528                 }
1529         }
1530
1531         if (optind == argc) {
1532                 fprintf(stderr, "error: %s: missing dirname\n",
1533                         argv[0]);
1534                 return CMD_HELP;
1535         }
1536
1537         if (stripe_offset_opt == NULL && stripe_count_opt == NULL) {
1538                 fprintf(stderr, "error: %s: missing stripe offset and count.\n",
1539                         argv[0]);
1540                 return CMD_HELP;
1541         }
1542
1543         if (stripe_offset_opt != NULL) {
1544                 /* get the stripe offset */
1545                 stripe_offset = strtoul(stripe_offset_opt, &end, 0);
1546                 if (*end != '\0') {
1547                         fprintf(stderr, "error: %s: bad stripe offset '%s'\n",
1548                                 argv[0], stripe_offset_opt);
1549                         return CMD_HELP;
1550                 }
1551         }
1552
1553         if (mode_opt != NULL) {
1554                 mode = strtoul(mode_opt, &end, 8);
1555                 if (*end != '\0') {
1556                         fprintf(stderr, "error: %s: bad mode '%s'\n",
1557                                 argv[0], mode_opt);
1558                         return CMD_HELP;
1559                 }
1560                 previous_mode = umask(0);
1561         }
1562
1563         if (stripe_hash_opt == NULL ||
1564             strcmp(stripe_hash_opt, LMV_HASH_NAME_FNV_1A_64) == 0) {
1565                 hash_type = LMV_HASH_TYPE_FNV_1A_64;
1566         } else if (strcmp(stripe_hash_opt, LMV_HASH_NAME_ALL_CHARS) == 0) {
1567                 hash_type = LMV_HASH_TYPE_ALL_CHARS;
1568         } else {
1569                 fprintf(stderr, "error: %s: bad stripe hash type '%s'\n",
1570                         argv[0], stripe_hash_opt);
1571                 return CMD_HELP;
1572         }
1573
1574         /* get the stripe count */
1575         if (stripe_count_opt != NULL) {
1576                 stripe_count = strtoul(stripe_count_opt, &end, 0);
1577                 if (*end != '\0') {
1578                         fprintf(stderr, "error: %s: bad stripe count '%s'\n",
1579                                 argv[0], stripe_count_opt);
1580                         return CMD_HELP;
1581                 }
1582         }
1583
1584         dname = argv[optind];
1585         do {
1586                 if (default_stripe == 1) {
1587                         result = llapi_dir_set_default_lmv_stripe(dname,
1588                                                     stripe_offset, stripe_count,
1589                                                     hash_type, NULL);
1590                 } else {
1591                         result = llapi_dir_create_pool(dname, mode,
1592                                                        stripe_offset,
1593                                                        stripe_count, hash_type,
1594                                                        NULL);
1595                 }
1596
1597                 if (result) {
1598                         fprintf(stderr, "error: %s: create stripe dir '%s' "
1599                                 "failed\n", argv[0], dname);
1600                         break;
1601                 }
1602                 dname = argv[++optind];
1603         } while (dname != NULL);
1604
1605         if (mode_opt != NULL)
1606                 umask(previous_mode);
1607
1608         return result;
1609 }
1610
1611 /* functions */
1612 static int lfs_rmentry(int argc, char **argv)
1613 {
1614         char *dname;
1615         int   index;
1616         int   result = 0;
1617
1618         if (argc <= 1) {
1619                 fprintf(stderr, "error: %s: missing dirname\n",
1620                         argv[0]);
1621                 return CMD_HELP;
1622         }
1623
1624         index = 1;
1625         dname = argv[index];
1626         while (dname != NULL) {
1627                 result = llapi_direntry_remove(dname);
1628                 if (result) {
1629                         fprintf(stderr, "error: %s: remove dir entry '%s' "
1630                                 "failed\n", argv[0], dname);
1631                         break;
1632                 }
1633                 dname = argv[++index];
1634         }
1635         return result;
1636 }
1637
1638 static int lfs_mv(int argc, char **argv)
1639 {
1640         struct  find_param param = {
1641                 .fp_max_depth = -1,
1642                 .mdtindex = -1,
1643         };
1644         char   *end;
1645         int     c;
1646         int     rc = 0;
1647         struct option long_opts[] = {
1648                 {"--mdt-index", required_argument, 0, 'M'},
1649                 {"verbose",     no_argument,       0, 'v'},
1650                 {0, 0, 0, 0}
1651         };
1652
1653         while ((c = getopt_long(argc, argv, "M:v", long_opts, NULL)) != -1) {
1654                 switch (c) {
1655                 case 'M': {
1656                         param.mdtindex = strtoul(optarg, &end, 0);
1657                         if (*end != '\0') {
1658                                 fprintf(stderr, "%s: invalid MDT index'%s'\n",
1659                                         argv[0], optarg);
1660                                 return CMD_HELP;
1661                         }
1662                         break;
1663                 }
1664                 case 'v': {
1665                         param.verbose = VERBOSE_DETAIL;
1666                         break;
1667                 }
1668                 default:
1669                         fprintf(stderr, "error: %s: unrecognized option '%s'\n",
1670                                 argv[0], argv[optind - 1]);
1671                         return CMD_HELP;
1672                 }
1673         }
1674
1675         if (param.mdtindex == -1) {
1676                 fprintf(stderr, "%s MDT index must be indicated\n", argv[0]);
1677                 return CMD_HELP;
1678         }
1679
1680         if (optind >= argc) {
1681                 fprintf(stderr, "%s missing operand path\n", argv[0]);
1682                 return CMD_HELP;
1683         }
1684
1685         param.migrate = 1;
1686         rc = llapi_mv(argv[optind], &param);
1687         if (rc != 0)
1688                 fprintf(stderr, "cannot migrate '%s' to MDT%04x: %s\n",
1689                         argv[optind], param.mdtindex, strerror(-rc));
1690         return rc;
1691 }
1692
1693 static int lfs_osts(int argc, char **argv)
1694 {
1695         return lfs_tgts(argc, argv);
1696 }
1697
1698 static int lfs_mdts(int argc, char **argv)
1699 {
1700         return lfs_tgts(argc, argv);
1701 }
1702
1703 #define COOK(value)                                                     \
1704 ({                                                                      \
1705         int radix = 0;                                                  \
1706         while (value > 1024) {                                          \
1707                 value /= 1024;                                          \
1708                 radix++;                                                \
1709         }                                                               \
1710         radix;                                                          \
1711 })
1712 #define UUF     "%-20s"
1713 #define CSF     "%11s"
1714 #define CDF     "%11llu"
1715 #define HDF     "%8.1f%c"
1716 #define RSF     "%4s"
1717 #define RDF     "%3d%%"
1718
1719 static int showdf(char *mntdir, struct obd_statfs *stat,
1720                   char *uuid, int ishow, int cooked,
1721                   char *type, int index, int rc)
1722 {
1723         long long avail, used, total;
1724         double ratio = 0;
1725         char *suffix = "KMGTPEZY";
1726         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
1727         char tbuf[20], ubuf[20], abuf[20], rbuf[20];
1728
1729         if (!uuid || !stat)
1730                 return -EINVAL;
1731
1732         switch (rc) {
1733         case 0:
1734                 if (ishow) {
1735                         avail = stat->os_ffree;
1736                         used = stat->os_files - stat->os_ffree;
1737                         total = stat->os_files;
1738                 } else {
1739                         int shift = cooked ? 0 : 10;
1740
1741                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
1742                         used  = ((stat->os_blocks - stat->os_bfree) *
1743                                  stat->os_bsize) >> shift;
1744                         total = (stat->os_blocks * stat->os_bsize) >> shift;
1745                 }
1746
1747                 if ((used + avail) > 0)
1748                         ratio = (double)used / (double)(used + avail);
1749
1750                 if (cooked) {
1751                         int i;
1752                         double cook_val;
1753
1754                         cook_val = (double)total;
1755                         i = COOK(cook_val);
1756                         if (i > 0)
1757                                 sprintf(tbuf, HDF, cook_val, suffix[i - 1]);
1758                         else
1759                                 sprintf(tbuf, CDF, total);
1760
1761                         cook_val = (double)used;
1762                         i = COOK(cook_val);
1763                         if (i > 0)
1764                                 sprintf(ubuf, HDF, cook_val, suffix[i - 1]);
1765                         else
1766                                 sprintf(ubuf, CDF, used);
1767
1768                         cook_val = (double)avail;
1769                         i = COOK(cook_val);
1770                         if (i > 0)
1771                                 sprintf(abuf, HDF, cook_val, suffix[i - 1]);
1772                         else
1773                                 sprintf(abuf, CDF, avail);
1774                 } else {
1775                         sprintf(tbuf, CDF, total);
1776                         sprintf(ubuf, CDF, used);
1777                         sprintf(abuf, CDF, avail);
1778                 }
1779
1780                 sprintf(rbuf, RDF, (int)(ratio * 100 + 0.5));
1781                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
1782                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
1783                 if (type)
1784                         printf("[%s:%d]\n", type, index);
1785                 else
1786                         printf("\n");
1787
1788                 break;
1789         case -ENODATA:
1790                 printf(UUF": inactive device\n", uuid);
1791                 break;
1792         default:
1793                 printf(UUF": %s\n", uuid, strerror(-rc));
1794                 break;
1795         }
1796
1797         return 0;
1798 }
1799
1800 struct ll_stat_type {
1801         int   st_op;
1802         char *st_name;
1803 };
1804
1805 static int mntdf(char *mntdir, char *fsname, char *pool, int ishow,
1806                 int cooked, int lazy)
1807 {
1808         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
1809         struct obd_uuid uuid_buf;
1810         char *poolname = NULL;
1811         struct ll_stat_type types[] = { { LL_STATFS_LMV, "MDT" },
1812                                         { LL_STATFS_LOV, "OST" },
1813                                         { 0, NULL } };
1814         struct ll_stat_type *tp;
1815         __u64 ost_ffree = 0;
1816         __u32 index;
1817         __u32 type;
1818         int rc;
1819
1820         if (pool) {
1821                 poolname = strchr(pool, '.');
1822                 if (poolname != NULL) {
1823                         if (strncmp(fsname, pool, strlen(fsname))) {
1824                                 fprintf(stderr, "filesystem name incorrect\n");
1825                                 return -ENODEV;
1826                         }
1827                         poolname++;
1828                 } else
1829                         poolname = pool;
1830         }
1831
1832         if (ishow)
1833                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
1834                        "UUID", "Inodes", "IUsed", "IFree",
1835                        "IUse%", "Mounted on");
1836         else
1837                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
1838                        "UUID", cooked ? "bytes" : "1K-blocks",
1839                        "Used", "Available", "Use%", "Mounted on");
1840
1841         for (tp = types; tp->st_name != NULL; tp++) {
1842                 for (index = 0; ; index++) {
1843                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
1844                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
1845                         type = lazy ? tp->st_op | LL_STATFS_NODELAY : tp->st_op;
1846                         rc = llapi_obd_statfs(mntdir, type, index,
1847                                               &stat_buf, &uuid_buf);
1848                         if (rc == -ENODEV)
1849                                 break;
1850
1851                         if (poolname && tp->st_op == LL_STATFS_LOV &&
1852                             llapi_search_ost(fsname, poolname,
1853                                              obd_uuid2str(&uuid_buf)) != 1)
1854                                 continue;
1855
1856                         /* the llapi_obd_statfs() call may have returned with
1857                          * an error, but if it filled in uuid_buf we will at
1858                          * lease use that to print out a message for that OBD.
1859                          * If we didn't get anything in the uuid_buf, then fill
1860                          * it in so that we can print an error message. */
1861                         if (uuid_buf.uuid[0] == '\0')
1862                                 sprintf(uuid_buf.uuid, "%s%04x",
1863                                         tp->st_name, index);
1864                         showdf(mntdir, &stat_buf, obd_uuid2str(&uuid_buf),
1865                                ishow, cooked, tp->st_name, index, rc);
1866
1867                         if (rc == 0) {
1868                                 if (tp->st_op == LL_STATFS_LMV) {
1869                                         sum.os_ffree += stat_buf.os_ffree;
1870                                         sum.os_files += stat_buf.os_files;
1871                                 } else /* if (tp->st_op == LL_STATFS_LOV) */ {
1872                                         sum.os_blocks += stat_buf.os_blocks *
1873                                                 stat_buf.os_bsize;
1874                                         sum.os_bfree  += stat_buf.os_bfree *
1875                                                 stat_buf.os_bsize;
1876                                         sum.os_bavail += stat_buf.os_bavail *
1877                                                 stat_buf.os_bsize;
1878                                         ost_ffree += stat_buf.os_ffree;
1879                                 }
1880                         } else if (rc == -EINVAL || rc == -EFAULT) {
1881                                 break;
1882                         }
1883                 }
1884         }
1885
1886         /* If we don't have as many objects free on the OST as inodes
1887          * on the MDS, we reduce the total number of inodes to
1888          * compensate, so that the "inodes in use" number is correct.
1889          * Matches ll_statfs_internal() so the results are consistent. */
1890         if (ost_ffree < sum.os_ffree) {
1891                 sum.os_files = (sum.os_files - sum.os_ffree) + ost_ffree;
1892                 sum.os_ffree = ost_ffree;
1893         }
1894         printf("\n");
1895         showdf(mntdir, &sum, "filesystem summary:", ishow, cooked, NULL, 0, 0);
1896         printf("\n");
1897         return 0;
1898 }
1899
1900 static int lfs_df(int argc, char **argv)
1901 {
1902         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
1903         int ishow = 0, cooked = 0;
1904         int lazy = 0;
1905         int c, rc = 0, index = 0;
1906         char fsname[PATH_MAX] = "", *pool_name = NULL;
1907         struct option long_opts[] = {
1908                 {"pool", required_argument, 0, 'p'},
1909                 {"lazy", 0, 0, 'l'},
1910                 {0, 0, 0, 0}
1911         };
1912
1913         optind = 0;
1914         while ((c = getopt_long(argc, argv, "hilp:", long_opts, NULL)) != -1) {
1915                 switch (c) {
1916                 case 'i':
1917                         ishow = 1;
1918                         break;
1919                 case 'h':
1920                         cooked = 1;
1921                         break;
1922                 case 'l':
1923                         lazy = 1;
1924                         break;
1925                 case 'p':
1926                         pool_name = optarg;
1927                         break;
1928                 default:
1929                         return CMD_HELP;
1930                 }
1931         }
1932         if (optind < argc && !realpath(argv[optind], path)) {
1933                 rc = -errno;
1934                 fprintf(stderr, "error: invalid path '%s': %s\n",
1935                         argv[optind], strerror(-rc));
1936                 return rc;
1937         }
1938
1939         while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
1940                 /* Check if we have a mount point */
1941                 if (mntdir[0] == '\0')
1942                         continue;
1943
1944                 rc = mntdf(mntdir, fsname, pool_name, ishow, cooked, lazy);
1945                 if (rc || path[0] != '\0')
1946                         break;
1947                 fsname[0] = '\0'; /* avoid matching in next loop */
1948                 mntdir[0] = '\0'; /* avoid matching in next loop */
1949         }
1950
1951         return rc;
1952 }
1953
1954 static int lfs_getname(int argc, char **argv)
1955 {
1956         char mntdir[PATH_MAX] = "", path[PATH_MAX] = "", fsname[PATH_MAX] = "";
1957         int rc = 0, index = 0, c;
1958         char buf[sizeof(struct obd_uuid)];
1959
1960         optind = 0;
1961         while ((c = getopt(argc, argv, "h")) != -1)
1962                 return CMD_HELP;
1963
1964         if (optind == argc) { /* no paths specified, get all paths. */
1965                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
1966                         rc = llapi_getname(mntdir, buf, sizeof(buf));
1967                         if (rc < 0) {
1968                                 fprintf(stderr,
1969                                         "cannot get name for `%s': %s\n",
1970                                         mntdir, strerror(-rc));
1971                                 break;
1972                         }
1973
1974                         printf("%s %s\n", buf, mntdir);
1975
1976                         path[0] = fsname[0] = mntdir[0] = 0;
1977                 }
1978         } else { /* paths specified, only attempt to search these. */
1979                 for (; optind < argc; optind++) {
1980                         rc = llapi_getname(argv[optind], buf, sizeof(buf));
1981                         if (rc < 0) {
1982                                 fprintf(stderr,
1983                                         "cannot get name for `%s': %s\n",
1984                                         argv[optind], strerror(-rc));
1985                                 break;
1986                         }
1987
1988                         printf("%s %s\n", buf, argv[optind]);
1989                 }
1990         }
1991         return rc;
1992 }
1993
1994 static int lfs_check(int argc, char **argv)
1995 {
1996         int rc;
1997         char mntdir[PATH_MAX] = {'\0'};
1998         int num_types = 1;
1999         char *obd_types[2];
2000         char obd_type1[4];
2001         char obd_type2[4];
2002
2003         if (argc != 2)
2004                 return CMD_HELP;
2005
2006         obd_types[0] = obd_type1;
2007         obd_types[1] = obd_type2;
2008
2009         if (strcmp(argv[1], "osts") == 0) {
2010                 strcpy(obd_types[0], "osc");
2011         } else if (strcmp(argv[1], "mds") == 0) {
2012                 strcpy(obd_types[0], "mdc");
2013         } else if (strcmp(argv[1], "servers") == 0) {
2014                 num_types = 2;
2015                 strcpy(obd_types[0], "osc");
2016                 strcpy(obd_types[1], "mdc");
2017         } else {
2018                 fprintf(stderr, "error: %s: option '%s' unrecognized\n",
2019                                 argv[0], argv[1]);
2020                         return CMD_HELP;
2021         }
2022
2023         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
2024         if (rc < 0 || mntdir[0] == '\0') {
2025                 fprintf(stderr, "No suitable Lustre mount found\n");
2026                 return rc;
2027         }
2028
2029         rc = llapi_target_iterate(num_types, obd_types,
2030                                   mntdir, llapi_ping_target);
2031
2032         if (rc)
2033                 fprintf(stderr, "error: %s: %s status failed\n",
2034                                 argv[0],argv[1]);
2035
2036         return rc;
2037
2038 }
2039
2040 static int lfs_join(int argc, char **argv)
2041 {
2042         fprintf(stderr, "join two lustre files into one.\n"
2043                         "obsolete, HEAD does not support it anymore.\n");
2044         return 0;
2045 }
2046
2047 #ifdef HAVE_SYS_QUOTA_H
2048 static int lfs_quotacheck(int argc, char **argv)
2049 {
2050         int c, check_type = 0;
2051         char *mnt;
2052         struct if_quotacheck qchk;
2053         struct if_quotactl qctl;
2054         char *obd_type = (char *)qchk.obd_type;
2055         int rc;
2056
2057         memset(&qchk, 0, sizeof(qchk));
2058
2059         optind = 0;
2060         while ((c = getopt(argc, argv, "gu")) != -1) {
2061                 switch (c) {
2062                 case 'u':
2063                         check_type |= 0x01;
2064                         break;
2065                 case 'g':
2066                         check_type |= 0x02;
2067                         break;
2068                 default:
2069                         fprintf(stderr, "error: %s: option '-%c' "
2070                                         "unrecognized\n", argv[0], c);
2071                         return CMD_HELP;
2072                 }
2073         }
2074
2075         if (check_type)
2076                 check_type--;
2077         else    /* do quotacheck for both user & group quota by default */
2078                 check_type = 0x02;
2079
2080         if (argc == optind)
2081                 return CMD_HELP;
2082
2083         mnt = argv[optind];
2084
2085         rc = llapi_quotacheck(mnt, check_type);
2086         if (rc == -EOPNOTSUPP) {
2087                 fprintf(stderr, "error: quotacheck not supported by the quota "
2088                         "master.\nPlease note that quotacheck is deprecated as "
2089                         "of lustre 2.4.0 since space accounting is always "
2090                         "enabled.\nFilesystems not formatted with 2.4 utils or "
2091                         "beyond can be upgraded with tunefs.lustre --quota.\n");
2092                 return rc;
2093         } else if (rc) {
2094                 fprintf(stderr, "quotacheck failed: %s\n", strerror(-rc));
2095                 return rc;
2096         }
2097
2098         rc = llapi_poll_quotacheck(mnt, &qchk);
2099         if (rc) {
2100                 if (*obd_type)
2101                         fprintf(stderr, "%s %s ", obd_type,
2102                                 obd_uuid2str(&qchk.obd_uuid));
2103                 fprintf(stderr, "quota check failed: %s\n", strerror(-rc));
2104                 return rc;
2105         }
2106
2107         memset(&qctl, 0, sizeof(qctl));
2108         qctl.qc_cmd = LUSTRE_Q_QUOTAON;
2109         qctl.qc_type = check_type;
2110         rc = llapi_quotactl(mnt, &qctl);
2111         if (rc && rc != -EALREADY) {
2112                 if (*obd_type)
2113                         fprintf(stderr, "%s %s ", (char *)qctl.obd_type,
2114                                 obd_uuid2str(&qctl.obd_uuid));
2115                 fprintf(stderr, "%s turn on quota failed: %s\n",
2116                         argv[0], strerror(-rc));
2117                 return rc;
2118         }
2119
2120         return 0;
2121 }
2122
2123 static int lfs_quotaon(int argc, char **argv)
2124 {
2125         int c;
2126         char *mnt;
2127         struct if_quotactl qctl;
2128         char *obd_type = (char *)qctl.obd_type;
2129         int rc;
2130
2131         memset(&qctl, 0, sizeof(qctl));
2132         qctl.qc_cmd = LUSTRE_Q_QUOTAON;
2133
2134         optind = 0;
2135         while ((c = getopt(argc, argv, "fgu")) != -1) {
2136                 switch (c) {
2137                 case 'u':
2138                         qctl.qc_type |= 0x01;
2139                         break;
2140                 case 'g':
2141                         qctl.qc_type |= 0x02;
2142                         break;
2143                 case 'f':
2144                         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
2145                         break;
2146                 default:
2147                         fprintf(stderr, "error: %s: option '-%c' "
2148                                         "unrecognized\n", argv[0], c);
2149                         return CMD_HELP;
2150                 }
2151         }
2152
2153         if (qctl.qc_type)
2154                 qctl.qc_type--;
2155         else /* by default, enable quota for both user & group */
2156                 qctl.qc_type = 0x02;
2157
2158         if (argc == optind)
2159                 return CMD_HELP;
2160
2161         mnt = argv[optind];
2162
2163         rc = llapi_quotactl(mnt, &qctl);
2164         if (rc) {
2165                 if (rc == -EOPNOTSUPP) {
2166                         fprintf(stderr, "error: quotaon not supported by the "
2167                                 "quota master.\nPlease note that quotaon/off is"
2168                                 " deprecated as of lustre 2.4.0.\nQuota "
2169                                 "enforcement should now be enabled on the MGS "
2170                                 "via:\nmgs# lctl conf_param ${FSNAME}.quota."
2171                                 "<ost|mdt>=<u|g|ug>\n(ost for block quota, mdt "
2172                                 "for inode quota, u for user and g for group"
2173                                 "\n");
2174                 } else if (rc == -EALREADY) {
2175                         rc = 0;
2176                 } else if (rc == -ENOENT) {
2177                         fprintf(stderr, "error: cannot find quota database, "
2178                                         "make sure you have run quotacheck\n");
2179                 } else {
2180                         if (*obd_type)
2181                                 fprintf(stderr, "%s %s ", obd_type,
2182                                         obd_uuid2str(&qctl.obd_uuid));
2183                         fprintf(stderr, "%s failed: %s\n", argv[0],
2184                                 strerror(-rc));
2185                 }
2186         }
2187
2188         return rc;
2189 }
2190
2191 static int lfs_quotaoff(int argc, char **argv)
2192 {
2193         int c;
2194         char *mnt;
2195         struct if_quotactl qctl;
2196         char *obd_type = (char *)qctl.obd_type;
2197         int rc;
2198
2199         memset(&qctl, 0, sizeof(qctl));
2200         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
2201
2202         optind = 0;
2203         while ((c = getopt(argc, argv, "gu")) != -1) {
2204                 switch (c) {
2205                 case 'u':
2206                         qctl.qc_type |= 0x01;
2207                         break;
2208                 case 'g':
2209                         qctl.qc_type |= 0x02;
2210                         break;
2211                 default:
2212                         fprintf(stderr, "error: %s: option '-%c' "
2213                                         "unrecognized\n", argv[0], c);
2214                         return CMD_HELP;
2215                 }
2216         }
2217
2218         if (qctl.qc_type)
2219                 qctl.qc_type--;
2220         else /* by default, disable quota for both user & group */
2221                 qctl.qc_type = 0x02;
2222
2223         if (argc == optind)
2224                 return CMD_HELP;
2225
2226         mnt = argv[optind];
2227
2228         rc = llapi_quotactl(mnt, &qctl);
2229         if (rc) {
2230                 if (rc == -EOPNOTSUPP) {
2231                         fprintf(stderr, "error: quotaoff not supported by the "
2232                                 "quota master.\nPlease note that quotaon/off is"
2233                                 " deprecated as of lustre 2.4.0.\nQuota "
2234                                 "enforcement can be disabled on the MGS via:\n"
2235                                 "mgs# lctl conf_param ${FSNAME}.quota.<ost|mdt>"
2236                                 "=\"\"\n");
2237                 } else if (rc == -EALREADY) {
2238                         rc = 0;
2239                 } else {
2240                         if (*obd_type)
2241                                 fprintf(stderr, "%s %s ", obd_type,
2242                                         obd_uuid2str(&qctl.obd_uuid));
2243                         fprintf(stderr, "quotaoff failed: %s\n",
2244                                 strerror(-rc));
2245                 }
2246         }
2247
2248         return rc;
2249 }
2250
2251 #define ARG2INT(nr, str, msg)                                           \
2252 do {                                                                    \
2253         char *endp;                                                     \
2254         nr = strtol(str, &endp, 0);                                     \
2255         if (*endp) {                                                    \
2256                 fprintf(stderr, "error: bad %s: %s\n", msg, str);       \
2257                 return CMD_HELP;                                        \
2258         }                                                               \
2259 } while (0)
2260
2261 #define ADD_OVERFLOW(a,b) ((a + b) < a) ? (a = ULONG_MAX) : (a = a + b)
2262
2263 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
2264  * returns the value or ULONG_MAX on integer overflow or incorrect format
2265  * Notes:
2266  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
2267  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
2268  *        3. empty integer value is interpreted as 0
2269  */
2270 static unsigned long str2sec(const char* timestr)
2271 {
2272         const char spec[] = "smhdw";
2273         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
2274         unsigned long val = 0;
2275         char *tail;
2276
2277         if (strpbrk(timestr, spec) == NULL) {
2278                 /* no specifiers inside the time string,
2279                    should treat it as an integer value */
2280                 val = strtoul(timestr, &tail, 10);
2281                 return *tail ? ULONG_MAX : val;
2282         }
2283
2284         /* format string is XXwXXdXXhXXmXXs */
2285         while (*timestr) {
2286                 unsigned long v;
2287                 int ind;
2288                 char* ptr;
2289
2290                 v = strtoul(timestr, &tail, 10);
2291                 if (v == ULONG_MAX || *tail == '\0')
2292                         /* value too large (ULONG_MAX or more)
2293                            or missing specifier */
2294                         goto error;
2295
2296                 ptr = strchr(spec, *tail);
2297                 if (ptr == NULL)
2298                         /* unknown specifier */
2299                         goto error;
2300
2301                 ind = ptr - spec;
2302
2303                 /* check if product will overflow the type */
2304                 if (!(v < ULONG_MAX / mult[ind]))
2305                         goto error;
2306
2307                 ADD_OVERFLOW(val, mult[ind] * v);
2308                 if (val == ULONG_MAX)
2309                         goto error;
2310
2311                 timestr = tail + 1;
2312         }
2313
2314         return val;
2315
2316 error:
2317         return ULONG_MAX;
2318 }
2319
2320 #define ARG2ULL(nr, str, def_units)                                     \
2321 do {                                                                    \
2322         unsigned long long limit, units = def_units;                    \
2323         int rc;                                                         \
2324                                                                         \
2325         rc = llapi_parse_size(str, &limit, &units, 1);                  \
2326         if (rc < 0) {                                                   \
2327                 fprintf(stderr, "error: bad limit value %s\n", str);    \
2328                 return CMD_HELP;                                        \
2329         }                                                               \
2330         nr = limit;                                                     \
2331 } while (0)
2332
2333 static inline int has_times_option(int argc, char **argv)
2334 {
2335         int i;
2336
2337         for (i = 1; i < argc; i++)
2338                 if (!strcmp(argv[i], "-t"))
2339                         return 1;
2340
2341         return 0;
2342 }
2343
2344 int lfs_setquota_times(int argc, char **argv)
2345 {
2346         int c, rc;
2347         struct if_quotactl qctl;
2348         char *mnt, *obd_type = (char *)qctl.obd_type;
2349         struct obd_dqblk *dqb = &qctl.qc_dqblk;
2350         struct obd_dqinfo *dqi = &qctl.qc_dqinfo;
2351         struct option long_opts[] = {
2352                 {"block-grace",     required_argument, 0, 'b'},
2353                 {"group",           no_argument,       0, 'g'},
2354                 {"inode-grace",     required_argument, 0, 'i'},
2355                 {"times",           no_argument,       0, 't'},
2356                 {"user",            no_argument,       0, 'u'},
2357                 {0, 0, 0, 0}
2358         };
2359
2360         memset(&qctl, 0, sizeof(qctl));
2361         qctl.qc_cmd  = LUSTRE_Q_SETINFO;
2362         qctl.qc_type = UGQUOTA;
2363
2364         optind = 0;
2365         while ((c = getopt_long(argc, argv, "b:gi:tu", long_opts, NULL)) != -1) {
2366                 switch (c) {
2367                 case 'u':
2368                 case 'g':
2369                         if (qctl.qc_type != UGQUOTA) {
2370                                 fprintf(stderr, "error: -u and -g can't be used "
2371                                                 "more than once\n");
2372                                 return CMD_HELP;
2373                         }
2374                         qctl.qc_type = (c == 'u') ? USRQUOTA : GRPQUOTA;
2375                         break;
2376                 case 'b':
2377                         if ((dqi->dqi_bgrace = str2sec(optarg)) == ULONG_MAX) {
2378                                 fprintf(stderr, "error: bad block-grace: %s\n",
2379                                         optarg);
2380                                 return CMD_HELP;
2381                         }
2382                         dqb->dqb_valid |= QIF_BTIME;
2383                         break;
2384                 case 'i':
2385                         if ((dqi->dqi_igrace = str2sec(optarg)) == ULONG_MAX) {
2386                                 fprintf(stderr, "error: bad inode-grace: %s\n",
2387                                         optarg);
2388                                 return CMD_HELP;
2389                         }
2390                         dqb->dqb_valid |= QIF_ITIME;
2391                         break;
2392                 case 't': /* Yes, of course! */
2393                         break;
2394                 default: /* getopt prints error message for us when opterr != 0 */
2395                         return CMD_HELP;
2396                 }
2397         }
2398
2399         if (qctl.qc_type == UGQUOTA) {
2400                 fprintf(stderr, "error: neither -u nor -g specified\n");
2401                 return CMD_HELP;
2402         }
2403
2404         if (optind != argc - 1) {
2405                 fprintf(stderr, "error: unexpected parameters encountered\n");
2406                 return CMD_HELP;
2407         }
2408
2409         mnt = argv[optind];
2410         rc = llapi_quotactl(mnt, &qctl);
2411         if (rc) {
2412                 if (*obd_type)
2413                         fprintf(stderr, "%s %s ", obd_type,
2414                                 obd_uuid2str(&qctl.obd_uuid));
2415                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
2416                 return rc;
2417         }
2418
2419         return 0;
2420 }
2421
2422 #define BSLIMIT (1 << 0)
2423 #define BHLIMIT (1 << 1)
2424 #define ISLIMIT (1 << 2)
2425 #define IHLIMIT (1 << 3)
2426
2427 int lfs_setquota(int argc, char **argv)
2428 {
2429         int c, rc;
2430         struct if_quotactl qctl;
2431         char *mnt, *obd_type = (char *)qctl.obd_type;
2432         struct obd_dqblk *dqb = &qctl.qc_dqblk;
2433         struct option long_opts[] = {
2434                 {"block-softlimit", required_argument, 0, 'b'},
2435                 {"block-hardlimit", required_argument, 0, 'B'},
2436                 {"group",           required_argument, 0, 'g'},
2437                 {"inode-softlimit", required_argument, 0, 'i'},
2438                 {"inode-hardlimit", required_argument, 0, 'I'},
2439                 {"user",            required_argument, 0, 'u'},
2440                 {0, 0, 0, 0}
2441         };
2442         unsigned limit_mask = 0;
2443         char *endptr;
2444
2445         if (has_times_option(argc, argv))
2446                 return lfs_setquota_times(argc, argv);
2447
2448         memset(&qctl, 0, sizeof(qctl));
2449         qctl.qc_cmd  = LUSTRE_Q_SETQUOTA;
2450         qctl.qc_type = UGQUOTA; /* UGQUOTA makes no sense for setquota,
2451                                  * so it can be used as a marker that qc_type
2452                                  * isn't reinitialized from command line */
2453
2454         optind = 0;
2455         while ((c = getopt_long(argc, argv, "b:B:g:i:I:u:", long_opts, NULL)) != -1) {
2456                 switch (c) {
2457                 case 'u':
2458                 case 'g':
2459                         if (qctl.qc_type != UGQUOTA) {
2460                                 fprintf(stderr, "error: -u and -g can't be used"
2461                                                 " more than once\n");
2462                                 return CMD_HELP;
2463                         }
2464                         qctl.qc_type = (c == 'u') ? USRQUOTA : GRPQUOTA;
2465                         rc = name2id(&qctl.qc_id, optarg,
2466                                      (qctl.qc_type == USRQUOTA) ? USER : GROUP);
2467                         if (rc) {
2468                                 qctl.qc_id = strtoul(optarg, &endptr, 10);
2469                                 if (*endptr != '\0') {
2470                                         fprintf(stderr, "error: can't find id "
2471                                                 "for name %s\n", optarg);
2472                                         return CMD_HELP;
2473                                 }
2474                         }
2475                         break;
2476                 case 'b':
2477                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
2478                         dqb->dqb_bsoftlimit >>= 10;
2479                         limit_mask |= BSLIMIT;
2480                         if (dqb->dqb_bsoftlimit &&
2481                             dqb->dqb_bsoftlimit <= 1024) /* <= 1M? */
2482                                 fprintf(stderr, "warning: block softlimit is "
2483                                         "smaller than the miminal qunit size, "
2484                                         "please see the help of setquota or "
2485                                         "Lustre manual for details.\n");
2486                         break;
2487                 case 'B':
2488                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
2489                         dqb->dqb_bhardlimit >>= 10;
2490                         limit_mask |= BHLIMIT;
2491                         if (dqb->dqb_bhardlimit &&
2492                             dqb->dqb_bhardlimit <= 1024) /* <= 1M? */
2493                                 fprintf(stderr, "warning: block hardlimit is "
2494                                         "smaller than the miminal qunit size, "
2495                                         "please see the help of setquota or "
2496                                         "Lustre manual for details.\n");
2497                         break;
2498                 case 'i':
2499                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
2500                         limit_mask |= ISLIMIT;
2501                         if (dqb->dqb_isoftlimit &&
2502                             dqb->dqb_isoftlimit <= 1024) /* <= 1K inodes? */
2503                                 fprintf(stderr, "warning: inode softlimit is "
2504                                         "smaller than the miminal qunit size, "
2505                                         "please see the help of setquota or "
2506                                         "Lustre manual for details.\n");
2507                         break;
2508                 case 'I':
2509                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
2510                         limit_mask |= IHLIMIT;
2511                         if (dqb->dqb_ihardlimit &&
2512                             dqb->dqb_ihardlimit <= 1024) /* <= 1K inodes? */
2513                                 fprintf(stderr, "warning: inode hardlimit is "
2514                                         "smaller than the miminal qunit size, "
2515                                         "please see the help of setquota or "
2516                                         "Lustre manual for details.\n");
2517                         break;
2518                 default: /* getopt prints error message for us when opterr != 0 */
2519                         return CMD_HELP;
2520                 }
2521         }
2522
2523         if (qctl.qc_type == UGQUOTA) {
2524                 fprintf(stderr, "error: neither -u nor -g was specified\n");
2525                 return CMD_HELP;
2526         }
2527
2528         if (limit_mask == 0) {
2529                 fprintf(stderr, "error: at least one limit must be specified\n");
2530                 return CMD_HELP;
2531         }
2532
2533         if (optind != argc - 1) {
2534                 fprintf(stderr, "error: unexpected parameters encountered\n");
2535                 return CMD_HELP;
2536         }
2537
2538         mnt = argv[optind];
2539
2540         if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
2541             (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
2542                 /* sigh, we can't just set blimits/ilimits */
2543                 struct if_quotactl tmp_qctl = {.qc_cmd  = LUSTRE_Q_GETQUOTA,
2544                                                .qc_type = qctl.qc_type,
2545                                                .qc_id   = qctl.qc_id};
2546
2547                 rc = llapi_quotactl(mnt, &tmp_qctl);
2548                 if (rc < 0) {
2549                         fprintf(stderr, "error: setquota failed while retrieving"
2550                                         " current quota settings (%s)\n",
2551                                         strerror(-rc));
2552                         return rc;
2553                 }
2554
2555                 if (!(limit_mask & BHLIMIT))
2556                         dqb->dqb_bhardlimit = tmp_qctl.qc_dqblk.dqb_bhardlimit;
2557                 if (!(limit_mask & BSLIMIT))
2558                         dqb->dqb_bsoftlimit = tmp_qctl.qc_dqblk.dqb_bsoftlimit;
2559                 if (!(limit_mask & IHLIMIT))
2560                         dqb->dqb_ihardlimit = tmp_qctl.qc_dqblk.dqb_ihardlimit;
2561                 if (!(limit_mask & ISLIMIT))
2562                         dqb->dqb_isoftlimit = tmp_qctl.qc_dqblk.dqb_isoftlimit;
2563
2564                 /* Keep grace times if we have got no softlimit arguments */
2565                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
2566                         dqb->dqb_valid |= QIF_BTIME;
2567                         dqb->dqb_btime = tmp_qctl.qc_dqblk.dqb_btime;
2568                 }
2569
2570                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
2571                         dqb->dqb_valid |= QIF_ITIME;
2572                         dqb->dqb_itime = tmp_qctl.qc_dqblk.dqb_itime;
2573                 }
2574         }
2575
2576         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
2577         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
2578
2579         rc = llapi_quotactl(mnt, &qctl);
2580         if (rc) {
2581                 if (*obd_type)
2582                         fprintf(stderr, "%s %s ", obd_type,
2583                                 obd_uuid2str(&qctl.obd_uuid));
2584                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
2585                 return rc;
2586         }
2587
2588         return 0;
2589 }
2590
2591 static inline char *type2name(int check_type)
2592 {
2593         if (check_type == USRQUOTA)
2594                 return "user";
2595         else if (check_type == GRPQUOTA)
2596                 return "group";
2597         else
2598                 return "unknown";
2599 }
2600
2601 /* Converts seconds value into format string
2602  * result is returned in buf
2603  * Notes:
2604  *        1. result is in descenting order: 1w2d3h4m5s
2605  *        2. zero fields are not filled (except for p. 3): 5d1s
2606  *        3. zero seconds value is presented as "0s"
2607  */
2608 static char * __sec2str(time_t seconds, char *buf)
2609 {
2610         const char spec[] = "smhdw";
2611         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
2612         unsigned long c;
2613         char *tail = buf;
2614         int i;
2615
2616         for (i = sizeof(mult) / sizeof(mult[0]) - 1 ; i >= 0; i--) {
2617                 c = seconds / mult[i];
2618
2619                 if (c > 0 || (i == 0 && buf == tail))
2620                         tail += snprintf(tail, 40-(tail-buf), "%lu%c", c, spec[i]);
2621
2622                 seconds %= mult[i];
2623         }
2624
2625         return tail;
2626 }
2627
2628 static void sec2str(time_t seconds, char *buf, int rc)
2629 {
2630         char *tail = buf;
2631
2632         if (rc)
2633                 *tail++ = '[';
2634
2635         tail = __sec2str(seconds, tail);
2636
2637         if (rc && tail - buf < 39) {
2638                 *tail++ = ']';
2639                 *tail++ = 0;
2640         }
2641 }
2642
2643 static void diff2str(time_t seconds, char *buf, time_t now)
2644 {
2645
2646         buf[0] = 0;
2647         if (!seconds)
2648                 return;
2649         if (seconds <= now) {
2650                 strcpy(buf, "none");
2651                 return;
2652         }
2653         __sec2str(seconds - now, buf);
2654 }
2655
2656 static void print_quota_title(char *name, struct if_quotactl *qctl,
2657                               bool human_readable)
2658 {
2659         printf("Disk quotas for %s %s (%cid %u):\n",
2660                type2name(qctl->qc_type), name,
2661                *type2name(qctl->qc_type), qctl->qc_id);
2662         printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
2663                "Filesystem", human_readable ? "used" : "kbytes",
2664                "quota", "limit", "grace",
2665                "files", "quota", "limit", "grace");
2666 }
2667
2668 static void kbytes2str(__u64 num, char *buf, bool h)
2669 {
2670         if (!h) {
2671                 sprintf(buf, LPU64, num);
2672         } else {
2673                 if (num >> 30)
2674                         sprintf(buf, "%5.4gT", (double)num / (1 << 30));
2675                 else if (num >> 20)
2676                         sprintf(buf, "%5.4gG", (double)num / (1 << 20));
2677                 else if (num >> 10)
2678                         sprintf(buf, "%5.4gM", (double)num / (1 << 10));
2679                 else
2680                         sprintf(buf, LPU64"%s", num, "k");
2681         }
2682 }
2683
2684 static void print_quota(char *mnt, struct if_quotactl *qctl, int type,
2685                         int rc, bool h)
2686 {
2687         time_t now;
2688
2689         time(&now);
2690
2691         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA) {
2692                 int bover = 0, iover = 0;
2693                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
2694                 char numbuf[3][32];
2695                 char timebuf[40];
2696                 char strbuf[32];
2697
2698                 if (dqb->dqb_bhardlimit &&
2699                     lustre_stoqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
2700                         bover = 1;
2701                 } else if (dqb->dqb_bsoftlimit && dqb->dqb_btime) {
2702                         if (dqb->dqb_btime > now) {
2703                                 bover = 2;
2704                         } else {
2705                                 bover = 3;
2706                         }
2707                 }
2708
2709                 if (dqb->dqb_ihardlimit &&
2710                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
2711                         iover = 1;
2712                 } else if (dqb->dqb_isoftlimit && dqb->dqb_itime) {
2713                         if (dqb->dqb_itime > now) {
2714                                 iover = 2;
2715                         } else {
2716                                 iover = 3;
2717                         }
2718                 }
2719
2720
2721                 if (strlen(mnt) > 15)
2722                         printf("%s\n%15s", mnt, "");
2723                 else
2724                         printf("%15s", mnt);
2725
2726                 if (bover)
2727                         diff2str(dqb->dqb_btime, timebuf, now);
2728
2729                 kbytes2str(lustre_stoqb(dqb->dqb_curspace), strbuf, h);
2730                 if (rc == -EREMOTEIO)
2731                         sprintf(numbuf[0], "%s*", strbuf);
2732                 else
2733                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
2734                                 "%s" : "[%s]", strbuf);
2735
2736                 kbytes2str(dqb->dqb_bsoftlimit, strbuf, h);
2737                 if (type == QC_GENERAL)
2738                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS) ?
2739                                 "%s" : "[%s]", strbuf);
2740                 else
2741                         sprintf(numbuf[1], "%s", "-");
2742
2743                 kbytes2str(dqb->dqb_bhardlimit, strbuf, h);
2744                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS) ?
2745                         "%s" : "[%s]", strbuf);
2746
2747                 printf(" %7s%c %6s %7s %7s",
2748                        numbuf[0], bover ? '*' : ' ', numbuf[1],
2749                        numbuf[2], bover > 1 ? timebuf : "-");
2750
2751                 if (iover)
2752                         diff2str(dqb->dqb_itime, timebuf, now);
2753
2754                 sprintf(numbuf[0], (dqb->dqb_valid & QIF_INODES) ?
2755                         LPU64 : "["LPU64"]", dqb->dqb_curinodes);
2756
2757                 if (type == QC_GENERAL)
2758                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS) ?
2759                                 LPU64 : "["LPU64"]", dqb->dqb_isoftlimit);
2760                 else
2761                         sprintf(numbuf[1], "%s", "-");
2762
2763                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
2764                         LPU64 : "["LPU64"]", dqb->dqb_ihardlimit);
2765
2766                 if (type != QC_OSTIDX)
2767                         printf(" %7s%c %6s %7s %7s",
2768                                numbuf[0], iover ? '*' : ' ', numbuf[1],
2769                                numbuf[2], iover > 1 ? timebuf : "-");
2770                 else
2771                         printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
2772                 printf("\n");
2773
2774         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO ||
2775                    qctl->qc_cmd == Q_GETOINFO) {
2776                 char bgtimebuf[40];
2777                 char igtimebuf[40];
2778
2779                 sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
2780                 sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
2781                 printf("Block grace time: %s; Inode grace time: %s\n",
2782                        bgtimebuf, igtimebuf);
2783         }
2784 }
2785
2786 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt,
2787                            bool h, __u64 *total)
2788 {
2789         int rc = 0, rc1 = 0, count = 0;
2790         __u32 valid = qctl->qc_valid;
2791
2792         rc = llapi_get_obd_count(mnt, &count, is_mdt);
2793         if (rc) {
2794                 fprintf(stderr, "can not get %s count: %s\n",
2795                         is_mdt ? "mdt": "ost", strerror(-rc));
2796                 return rc;
2797         }
2798
2799         for (qctl->qc_idx = 0; qctl->qc_idx < count; qctl->qc_idx++) {
2800                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
2801                 rc = llapi_quotactl(mnt, qctl);
2802                 if (rc) {
2803                         /* It is remote client case. */
2804                         if (-rc == EOPNOTSUPP) {
2805                                 rc = 0;
2806                                 goto out;
2807                         }
2808
2809                         if (!rc1)
2810                                 rc1 = rc;
2811                         fprintf(stderr, "quotactl %s%d failed.\n",
2812                                 is_mdt ? "mdt": "ost", qctl->qc_idx);
2813                         continue;
2814                 }
2815
2816                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl,
2817                             qctl->qc_valid, 0, h);
2818                 *total += is_mdt ? qctl->qc_dqblk.dqb_ihardlimit :
2819                                    qctl->qc_dqblk.dqb_bhardlimit;
2820         }
2821 out:
2822         qctl->qc_valid = valid;
2823         return rc ? : rc1;
2824 }
2825
2826 static int lfs_quota(int argc, char **argv)
2827 {
2828         int c;
2829         char *mnt, *name = NULL;
2830         struct if_quotactl qctl = { .qc_cmd = LUSTRE_Q_GETQUOTA,
2831                                     .qc_type = UGQUOTA };
2832         char *obd_type = (char *)qctl.obd_type;
2833         char *obd_uuid = (char *)qctl.obd_uuid.uuid;
2834         int rc, rc1 = 0, rc2 = 0, rc3 = 0,
2835             verbose = 0, pass = 0, quiet = 0, inacc;
2836         char *endptr;
2837         __u32 valid = QC_GENERAL, idx = 0;
2838         __u64 total_ialloc = 0, total_balloc = 0;
2839         bool human_readable = false;
2840
2841         optind = 0;
2842         while ((c = getopt(argc, argv, "gi:I:o:qtuvh")) != -1) {
2843                 switch (c) {
2844                 case 'u':
2845                         if (qctl.qc_type != UGQUOTA) {
2846                                 fprintf(stderr, "error: use either -u or -g\n");
2847                                 return CMD_HELP;
2848                         }
2849                         qctl.qc_type = USRQUOTA;
2850                         break;
2851                 case 'g':
2852                         if (qctl.qc_type != UGQUOTA) {
2853                                 fprintf(stderr, "error: use either -u or -g\n");
2854                                 return CMD_HELP;
2855                         }
2856                         qctl.qc_type = GRPQUOTA;
2857                         break;
2858                 case 't':
2859                         qctl.qc_cmd = LUSTRE_Q_GETINFO;
2860                         break;
2861                 case 'o':
2862                         valid = qctl.qc_valid = QC_UUID;
2863                         strncpy(obd_uuid, optarg, sizeof(qctl.obd_uuid));
2864                         break;
2865                 case 'i':
2866                         valid = qctl.qc_valid = QC_MDTIDX;
2867                         idx = qctl.qc_idx = atoi(optarg);
2868                         break;
2869                 case 'I':
2870                         valid = qctl.qc_valid = QC_OSTIDX;
2871                         idx = qctl.qc_idx = atoi(optarg);
2872                         break;
2873                 case 'v':
2874                         verbose = 1;
2875                         break;
2876                 case 'q':
2877                         quiet = 1;
2878                         break;
2879                 case 'h':
2880                         human_readable = true;
2881                         break;
2882                 default:
2883                         fprintf(stderr, "error: %s: option '-%c' "
2884                                         "unrecognized\n", argv[0], c);
2885                         return CMD_HELP;
2886                 }
2887         }
2888
2889         /* current uid/gid info for "lfs quota /path/to/lustre/mount" */
2890         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA && qctl.qc_type == UGQUOTA &&
2891             optind == argc - 1) {
2892 ug_output:
2893                 memset(&qctl, 0, sizeof(qctl)); /* spoiled by print_*_quota */
2894                 qctl.qc_cmd = LUSTRE_Q_GETQUOTA;
2895                 qctl.qc_valid = valid;
2896                 qctl.qc_idx = idx;
2897                 if (pass++ == 0) {
2898                         qctl.qc_type = USRQUOTA;
2899                         qctl.qc_id = geteuid();
2900                 } else {
2901                         qctl.qc_type = GRPQUOTA;
2902                         qctl.qc_id = getegid();
2903                 }
2904                 rc = id2name(&name, qctl.qc_id,
2905                              (qctl.qc_type == USRQUOTA) ? USER : GROUP);
2906                 if (rc)
2907                         name = "<unknown>";
2908         /* lfs quota -u username /path/to/lustre/mount */
2909         } else if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) {
2910                 /* options should be followed by u/g-name and mntpoint */
2911                 if (optind + 2 != argc || qctl.qc_type == UGQUOTA) {
2912                         fprintf(stderr, "error: missing quota argument(s)\n");
2913                         return CMD_HELP;
2914                 }
2915
2916                 name = argv[optind++];
2917                 rc = name2id(&qctl.qc_id, name,
2918                              (qctl.qc_type == USRQUOTA) ? USER : GROUP);
2919                 if (rc) {
2920                         qctl.qc_id = strtoul(name, &endptr, 10);
2921                         if (*endptr != '\0') {
2922                                 fprintf(stderr, "error: can't find id for name "
2923                                         "%s\n", name);
2924                                 return CMD_HELP;
2925                         }
2926                 }
2927         } else if (optind + 1 != argc || qctl.qc_type == UGQUOTA) {
2928                 fprintf(stderr, "error: missing quota info argument(s)\n");
2929                 return CMD_HELP;
2930         }
2931
2932         mnt = argv[optind];
2933
2934         rc1 = llapi_quotactl(mnt, &qctl);
2935         if (rc1 < 0) {
2936                 switch (rc1) {
2937                 case -ESRCH:
2938                         fprintf(stderr, "%s quotas are not enabled.\n",
2939                                 qctl.qc_type == USRQUOTA ? "user" : "group");
2940                         goto out;
2941                 case -EPERM:
2942                         fprintf(stderr, "Permission denied.\n");
2943                 case -ENOENT:
2944                         /* We already got a "No such file..." message. */
2945                         goto out;
2946                 default:
2947                         fprintf(stderr, "Unexpected quotactl error: %s\n",
2948                                 strerror(-rc1));
2949                 }
2950         }
2951
2952         if (qctl.qc_cmd == LUSTRE_Q_GETQUOTA && !quiet)
2953                 print_quota_title(name, &qctl, human_readable);
2954
2955         if (rc1 && *obd_type)
2956                 fprintf(stderr, "%s %s ", obd_type, obd_uuid);
2957
2958         if (qctl.qc_valid != QC_GENERAL)
2959                 mnt = "";
2960
2961         inacc = (qctl.qc_cmd == LUSTRE_Q_GETQUOTA) &&
2962                 ((qctl.qc_dqblk.dqb_valid & (QIF_LIMITS|QIF_USAGE)) !=
2963                  (QIF_LIMITS|QIF_USAGE));
2964
2965         print_quota(mnt, &qctl, QC_GENERAL, rc1, human_readable);
2966
2967         if (qctl.qc_valid == QC_GENERAL && qctl.qc_cmd != LUSTRE_Q_GETINFO &&
2968             verbose) {
2969                 char strbuf[32];
2970
2971                 rc2 = print_obd_quota(mnt, &qctl, 1, human_readable,
2972                                       &total_ialloc);
2973                 rc3 = print_obd_quota(mnt, &qctl, 0, human_readable,
2974                                       &total_balloc);
2975                 kbytes2str(total_balloc, strbuf, human_readable);
2976                 printf("Total allocated inode limit: "LPU64", total "
2977                        "allocated block limit: %s\n", total_ialloc, strbuf);
2978         }
2979
2980         if (rc1 || rc2 || rc3 || inacc)
2981                 printf("Some errors happened when getting quota info. "
2982                        "Some devices may be not working or deactivated. "
2983                        "The data in \"[]\" is inaccurate.\n");
2984
2985 out:
2986         if (pass == 1)
2987                 goto ug_output;
2988
2989         return rc1;
2990 }
2991 #endif /* HAVE_SYS_QUOTA_H! */
2992
2993 static int flushctx_ioctl(char *mp)
2994 {
2995         int fd, rc;
2996
2997         fd = open(mp, O_RDONLY);
2998         if (fd == -1) {
2999                 fprintf(stderr, "flushctx: error open %s: %s\n",
3000                         mp, strerror(errno));
3001                 return -1;
3002         }
3003
3004         rc = ioctl(fd, LL_IOC_FLUSHCTX);
3005         if (rc == -1)
3006                 fprintf(stderr, "flushctx: error ioctl %s: %s\n",
3007                         mp, strerror(errno));
3008
3009         close(fd);
3010         return rc;
3011 }
3012
3013 static int lfs_flushctx(int argc, char **argv)
3014 {
3015         int     kdestroy = 0, c;
3016         FILE   *proc = NULL;
3017         char    procline[PATH_MAX], *line;
3018         int     rc = 0;
3019
3020         optind = 0;
3021         while ((c = getopt(argc, argv, "k")) != -1) {
3022                 switch (c) {
3023                 case 'k':
3024                         kdestroy = 1;
3025                         break;
3026                 default:
3027                         fprintf(stderr, "error: %s: option '-%c' "
3028                                         "unrecognized\n", argv[0], c);
3029                         return CMD_HELP;
3030                 }
3031         }
3032
3033         if (kdestroy) {
3034             int rc;
3035             if ((rc = system("kdestroy > /dev/null")) != 0) {
3036                 rc = WEXITSTATUS(rc);
3037                 fprintf(stderr, "error destroying tickets: %d, continuing\n", rc);
3038             }
3039         }
3040
3041         if (optind >= argc) {
3042                 /* flush for all mounted lustre fs. */
3043                 proc = fopen("/proc/mounts", "r");
3044                 if (!proc) {
3045                         fprintf(stderr, "error: %s: can't open /proc/mounts\n",
3046                                 argv[0]);
3047                         return -1;
3048                 }
3049
3050                 while ((line = fgets(procline, PATH_MAX, proc)) != NULL) {
3051                         char dev[PATH_MAX];
3052                         char mp[PATH_MAX];
3053                         char fs[PATH_MAX];
3054
3055                         if (sscanf(line, "%s %s %s", dev, mp, fs) != 3) {
3056                                 fprintf(stderr, "%s: unexpected format in "
3057                                                 "/proc/mounts\n",
3058                                         argv[0]);
3059                                 rc = -1;
3060                                 goto out;
3061                         }
3062
3063                         if (strcmp(fs, "lustre") != 0)
3064                                 continue;
3065                         /* we use '@' to determine it's a client. are there
3066                          * any other better way?
3067                          */
3068                         if (strchr(dev, '@') == NULL)
3069                                 continue;
3070
3071                         if (flushctx_ioctl(mp))
3072                                 rc = -1;
3073                 }
3074         } else {
3075                 /* flush fs as specified */
3076                 while (optind < argc) {
3077                         if (flushctx_ioctl(argv[optind++]))
3078                                 rc = -1;
3079                 }
3080         }
3081
3082 out:
3083         if (proc != NULL)
3084                 fclose(proc);
3085         return rc;
3086 }
3087
3088 static int lfs_lsetfacl(int argc, char **argv)
3089 {
3090         argv[0]++;
3091         return(llapi_lsetfacl(argc, argv));
3092 }
3093
3094 static int lfs_lgetfacl(int argc, char **argv)
3095 {
3096         argv[0]++;
3097         return(llapi_lgetfacl(argc, argv));
3098 }
3099
3100 static int lfs_rsetfacl(int argc, char **argv)
3101 {
3102         argv[0]++;
3103         return(llapi_rsetfacl(argc, argv));
3104 }
3105
3106 static int lfs_rgetfacl(int argc, char **argv)
3107 {
3108         argv[0]++;
3109         return(llapi_rgetfacl(argc, argv));
3110 }
3111
3112 static int lfs_cp(int argc, char **argv)
3113 {
3114         return(llapi_cp(argc, argv));
3115 }
3116
3117 static int lfs_ls(int argc, char **argv)
3118 {
3119         return(llapi_ls(argc, argv));
3120 }
3121
3122 static int lfs_changelog(int argc, char **argv)
3123 {
3124         void *changelog_priv;
3125         struct changelog_ext_rec *rec;
3126         long long startrec = 0, endrec = 0;
3127         char *mdd;
3128         struct option long_opts[] = {
3129                 {"follow", no_argument, 0, 'f'},
3130                 {0, 0, 0, 0}
3131         };
3132         char short_opts[] = "f";
3133         int rc, follow = 0;
3134
3135         optind = 0;
3136         while ((rc = getopt_long(argc, argv, short_opts,
3137                                 long_opts, NULL)) != -1) {
3138                 switch (rc) {
3139                 case 'f':
3140                         follow++;
3141                         break;
3142                 case '?':
3143                         return CMD_HELP;
3144                 default:
3145                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
3146                                 argv[0], argv[optind - 1]);
3147                         return CMD_HELP;
3148                 }
3149         }
3150         if (optind >= argc)
3151                 return CMD_HELP;
3152
3153         mdd = argv[optind++];
3154         if (argc > optind)
3155                 startrec = strtoll(argv[optind++], NULL, 10);
3156         if (argc > optind)
3157                 endrec = strtoll(argv[optind++], NULL, 10);
3158
3159         rc = llapi_changelog_start(&changelog_priv,
3160                                    CHANGELOG_FLAG_BLOCK |
3161                                    (follow ? CHANGELOG_FLAG_FOLLOW : 0),
3162                                    mdd, startrec);
3163         if (rc < 0) {
3164                 fprintf(stderr, "Can't start changelog: %s\n",
3165                         strerror(errno = -rc));
3166                 return rc;
3167         }
3168
3169         while ((rc = llapi_changelog_recv(changelog_priv, &rec)) == 0) {
3170                 time_t secs;
3171                 struct tm ts;
3172
3173                 if (endrec && rec->cr_index > endrec) {
3174                         llapi_changelog_free(&rec);
3175                         break;
3176                 }
3177                 if (rec->cr_index < startrec) {
3178                         llapi_changelog_free(&rec);
3179                         continue;
3180                 }
3181
3182                 secs = rec->cr_time >> 30;
3183                 gmtime_r(&secs, &ts);
3184                 printf(LPU64" %02d%-5s %02d:%02d:%02d.%06d %04d.%02d.%02d "
3185                        "0x%x t="DFID, rec->cr_index, rec->cr_type,
3186                        changelog_type2str(rec->cr_type),
3187                        ts.tm_hour, ts.tm_min, ts.tm_sec,
3188                        (int)(rec->cr_time & ((1<<30) - 1)),
3189                        ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday,
3190                        rec->cr_flags & CLF_FLAGMASK, PFID(&rec->cr_tfid));
3191                 if (rec->cr_namelen)
3192                         /* namespace rec includes parent and filename */
3193                         printf(" p="DFID" %.*s", PFID(&rec->cr_pfid),
3194                                 rec->cr_namelen, rec->cr_name);
3195
3196                 if (!fid_is_zero(&rec->cr_sfid))
3197                         printf(" s="DFID" sp="DFID" %.*s",
3198                                 PFID(&rec->cr_sfid), PFID(&rec->cr_spfid),
3199                                 changelog_rec_snamelen(rec),
3200                                 changelog_rec_sname(rec));
3201                 printf("\n");
3202
3203                 llapi_changelog_free(&rec);
3204         }
3205
3206         llapi_changelog_fini(&changelog_priv);
3207
3208         if (rc < 0)
3209                 fprintf(stderr, "Changelog: %s\n", strerror(errno = -rc));
3210
3211         return (rc == 1 ? 0 : rc);
3212 }
3213
3214 static int lfs_changelog_clear(int argc, char **argv)
3215 {
3216         long long endrec;
3217         int rc;
3218
3219         if (argc != 4)
3220                 return CMD_HELP;
3221
3222         endrec = strtoll(argv[3], NULL, 10);
3223
3224         rc = llapi_changelog_clear(argv[1], argv[2], endrec);
3225         if (rc)
3226                 fprintf(stderr, "%s error: %s\n", argv[0],
3227                         strerror(errno = -rc));
3228         return rc;
3229 }
3230
3231 static int lfs_fid2path(int argc, char **argv)
3232 {
3233         struct option long_opts[] = {
3234                 {"cur", no_argument, 0, 'c'},
3235                 {"link", required_argument, 0, 'l'},
3236                 {"rec", required_argument, 0, 'r'},
3237                 {0, 0, 0, 0}
3238         };
3239         char  short_opts[] = "cl:r:";
3240         char *device, *fid, *path;
3241         long long recno = -1;
3242         int linkno = -1;
3243         int lnktmp;
3244         int printcur = 0;
3245         int rc = 0;
3246
3247         optind = 0;
3248
3249         while ((rc = getopt_long(argc, argv, short_opts,
3250                                 long_opts, NULL)) != -1) {
3251                 switch (rc) {
3252                 case 'c':
3253                         printcur++;
3254                         break;
3255                 case 'l':
3256                         linkno = strtol(optarg, NULL, 10);
3257                         break;
3258                 case 'r':
3259                         recno = strtoll(optarg, NULL, 10);
3260                         break;
3261                 case '?':
3262                         return CMD_HELP;
3263                 default:
3264                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
3265                                 argv[0], argv[optind - 1]);
3266                         return CMD_HELP;
3267                 }
3268         }
3269
3270         if (argc < 3)
3271                 return CMD_HELP;
3272
3273         device = argv[optind++];
3274         path = calloc(1, PATH_MAX);
3275
3276         rc = 0;
3277         while (optind < argc) {
3278                 fid = argv[optind++];
3279
3280                 lnktmp = (linkno >= 0) ? linkno : 0;
3281                 while (1) {
3282                         int oldtmp = lnktmp;
3283                         long long rectmp = recno;
3284                         int rc2;
3285                         rc2 = llapi_fid2path(device, fid, path, PATH_MAX,
3286                                              &rectmp, &lnktmp);
3287                         if (rc2 < 0) {
3288                                 fprintf(stderr, "%s: error on FID %s: %s\n",
3289                                         argv[0], fid, strerror(errno = -rc2));
3290                                 if (rc == 0)
3291                                         rc = rc2;
3292                                 break;
3293                         }
3294
3295                         if (printcur)
3296                                 fprintf(stdout, "%lld ", rectmp);
3297                         if (device[0] == '/') {
3298                                 fprintf(stdout, "%s", device);
3299                                 if (device[strlen(device) - 1] != '/')
3300                                         fprintf(stdout, "/");
3301                         } else if (path[0] == '\0') {
3302                                 fprintf(stdout, "/");
3303                         }
3304                         fprintf(stdout, "%s\n", path);
3305
3306                         if (linkno >= 0)
3307                                 /* specified linkno */
3308                                 break;
3309                         if (oldtmp == lnktmp)
3310                                 /* no more links */
3311                                 break;
3312                 }
3313         }
3314
3315         free(path);
3316         return rc;
3317 }
3318
3319 static int lfs_path2fid(int argc, char **argv)
3320 {
3321         char **path;
3322         const char *sep = "";
3323         lustre_fid fid;
3324         int rc = 0;
3325
3326         if (argc < 2)
3327                 return CMD_HELP;
3328         else if (argc > 2)
3329                 sep = ": ";
3330
3331         path = argv + 1;
3332         while (*path != NULL) {
3333                 int err = llapi_path2fid(*path, &fid);
3334
3335                 if (err) {
3336                         fprintf(stderr, "%s: can't get fid for %s: %s\n",
3337                                 argv[0], *path, strerror(-err));
3338                         if (rc == 0) {
3339                                 rc = err;
3340                                 errno = -err;
3341                         }
3342                         goto out;
3343                 }
3344                 printf("%s%s"DFID"\n", *sep != '\0' ? *path : "", sep,
3345                        PFID(&fid));
3346 out:
3347                 path++;
3348         }
3349
3350         return rc;
3351 }
3352
3353 static int lfs_data_version(int argc, char **argv)
3354 {
3355         char *path;
3356         __u64 data_version;
3357         int fd;
3358         int rc;
3359         int c;
3360         int data_version_flags = LL_DV_RD_FLUSH; /* Read by default */
3361
3362         if (argc < 2)
3363                 return CMD_HELP;
3364
3365         optind = 0;
3366         while ((c = getopt(argc, argv, "nrw")) != -1) {
3367                 switch (c) {
3368                 case 'n':
3369                         data_version_flags = 0;
3370                         break;
3371                 case 'r':
3372                         data_version_flags |= LL_DV_RD_FLUSH;
3373                         break;
3374                 case 'w':
3375                         data_version_flags |= LL_DV_WR_FLUSH;
3376                         break;
3377                 default:
3378                         return CMD_HELP;
3379                 }
3380         }
3381         if (optind == argc)
3382                 return CMD_HELP;
3383
3384         path = argv[optind];
3385         fd = open(path, O_RDONLY);
3386         if (fd < 0)
3387                 err(errno, "cannot open file %s", path);
3388
3389         rc = llapi_get_data_version(fd, &data_version, data_version_flags);
3390         if (rc < 0)
3391                 err(errno, "cannot get version for %s", path);
3392         else
3393                 printf(LPU64 "\n", data_version);
3394
3395         close(fd);
3396         return rc;
3397 }
3398
3399 static int lfs_hsm_state(int argc, char **argv)
3400 {
3401         int rc;
3402         int i = 1;
3403         char *path;
3404         struct hsm_user_state hus;
3405
3406         if (argc < 2)
3407                 return CMD_HELP;
3408
3409         do {
3410                 path = argv[i];
3411
3412                 rc = llapi_hsm_state_get(path, &hus);
3413                 if (rc) {
3414                         fprintf(stderr, "can't get hsm state for %s: %s\n",
3415                                 path, strerror(errno = -rc));
3416                         return rc;
3417                 }
3418
3419                 /* Display path name and status flags */
3420                 printf("%s: (0x%08x)", path, hus.hus_states);
3421
3422                 if (hus.hus_states & HS_RELEASED)
3423                         printf(" released");
3424                 if (hus.hus_states & HS_EXISTS)
3425                         printf(" exists");
3426                 if (hus.hus_states & HS_DIRTY)
3427                         printf(" dirty");
3428                 if (hus.hus_states & HS_ARCHIVED)
3429                         printf(" archived");
3430                 /* Display user-settable flags */
3431                 if (hus.hus_states & HS_NORELEASE)
3432                         printf(" never_release");
3433                 if (hus.hus_states & HS_NOARCHIVE)
3434                         printf(" never_archive");
3435                 if (hus.hus_states & HS_LOST)
3436                         printf(" lost_from_hsm");
3437
3438                 if (hus.hus_archive_id != 0)
3439                         printf(", archive_id:%d", hus.hus_archive_id);
3440                 printf("\n");
3441
3442         } while (++i < argc);
3443
3444         return 0;
3445 }
3446
3447 #define LFS_HSM_SET   0
3448 #define LFS_HSM_CLEAR 1
3449
3450 /**
3451  * Generic function to set or clear HSM flags.
3452  * Used by hsm_set and hsm_clear.
3453  *
3454  * @mode  if LFS_HSM_SET, set the flags, if LFS_HSM_CLEAR, clear the flags.
3455  */
3456 static int lfs_hsm_change_flags(int argc, char **argv, int mode)
3457 {
3458         struct option long_opts[] = {
3459                 {"lost", 0, 0, 'l'},
3460                 {"norelease", 0, 0, 'r'},
3461                 {"noarchive", 0, 0, 'a'},
3462                 {"archived", 0, 0, 'A'},
3463                 {"dirty", 0, 0, 'd'},
3464                 {"exists", 0, 0, 'e'},
3465                 {0, 0, 0, 0}
3466         };
3467         char short_opts[] = "lraAde";
3468         __u64 mask = 0;
3469         int c, rc;
3470         char *path;
3471
3472         if (argc < 3)
3473                 return CMD_HELP;
3474
3475         optind = 0;
3476         while ((c = getopt_long(argc, argv, short_opts,
3477                                 long_opts, NULL)) != -1) {
3478                 switch (c) {
3479                 case 'l':
3480                         mask |= HS_LOST;
3481                         break;
3482                 case 'a':
3483                         mask |= HS_NOARCHIVE;
3484                         break;
3485                 case 'A':
3486                         mask |= HS_ARCHIVED;
3487                         break;
3488                 case 'r':
3489                         mask |= HS_NORELEASE;
3490                         break;
3491                 case 'd':
3492                         mask |= HS_DIRTY;
3493                         break;
3494                 case 'e':
3495                         mask |= HS_EXISTS;
3496                         break;
3497                 case '?':
3498                         return CMD_HELP;
3499                 default:
3500                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
3501                                 argv[0], argv[optind - 1]);
3502                         return CMD_HELP;
3503                 }
3504         }
3505
3506         /* User should have specified a flag */
3507         if (mask == 0)
3508                 return CMD_HELP;
3509
3510         while (optind < argc) {
3511
3512                 path = argv[optind];
3513
3514                 /* If mode == 0, this means we apply the mask. */
3515                 if (mode == LFS_HSM_SET)
3516                         rc = llapi_hsm_state_set(path, mask, 0, 0);
3517                 else
3518                         rc = llapi_hsm_state_set(path, 0, mask, 0);
3519
3520                 if (rc != 0) {
3521                         fprintf(stderr, "Can't change hsm flags for %s: %s\n",
3522                                 path, strerror(errno = -rc));
3523                         return rc;
3524                 }
3525                 optind++;
3526         }
3527
3528         return 0;
3529 }
3530
3531 static int lfs_hsm_action(int argc, char **argv)
3532 {
3533         int                              rc;
3534         int                              i = 1;
3535         char                            *path;
3536         struct hsm_current_action        hca;
3537         struct hsm_extent                he;
3538         enum hsm_user_action             hua;
3539         enum hsm_progress_states         hps;
3540
3541         if (argc < 2)
3542                 return CMD_HELP;
3543
3544         do {
3545                 path = argv[i];
3546
3547                 rc = llapi_hsm_current_action(path, &hca);
3548                 if (rc) {
3549                         fprintf(stderr, "can't get hsm action for %s: %s\n",
3550                                 path, strerror(errno = -rc));
3551                         return rc;
3552                 }
3553                 he = hca.hca_location;
3554                 hua = hca.hca_action;
3555                 hps = hca.hca_state;
3556
3557                 printf("%s: %s", path, hsm_user_action2name(hua));
3558
3559                 /* Skip file without action */
3560                 if (hca.hca_action == HUA_NONE) {
3561                         printf("\n");
3562                         continue;
3563                 }
3564
3565                 printf(" %s ", hsm_progress_state2name(hps));
3566
3567                 if ((hps == HPS_RUNNING) &&
3568                     (hua == HUA_ARCHIVE || hua == HUA_RESTORE))
3569                         printf("("LPX64 " bytes moved)\n", he.length);
3570                 else if ((he.offset + he.length) == LUSTRE_EOF)
3571                         printf("(from "LPX64 " to EOF)\n", he.offset);
3572                 else
3573                         printf("(from "LPX64 " to "LPX64")\n",
3574                                he.offset, he.offset + he.length);
3575
3576         } while (++i < argc);
3577
3578         return 0;
3579 }
3580
3581 static int lfs_hsm_set(int argc, char **argv)
3582 {
3583         return lfs_hsm_change_flags(argc, argv, LFS_HSM_SET);
3584 }
3585
3586 static int lfs_hsm_clear(int argc, char **argv)
3587 {
3588         return lfs_hsm_change_flags(argc, argv, LFS_HSM_CLEAR);
3589 }
3590
3591 /**
3592  * Check file state and return its fid, to be used by lfs_hsm_request().
3593  *
3594  * \param[in]     file      Path to file to check
3595  * \param[in,out] fid       Pointer to allocated lu_fid struct.
3596  * \param[in,out] last_dev  Pointer to last device id used.
3597  *
3598  * \return 0 on success.
3599  */
3600 static int lfs_hsm_prepare_file(char *file, struct lu_fid *fid,
3601                                 dev_t *last_dev)
3602 {
3603         struct stat     st;
3604         int             rc;
3605
3606         rc = lstat(file, &st);
3607         if (rc) {
3608                 fprintf(stderr, "Cannot stat %s: %s\n", file, strerror(errno));
3609                 return -errno;
3610         }
3611         /* A request should be ... */
3612         if (*last_dev != st.st_dev && *last_dev != 0) {
3613                 fprintf(stderr, "All files should be "
3614                         "on the same filesystem: %s\n", file);
3615                 return -EINVAL;
3616         }
3617         *last_dev = st.st_dev;
3618
3619         rc = llapi_path2fid(file, fid);
3620         if (rc) {
3621                 fprintf(stderr, "Cannot read FID of %s: %s\n",
3622                         file, strerror(-rc));
3623                 return rc;
3624         }
3625         return 0;
3626 }
3627
3628 static int lfs_hsm_request(int argc, char **argv, int action)
3629 {
3630         struct option            long_opts[] = {
3631                 {"filelist", 1, 0, 'l'},
3632                 {"data", 1, 0, 'D'},
3633                 {"archive", 1, 0, 'a'},
3634                 {0, 0, 0, 0}
3635         };
3636         dev_t                    last_dev = 0;
3637         char                     short_opts[] = "l:D:a:";
3638         struct hsm_user_request *hur, *oldhur;
3639         int                      c, i;
3640         size_t                   len;
3641         int                      nbfile;
3642         char                    *line = NULL;
3643         char                    *filelist = NULL;
3644         char                     fullpath[PATH_MAX];
3645         char                    *opaque = NULL;
3646         int                      opaque_len = 0;
3647         int                      archive_id = 0;
3648         FILE                    *fp;
3649         int                      nbfile_alloc = 0;
3650         char                     some_file[PATH_MAX+1] = "";
3651         int                      rc;
3652
3653         if (argc < 2)
3654                 return CMD_HELP;
3655
3656         optind = 0;
3657         while ((c = getopt_long(argc, argv, short_opts,
3658                                 long_opts, NULL)) != -1) {
3659                 switch (c) {
3660                 case 'l':
3661                         filelist = optarg;
3662                         break;
3663                 case 'D':
3664                         opaque = optarg;
3665                         break;
3666                 case 'a':
3667                         if (action != HUA_ARCHIVE) {
3668                                 fprintf(stderr,
3669                                         "error: -a is supported only "
3670                                         "when archiving\n");
3671                                 return CMD_HELP;
3672                         }
3673                         archive_id = atoi(optarg);
3674                         break;
3675                 case '?':
3676                         return CMD_HELP;
3677                 default:
3678                         fprintf(stderr, "error: %s: option '%s' unrecognized\n",
3679                                 argv[0], argv[optind - 1]);
3680                         return CMD_HELP;
3681                 }
3682         }
3683
3684         /* All remaining args are files, so we have at least nbfile */
3685         nbfile = argc - optind;
3686
3687         if ((nbfile == 0) && (filelist == NULL))
3688                 return CMD_HELP;
3689
3690         if (opaque != NULL)
3691                 opaque_len = strlen(opaque);
3692
3693         /* Alloc the request structure with enough place to store all files
3694          * from command line. */
3695         hur = llapi_hsm_user_request_alloc(nbfile, opaque_len);
3696         if (hur == NULL) {
3697                 fprintf(stderr, "Cannot create the request: %s\n",
3698                         strerror(errno));
3699                 return errno;
3700         }
3701         nbfile_alloc = nbfile;
3702
3703         hur->hur_request.hr_action = action;
3704         hur->hur_request.hr_archive_id = archive_id;
3705         hur->hur_request.hr_flags = 0;
3706
3707         /* All remaining args are files, add them */
3708         if (nbfile != 0) {
3709                 if (strlen(argv[optind]) > sizeof(some_file)-1) {
3710                         free(hur);
3711                         return -E2BIG;
3712                 }
3713                 strncpy(some_file, argv[optind], sizeof(some_file));
3714         }
3715
3716         for (i = 0; i < nbfile; i++) {
3717                 hur->hur_user_item[i].hui_extent.length = -1;
3718                 rc = lfs_hsm_prepare_file(argv[optind + i],
3719                                           &hur->hur_user_item[i].hui_fid,
3720                                           &last_dev);
3721                 hur->hur_request.hr_itemcount++;
3722                 if (rc)
3723                         goto out_free;
3724         }
3725
3726         /* from here stop using nb_file, use hur->hur_request.hr_itemcount */
3727
3728         /* If a filelist was specified, read the filelist from it. */
3729         if (filelist != NULL) {
3730                 fp = fopen(filelist, "r");
3731                 if (fp == NULL) {
3732                         fprintf(stderr, "Cannot read the file list %s: %s\n",
3733                                 filelist, strerror(errno));
3734                         rc = -errno;
3735                         goto out_free;
3736                 }
3737
3738                 while ((rc = getline(&line, &len, fp)) != -1) {
3739                         struct hsm_user_item *hui;
3740
3741                         /* If allocated buffer was too small, gets something
3742                          * bigger */
3743                         if (nbfile_alloc <= hur->hur_request.hr_itemcount) {
3744                                 nbfile_alloc = nbfile_alloc * 2 + 1;
3745                                 oldhur = hur;
3746                                 hur = llapi_hsm_user_request_alloc(nbfile_alloc,
3747                                                                    opaque_len);
3748                                 if (hur == NULL) {
3749                                         fprintf(stderr, "Cannot allocate "
3750                                                 "the request: %s\n",
3751                                                 strerror(errno));
3752                                         hur = oldhur;
3753                                         rc = -errno;
3754                                         fclose(fp);
3755                                         goto out_free;
3756                                 }
3757                                 memcpy(hur, oldhur, hur_len(oldhur));
3758                                 free(oldhur);
3759                         }
3760
3761                         /* Chop CR */
3762                         if (line[strlen(line) - 1] == '\n')
3763                                 line[strlen(line) - 1] = '\0';
3764
3765                         hui =
3766                              &hur->hur_user_item[hur->hur_request.hr_itemcount];
3767                         hui->hui_extent.length = -1;
3768                         rc = lfs_hsm_prepare_file(line, &hui->hui_fid,
3769                                                   &last_dev);
3770                         hur->hur_request.hr_itemcount++;
3771                         if (rc) {
3772                                 fclose(fp);
3773                                 goto out_free;
3774                         }
3775
3776                         if ((some_file[0] == '\0') &&
3777                             (strlen(line) < sizeof(some_file)))
3778                                 strcpy(some_file, line);
3779                 }
3780
3781                 rc = fclose(fp);
3782                 if (line)
3783                         free(line);
3784         }
3785
3786         /* If a --data was used, add it to the request */
3787         hur->hur_request.hr_data_len = opaque_len;
3788         if (opaque != NULL)
3789                 memcpy(hur_data(hur), opaque, opaque_len);
3790
3791         /* Send the HSM request */
3792         if (realpath(some_file, fullpath) == NULL) {
3793                 fprintf(stderr, "Could not find path '%s': %s\n",
3794                         some_file, strerror(errno));
3795         }
3796         rc = llapi_hsm_request(fullpath, hur);
3797         if (rc) {
3798                 fprintf(stderr, "Cannot send HSM request (use of %s): %s\n",
3799                         some_file, strerror(-rc));
3800                 goto out_free;
3801         }
3802
3803 out_free:
3804         free(hur);
3805         return rc;
3806 }
3807
3808 static int lfs_hsm_archive(int argc, char **argv)
3809 {
3810         return lfs_hsm_request(argc, argv, HUA_ARCHIVE);
3811 }
3812
3813 static int lfs_hsm_restore(int argc, char **argv)
3814 {
3815         return lfs_hsm_request(argc, argv, HUA_RESTORE);
3816 }
3817
3818 static int lfs_hsm_release(int argc, char **argv)
3819 {
3820         return lfs_hsm_request(argc, argv, HUA_RELEASE);
3821 }
3822
3823 static int lfs_hsm_remove(int argc, char **argv)
3824 {
3825         return lfs_hsm_request(argc, argv, HUA_REMOVE);
3826 }
3827
3828 static int lfs_hsm_cancel(int argc, char **argv)
3829 {
3830         return lfs_hsm_request(argc, argv, HUA_CANCEL);
3831 }
3832
3833 static int lfs_swap_layouts(int argc, char **argv)
3834 {
3835         if (argc != 3)
3836                 return CMD_HELP;
3837
3838         return llapi_swap_layouts(argv[1], argv[2], 0, 0,
3839                                   SWAP_LAYOUTS_KEEP_MTIME |
3840                                   SWAP_LAYOUTS_KEEP_ATIME);
3841 }
3842
3843 int main(int argc, char **argv)
3844 {
3845         int rc;
3846
3847         setlinebuf(stdout);
3848
3849         ptl_initialize(argc, argv);
3850         if (obd_initialize(argc, argv) < 0)
3851                 exit(2);
3852
3853         Parser_init("lfs > ", cmdlist);
3854
3855         if (argc > 1) {
3856                 rc = Parser_execarg(argc - 1, argv + 1, cmdlist);
3857         } else {
3858                 rc = Parser_commands();
3859         }
3860
3861         obd_finalize(argc, argv);
3862         return rc < 0 ? -rc : rc;
3863 }
3864
3865 #ifdef _LUSTRE_IDL_H_
3866 /* Everything we need here should be included by lustreapi.h. */
3867 # error "lfs should not depend on lustre_idl.h"
3868 #endif /* _LUSTRE_IDL_H_ */