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