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