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