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