Whamcloud - gitweb
LU-5710 all: second batch of corrected typos and grammar errors
[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 /* Setstripe and migrate share mostly the same parameters */
119 #define SSM_CMD_COMMON(cmd) \
120         "usage: "cmd" [--stripe-count|-c <stripe_count>]\n"             \
121         "                 [--stripe-index|-i <start_ost_idx>]\n"        \
122         "                 [--stripe-size|-S <stripe_size>]\n"           \
123         "                 [--pool|-p <pool_name>]\n"                    \
124         "                 [--ost-list|-o <ost_indices>]\n"
125
126 #define SSM_HELP_COMMON \
127         "\tstripe_size:  Number of bytes on each OST (0 filesystem default)\n" \
128         "\t              Can be specified with k, m or g (in KB, MB and GB\n" \
129         "\t              respectively)\n"                               \
130         "\tstart_ost_idx: OST index of first stripe (-1 default)\n"     \
131         "\tstripe_count: Number of OSTs to stripe over (0 default, -1 all)\n" \
132         "\tpool_name:    Name of OST pool to use (default none)\n"      \
133         "\tost_indices:  List of OST indices, can be repeated multiple times\n"\
134         "\t              Indices be specified in a format of:\n"        \
135         "\t                -o <ost_1>,<ost_i>-<ost_j>,<ost_n>\n"        \
136         "\t              Or:\n"                                         \
137         "\t                -o <ost_1> -o <ost_i>-<ost_j> -o <ost_n>\n"  \
138         "\t              If --pool is set with --ost-list, then the OSTs\n" \
139         "\t              must be the members of the pool."
140
141 #define SETSTRIPE_USAGE                                         \
142         SSM_CMD_COMMON("setstripe")                             \
143         "                 <directory|filename>\n"               \
144         SSM_HELP_COMMON
145
146 #define MIGRATE_USAGE                                                   \
147         SSM_CMD_COMMON("migrate  ")                                     \
148         "                 [--block|-b]\n"                               \
149         "                 <filename>\n"                                 \
150         SSM_HELP_COMMON                                                 \
151         "\n"                                                            \
152         "\tblock:        Block file access during data migration\n"     \
153
154 /* all available commands */
155 command_t cmdlist[] = {
156         {"setstripe", lfs_setstripe, 0,
157          "Create a new file with a specific striping pattern or\n"
158          "set the default striping pattern on an existing directory or\n"
159          "delete the default striping pattern from an existing directory\n"
160          "usage: setstripe -d <directory>   (to delete default striping)\n"\
161          " or\n"
162          SETSTRIPE_USAGE},
163         {"getstripe", lfs_getstripe, 0,
164          "To list the striping info for a given file or files in a\n"
165          "directory or recursively for all files in a directory tree.\n"
166          "usage: getstripe [--ost|-O <uuid>] [--quiet | -q] [--verbose | -v]\n"
167          "                 [--stripe-count|-c] [--stripe-index|-i]\n"
168          "                 [--pool|-p] [--stripe-size|-S] [--directory|-d]\n"
169          "                 [--mdt-index|-M] [--recursive|-r] [--raw|-R]\n"
170          "                 [--layout|-L]\n"
171          "                 <directory|filename> ..."},
172         {"setdirstripe", lfs_setdirstripe, 0,
173          "To create a striped directory on a specified MDT. This can only\n"
174          "be done on MDT0 with the right of administrator.\n"
175          "usage: setdirstripe <--count|-c stripe_count>\n"
176          "              [--index|-i mdt_index] [--hash-type|-t hash_type]\n"
177          "              [--default_stripe|-D ] [--mode|-m mode] <dir>\n"
178          "\tstripe_count: stripe count of the striped directory\n"
179          "\tmdt_index:  MDT index of first stripe\n"
180          "\thash_type:  hash type of the striped directory. Hash types:\n"
181          "      fnv_1a_64 FNV-1a hash algorithm (default)\n"
182          "      all_char  sum of characters % MDT_COUNT (not recommended)\n"
183          "\tdefault_stripe: set default dirstripe of the directory\n"
184          "\tmode: the mode of the directory\n"},
185         {"getdirstripe", lfs_getdirstripe, 0,
186          "To list the striping info for a given directory\n"
187          "or recursively for all directories in a directory tree.\n"
188          "usage: getdirstripe [--obd|-O <uuid>] [--quiet|-q] [--verbose|-v]\n"
189          "               [--count|-c ] [--index|-i ] [--raw|-R]\n"
190          "               [--recursive | -r] [ --default_stripe | -D ] <dir> "},
191         {"mkdir", lfs_setdirstripe, 0,
192          "To create a striped directory on a specified MDT. This can only\n"
193          "be done on MDT0 with the right of administrator.\n"
194          "usage: mkdir <--count|-c stripe_count>\n"
195          "              [--index|-i mdt_index] [--hash-type|-t hash_type]\n"
196          "              [--default_stripe|-D ] [--mode|-m mode] <dir>\n"
197          "\tstripe_count: stripe count of the striped directory\n"
198          "\tmdt_index:  MDT index of first stripe\n"
199          "\thash_type:  hash type of the striped directory. Hash types:\n"
200          "      fnv_1a_64 FNV-1a hash algorithm (default)\n"
201          "      all_char  sum of characters % MDT_COUNT (not recommended)\n"
202          "\tdefault_stripe: set default dirstripe of the directory\n"
203          "\tmode: the mode of the directory\n"},
204         {"rm_entry", lfs_rmentry, 0,
205          "To remove the name entry of the remote directory. Note: This\n"
206          "command will only delete the name entry, i.e. the remote directory\n"
207          "will become inaccessable after this command. This can only be done\n"
208          "by the administrator\n"
209          "usage: rm_entry <dir>\n"},
210         {"pool_list", lfs_poollist, 0,
211          "List pools or pool OSTs\n"
212          "usage: pool_list <fsname>[.<pool>] | <pathname>\n"},
213         {"find", lfs_find, 0,
214          "find files matching given attributes recursively in directory tree.\n"
215          "usage: find <directory|filename> ...\n"
216          "     [[!] --atime|-A [+-]N] [[!] --ctime|-C [+-]N]\n"
217          "     [[!] --mtime|-M [+-]N] [[!] --mdt|-m <uuid|index,...>]\n"
218          "     [--maxdepth|-D N] [[!] --name|-n <pattern>]\n"
219          "     [[!] --ost|-O <uuid|index,...>] [--print|-p] [--print0|-P]\n"
220          "     [[!] --size|-s [+-]N[bkMGTPE]]\n"
221          "     [[!] --stripe-count|-c [+-]<stripes>]\n"
222          "     [[!] --stripe-index|-i <index,...>]\n"
223          "     [[!] --stripe-size|-S [+-]N[kMGT]] [[!] --type|-t <filetype>]\n"
224          "     [[!] --gid|-g|--group|-G <gid>|<gname>]\n"
225          "     [[!] --uid|-u|--user|-U <uid>|<uname>] [[!] --pool <pool>]\n"
226          "     [[!] --layout|-L released,raid0]\n"
227          "\t !: used before an option indicates 'NOT' requested attribute\n"
228          "\t -: used before a value indicates 'AT MOST' requested value\n"
229          "\t +: used before a value indicates 'AT LEAST' requested value\n"},
230         {"check", lfs_check, 0,
231          "Display the status of MDS or OSTs (as specified in the command)\n"
232          "or all the servers (MDS and OSTs).\n"
233          "usage: check <osts|mds|servers>"},
234         {"join", lfs_join, 0,
235          "join two lustre files into one.\n"
236          "obsolete, HEAD does not support it anymore.\n"},
237         {"osts", lfs_osts, 0, "list OSTs connected to client "
238          "[for specified path only]\n" "usage: osts [path]"},
239         {"mdts", lfs_mdts, 0, "list MDTs connected to client "
240          "[for specified path only]\n" "usage: mdts [path]"},
241         {"df", lfs_df, 0,
242          "report filesystem disk space usage or inodes usage"
243          "of each MDS and all OSDs or a batch belonging to a specific pool .\n"
244          "Usage: df [-i] [-h] [--lazy|-l] [--pool|-p <fsname>[.<pool>] [path]"},
245         {"getname", lfs_getname, 0, "list instances and specified mount points "
246          "[for specified path only]\n"
247          "Usage: getname [-h]|[path ...] "},
248 #ifdef HAVE_SYS_QUOTA_H
249         {"quotacheck", lfs_quotacheck, 0,
250          "Scan the specified filesystem for disk usage, and create,\n"
251          "or update quota files. Deprecated as of 2.4.0.\n"
252          "usage: quotacheck [ -ug ] <filesystem>"},
253         {"quotaon", lfs_quotaon, 0, "Turn filesystem"
254          " quotas on. Deprecated as of 2.4.0.\n"
255          "usage: quotaon [ -ugf ] <filesystem>"},
256         {"quotaoff", lfs_quotaoff, 0, "Turn filesystem"
257          " quotas off. Deprecated as of 2.4.0.\n"
258          "usage: quotaoff [ -ug ] <filesystem>"},
259         {"setquota", lfs_setquota, 0, "Set filesystem quotas.\n"
260          "usage: setquota <-u|-g> <uname>|<uid>|<gname>|<gid>\n"
261          "                -b <block-softlimit> -B <block-hardlimit>\n"
262          "                -i <inode-softlimit> -I <inode-hardlimit> <filesystem>\n"
263          "       setquota <-u|--user|-g|--group> <uname>|<uid>|<gname>|<gid>\n"
264          "                [--block-softlimit <block-softlimit>]\n"
265          "                [--block-hardlimit <block-hardlimit>]\n"
266          "                [--inode-softlimit <inode-softlimit>]\n"
267          "                [--inode-hardlimit <inode-hardlimit>] <filesystem>\n"
268          "       setquota [-t] <-u|--user|-g|--group>\n"
269          "                [--block-grace <block-grace>]\n"
270          "                [--inode-grace <inode-grace>] <filesystem>\n"
271          "       -b can be used instead of --block-softlimit/--block-grace\n"
272          "       -B can be used instead of --block-hardlimit\n"
273          "       -i can be used instead of --inode-softlimit/--inode-grace\n"
274          "       -I can be used instead of --inode-hardlimit\n\n"
275          "Note: The total quota space will be split into many qunits and\n"
276          "      balanced over all server targets, the minimal qunit size is\n"
277          "      1M bytes for block space and 1K inodes for inode space.\n\n"
278          "      Quota space rebalancing process will stop when this mininum\n"
279          "      value is reached. As a result, quota exceeded can be returned\n"
280          "      while many targets still have 1MB or 1K inodes of spare\n"
281          "      quota space."},
282         {"quota", lfs_quota, 0, "Display disk usage and limits.\n"
283          "usage: quota [-q] [-v] [-h] [-o <obd_uuid>|-i <mdt_idx>|-I "
284                        "<ost_idx>]\n"
285          "             [<-u|-g> <uname>|<uid>|<gname>|<gid>] <filesystem>\n"
286          "       quota [-o <obd_uuid>|-i <mdt_idx>|-I <ost_idx>] -t <-u|-g> <filesystem>"},
287 #endif
288         {"flushctx", lfs_flushctx, 0, "Flush security context for current user.\n"
289          "usage: flushctx [-k] [mountpoint...]"},
290         {"lsetfacl", lfs_lsetfacl, 0,
291          "Remote user setfacl for user/group on the same remote client.\n"
292          "usage: lsetfacl [-bkndRLPvh] [{-m|-x} acl_spec] [{-M|-X} acl_file] file ..."},
293         {"lgetfacl", lfs_lgetfacl, 0,
294          "Remote user getfacl for user/group on the same remote client.\n"
295          "usage: lgetfacl [-dRLPvh] file ..."},
296         {"rsetfacl", lfs_rsetfacl, 0,
297          "Remote user setfacl for user/group on other clients.\n"
298          "usage: rsetfacl [-bkndRLPvh] [{-m|-x} acl_spec] [{-M|-X} acl_file] file ..."},
299         {"rgetfacl", lfs_rgetfacl, 0,
300          "Remote user getfacl for user/group on other clients.\n"
301          "usage: rgetfacl [-dRLPvh] file ..."},
302         {"cp", lfs_cp, 0,
303          "Remote user copy files and directories.\n"
304          "usage: cp [OPTION]... [-T] SOURCE DEST\n\tcp [OPTION]... SOURCE... DIRECTORY\n\tcp [OPTION]... -t DIRECTORY SOURCE..."},
305         {"ls", lfs_ls, 0,
306          "Remote user list directory contents.\n"
307          "usage: ls [OPTION]... [FILE]..."},
308         {"changelog", lfs_changelog, 0,
309          "Show the metadata changes on an MDT."
310          "\nusage: changelog <mdtname> [startrec [endrec]]"},
311         {"changelog_clear", lfs_changelog_clear, 0,
312          "Indicate that old changelog records up to <endrec> are no longer of "
313          "interest to consumer <id>, allowing the system to free up space.\n"
314          "An <endrec> of 0 means all records.\n"
315          "usage: changelog_clear <mdtname> <id> <endrec>"},
316         {"fid2path", lfs_fid2path, 0,
317          "Resolve the full path(s) for given FID(s). For a specific hardlink "
318          "specify link number <linkno>.\n"
319         /* "For a historical link name, specify changelog record <recno>.\n" */
320          "usage: fid2path [--link <linkno>] <fsname|rootpath> <fid> ..."
321                 /* [ --rec <recno> ] */ },
322         {"path2fid", lfs_path2fid, 0, "Display the fid(s) for a given path(s).\n"
323          "usage: path2fid [--parents] <path> ..."},
324         {"data_version", lfs_data_version, 0, "Display file data version for "
325          "a given path.\n" "usage: data_version -[n|r|w] <path>"},
326         {"hsm_state", lfs_hsm_state, 0, "Display the HSM information (states, "
327          "undergoing actions) for given files.\n usage: hsm_state <file> ..."},
328         {"hsm_set", lfs_hsm_set, 0, "Set HSM user flag on specified files.\n"
329          "usage: hsm_set [--norelease] [--noarchive] [--dirty] [--exists] "
330          "[--archived] [--lost] <file> ..."},
331         {"hsm_clear", lfs_hsm_clear, 0, "Clear HSM user flag on specified "
332          "files.\n"
333          "usage: hsm_clear [--norelease] [--noarchive] [--dirty] [--exists] "
334          "[--archived] [--lost] <file> ..."},
335         {"hsm_action", lfs_hsm_action, 0, "Display current HSM request for "
336          "given files.\n" "usage: hsm_action <file> ..."},
337         {"hsm_archive", lfs_hsm_archive, 0,
338          "Archive file to external storage.\n"
339          "usage: hsm_archive [--filelist FILELIST] [--data DATA] [--archive NUM] "
340          "<file> ..."},
341         {"hsm_restore", lfs_hsm_restore, 0,
342          "Restore file from external storage.\n"
343          "usage: hsm_restore [--filelist FILELIST] [--data DATA] <file> ..."},
344         {"hsm_release", lfs_hsm_release, 0,
345          "Release files from Lustre.\n"
346          "usage: hsm_release [--filelist FILELIST] [--data DATA] <file> ..."},
347         {"hsm_remove", lfs_hsm_remove, 0,
348          "Remove file copy from external storage.\n"
349          "usage: hsm_remove [--filelist FILELIST] [--data DATA] <file> ..."},
350         {"hsm_cancel", lfs_hsm_cancel, 0,
351          "Cancel requests related to specified files.\n"
352          "usage: hsm_cancel [--filelist FILELIST] [--data DATA] <file> ..."},
353         {"swap_layouts", lfs_swap_layouts, 0, "Swap layouts between 2 files.\n"
354          "usage: swap_layouts <path1> <path2>"},
355         {"migrate", lfs_setstripe, 0, "migrate file from one OST layout to "
356          "another (may be not safe with concurrent writes).\n"
357          MIGRATE_USAGE},
358         {"mv", lfs_mv, 0,
359          "To move directories between MDTs.\n"
360          "usage: mv <directory|filename> [--mdt-index|-M] <mdt_index> "
361          "[--verbose|-v]\n"},
362         {"help", Parser_help, 0, "help"},
363         {"exit", Parser_quit, 0, "quit"},
364         {"quit", Parser_quit, 0, "quit"},
365         {"--version", Parser_version, 0,
366          "output build version of the utility and exit"},
367         { 0, 0, 0, NULL }
368 };
369
370 #define MIGRATION_BLOCKS 1
371
372 static int lfs_migrate(char *name, __u64 migration_flags,
373                        struct llapi_stripe_param *param)
374 {
375         int                      fd, fdv;
376         char                     volatile_file[PATH_MAX +
377                                                 LUSTRE_VOLATILE_HDR_LEN + 4];
378         char                     parent[PATH_MAX];
379         char                    *ptr;
380         int                      rc;
381         __u64                    dv1;
382         struct lov_user_md      *lum = NULL;
383         int                      lumsz;
384         int                      bufsz;
385         void                    *buf = NULL;
386         int                      rsize, wsize;
387         __u64                    rpos, wpos, bufoff;
388         int                      gid;
389         int                      have_gl = 0;
390         struct stat              st, stv;
391
392         /* find the right size for the IO and allocate the buffer */
393         lumsz = lov_user_md_size(LOV_MAX_STRIPE_COUNT, LOV_USER_MAGIC_V3);
394         lum = malloc(lumsz);
395         if (lum == NULL) {
396                 rc = -ENOMEM;
397                 goto free;
398         }
399
400         rc = llapi_file_get_stripe(name, lum);
401         /* failure can happen for many reasons and some may be not real errors
402          * (eg: no stripe)
403          * in case of a real error, a later call will fail with better
404          * error management */
405         if (rc < 0)
406                 bufsz = 1024*1024;
407         else
408                 bufsz = lum->lmm_stripe_size;
409         rc = posix_memalign(&buf, getpagesize(), bufsz);
410         if (rc != 0) {
411                 rc = -rc;
412                 goto free;
413         }
414
415         /* search for file directory pathname */
416         if (strlen(name) > sizeof(parent)-1) {
417                 rc = -E2BIG;
418                 goto free;
419         }
420         strncpy(parent, name, sizeof(parent));
421         ptr = strrchr(parent, '/');
422         if (ptr == NULL) {
423                 if (getcwd(parent, sizeof(parent)) == NULL) {
424                         rc = -errno;
425                         goto free;
426                 }
427         } else {
428                 if (ptr == parent)
429                         strcpy(parent, "/");
430                 else
431                         *ptr = '\0';
432         }
433         rc = snprintf(volatile_file, sizeof(volatile_file), "%s/%s::", parent,
434                       LUSTRE_VOLATILE_HDR);
435         if (rc >= sizeof(volatile_file)) {
436                 rc = -E2BIG;
437                 goto free;
438         }
439
440         /* create, open a volatile file, use caching (ie no directio) */
441         /* exclusive create is not needed because volatile files cannot
442          * conflict on name by construction */
443         fdv = llapi_file_open_param(volatile_file, O_CREAT | O_WRONLY, 0644,
444                                     param);
445         if (fdv < 0) {
446                 rc = fdv;
447                 fprintf(stderr, "cannot create volatile file in %s (%s)\n",
448                         parent, strerror(-rc));
449                 goto free;
450         }
451
452         /* open file, direct io */
453         /* even if the file is only read, WR mode is nedeed to allow
454          * layout swap on fd */
455         fd = open(name, O_RDWR | O_DIRECT);
456         if (fd == -1) {
457                 rc = -errno;
458                 fprintf(stderr, "cannot open %s (%s)\n", name, strerror(-rc));
459                 close(fdv);
460                 goto free;
461         }
462
463         /* Not-owner (root?) special case.
464          * Need to set owner/group of volatile file like original.
465          * This will allow to pass related check during layout_swap.
466          */
467         rc = fstat(fd, &st);
468         if (rc != 0) {
469                 rc = -errno;
470                 fprintf(stderr, "cannot stat %s (%s)\n", name,
471                         strerror(errno));
472                 goto error;
473         }
474         rc = fstat(fdv, &stv);
475         if (rc != 0) {
476                 rc = -errno;
477                 fprintf(stderr, "cannot stat %s (%s)\n", volatile_file,
478                         strerror(errno));
479                 goto error;
480         }
481         if (st.st_uid != stv.st_uid || st.st_gid != stv.st_gid) {
482                 rc = fchown(fdv, st.st_uid, st.st_gid);
483                 if (rc != 0) {
484                         rc = -errno;
485                         fprintf(stderr, "cannot chown %s (%s)\n", name,
486                                 strerror(errno));
487                         goto error;
488                 }
489         }
490
491         /* get file data version */
492         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
493         if (rc != 0) {
494                 fprintf(stderr, "cannot get dataversion on %s (%s)\n",
495                         name, strerror(-rc));
496                 goto error;
497         }
498
499         do
500                 gid = random();
501         while (gid == 0);
502         if (migration_flags & MIGRATION_BLOCKS) {
503                 /* take group lock to limit concurrent access
504                  * this will be no more needed when exclusive access will
505                  * be implemented (see LU-2919) */
506                 /* group lock is taken after data version read because it
507                  * blocks data version call */
508                 rc = llapi_group_lock(fd, gid);
509                 if (rc < 0) {
510                         fprintf(stderr, "cannot get group lock on %s (%s)\n",
511                                 name, strerror(-rc));
512                         goto error;
513                 }
514                 have_gl = 1;
515         }
516
517         /* copy data */
518         rpos = 0;
519         wpos = 0;
520         bufoff = 0;
521         rsize = -1;
522         do {
523                 /* read new data only if we have written all
524                  * previously read data */
525                 if (wpos == rpos) {
526                         rsize = read(fd, buf, bufsz);
527                         if (rsize < 0) {
528                                 rc = -errno;
529                                 fprintf(stderr, "read failed on %s"
530                                         " (%s)\n", name,
531                                         strerror(-rc));
532                                 goto error;
533                         }
534                         rpos += rsize;
535                         bufoff = 0;
536                 }
537                 /* eof ? */
538                 if (rsize == 0)
539                         break;
540                 wsize = write(fdv, buf + bufoff, rpos - wpos);
541                 if (wsize < 0) {
542                         rc = -errno;
543                         fprintf(stderr, "write failed on volatile"
544                                 " for %s (%s)\n", name, strerror(-rc));
545                         goto error;
546                 }
547                 wpos += wsize;
548                 bufoff += wsize;
549         } while (1);
550
551         /* flush data */
552         fsync(fdv);
553
554         if (migration_flags & MIGRATION_BLOCKS) {
555                 /* give back group lock */
556                 rc = llapi_group_unlock(fd, gid);
557                 if (rc < 0)
558                         fprintf(stderr, "cannot put group lock on %s (%s)\n",
559                                 name, strerror(-rc));
560                 have_gl = 0;
561         }
562
563         /* swap layouts
564          * for a migration we need to:
565          * - check data version on file did not change
566          * - keep file mtime
567          * - keep file atime
568          */
569         rc = llapi_fswap_layouts(fd, fdv, dv1, 0,
570                                  SWAP_LAYOUTS_CHECK_DV1 |
571                                  SWAP_LAYOUTS_KEEP_MTIME |
572                                  SWAP_LAYOUTS_KEEP_ATIME);
573         if (rc == -EAGAIN) {
574                 fprintf(stderr, "%s: dataversion changed during copy, "
575                         "migration aborted\n", name);
576                 goto error;
577         }
578         if (rc != 0)
579                 fprintf(stderr, "%s: swap layout to new file failed: %s\n",
580                         name, strerror(-rc));
581
582 error:
583         /* give back group lock */
584         if ((migration_flags & MIGRATION_BLOCKS) && have_gl) {
585                 int rc2;
586
587                 /* we keep the original error in rc */
588                 rc2 = llapi_group_unlock(fd, gid);
589                 if (rc2 < 0)
590                         fprintf(stderr, "cannot put group lock on %s (%s)\n",
591                                 name, strerror(-rc2));
592         }
593
594         close(fdv);
595         close(fd);
596 free:
597         if (lum)
598                 free(lum);
599         if (buf)
600                 free(buf);
601         return rc;
602 }
603
604 /**
605  * Parse a string containing an OST index list into an array of integers.
606  *
607  * The input string contains a comma delimited list of individual
608  * indices and ranges, for example "1,2-4,7". Add the indices into the
609  * \a osts array and remove duplicates.
610  *
611  * \param[out] osts    array to store indices in
612  * \param[in] size     size of \a osts array
613  * \param[in] offset   starting index in \a osts
614  * \param[in] arg      string containing OST index list
615  *
616  * \retval positive    number of indices in \a osts
617  * \retval -EINVAL     unable to parse \a arg
618  */
619 static int parse_targets(__u32 *osts, int size, int offset, char *arg)
620 {
621         int rc;
622         int nr = offset;
623         int slots = size - offset;
624         char *ptr = NULL;
625         bool end_of_loop;
626
627         if (arg == NULL)
628                 return -EINVAL;
629
630         end_of_loop = false;
631         while (!end_of_loop) {
632                 int start_index;
633                 int end_index;
634                 int i;
635                 char *endptr = NULL;
636
637                 rc = -EINVAL;
638
639                 ptr = strchrnul(arg, ',');
640
641                 end_of_loop = *ptr == '\0';
642                 *ptr = '\0';
643
644                 start_index = strtol(arg, &endptr, 0);
645                 if (endptr == arg) /* no data at all */
646                         break;
647                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
648                         break;
649                 if (start_index < 0)
650                         break;
651
652                 end_index = start_index;
653                 if (*endptr == '-') {
654                         end_index = strtol(endptr + 1, &endptr, 0);
655                         if (*endptr != '\0')
656                                 break;
657                         if (end_index < start_index)
658                                 break;
659                 }
660
661                 for (i = start_index; i <= end_index && slots > 0; i++) {
662                         int j;
663
664                         /* remove duplicate */
665                         for (j = 0; j < offset; j++) {
666                                 if (osts[j] == i)
667                                         break;
668                         }
669                         if (j == offset) { /* no duplicate */
670                                 osts[nr++] = i;
671                                 --slots;
672                         }
673                 }
674                 if (slots == 0 && i < end_index)
675                         break;
676
677                 *ptr = ',';
678                 arg = ++ptr;
679                 offset = nr;
680                 rc = 0;
681         }
682         if (!end_of_loop && ptr != NULL)
683                 *ptr = ',';
684
685         return rc < 0 ? rc : nr;
686 }
687
688 /* functions */
689 static int lfs_setstripe(int argc, char **argv)
690 {
691         struct llapi_stripe_param       *param;
692         char                            *fname;
693         int                              result;
694         unsigned long long               st_size;
695         int                              st_offset, st_count;
696         char                            *end;
697         int                              c;
698         int                              delete = 0;
699         char                            *stripe_size_arg = NULL;
700         char                            *stripe_off_arg = NULL;
701         char                            *stripe_count_arg = NULL;
702         char                            *pool_name_arg = NULL;
703         unsigned long long               size_units = 1;
704         bool                             migrate_mode = false;
705         __u64                            migration_flags = 0;
706         __u32                            osts[LOV_MAX_STRIPE_COUNT] = { 0 };
707         int                              nr_osts = 0;
708
709         struct option            long_opts[] = {
710                 /* valid only in migrate mode */
711                 {"block",        no_argument,       0, 'b'},
712 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
713                 /* This formerly implied "stripe-count", but was explicitly
714                  * made "stripe-count" for consistency with other options,
715                  * and to separate it from "mdt-count" when DNE arrives. */
716                 {"count",        required_argument, 0, 'c'},
717 #endif
718                 {"stripe-count", required_argument, 0, 'c'},
719                 {"stripe_count", required_argument, 0, 'c'},
720                 {"delete",       no_argument,       0, 'd'},
721 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
722                 /* This formerly implied "stripe-index", but was explicitly
723                  * made "stripe-index" for consistency with other options,
724                  * and to separate it from "mdt-index" when DNE arrives. */
725                 {"index",        required_argument, 0, 'i'},
726 #endif
727                 {"stripe-index", required_argument, 0, 'i'},
728                 {"stripe_index", required_argument, 0, 'i'},
729                 {"ost-list",     required_argument, 0, 'o'},
730                 {"ost_list",     required_argument, 0, 'o'},
731                 {"pool",         required_argument, 0, 'p'},
732 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
733                 /* This formerly implied "--stripe-size", but was confusing
734                  * with "lfs find --size|-s", which means "file size", so use
735                  * the consistent "--stripe-size|-S" for all commands. */
736                 {"size",         required_argument, 0, 's'},
737 #endif
738                 {"stripe-size",  required_argument, 0, 'S'},
739                 {"stripe_size",  required_argument, 0, 'S'},
740                 {0, 0, 0, 0}
741         };
742
743         st_size = 0;
744         st_offset = -1;
745         st_count = 0;
746
747         if (strcmp(argv[0], "migrate") == 0)
748                 migrate_mode = true;
749
750         while ((c = getopt_long(argc, argv, "bc:di:o:p:s:S:",
751                                 long_opts, NULL)) >= 0) {
752                 switch (c) {
753                 case 0:
754                         /* Long options. */
755                         break;
756                 case 'b':
757                         if (!migrate_mode) {
758                                 fprintf(stderr, "--block is valid only for"
759                                                 " migrate mode");
760                                 return CMD_HELP;
761                         }
762                         migration_flags |= MIGRATION_BLOCKS;
763                         break;
764                 case 'c':
765 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 6, 53, 0)
766                         if (strcmp(argv[optind - 1], "--count") == 0)
767                                 fprintf(stderr, "warning: '--count' deprecated"
768                                         ", use '--stripe-count' instead\n");
769 #endif
770                         stripe_count_arg = optarg;
771                         break;
772                 case 'd':
773                         /* delete the default striping pattern */
774                         delete = 1;
775                         break;
776                 case 'o':
777                         nr_osts = parse_targets(osts, ARRAY_SIZE(osts), nr_osts,
778                                                 optarg);
779                         if (nr_osts < 0) {
780                                 fprintf(stderr,
781                                         "error: %s: bad OST indices '%s'\n",
782                                         argv[0], optarg);
783                                 return CMD_HELP;
784                         }
785
786                         if (st_offset == -1) /* first in the command line */
787                                 st_offset = osts[0];
788                         break;
789                 case 'i':
790 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 6, 53, 0)
791                         if (strcmp(argv[optind - 1], "--index") == 0)
792                                 fprintf(stderr, "warning: '--index' deprecated"
793                                         ", use '--stripe-index' instead\n");
794 #endif
795                         stripe_off_arg = optarg;
796                         break;
797 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
798                 case 's':
799 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 6, 53, 0)
800                         fprintf(stderr, "warning: '--size|-s' deprecated, "
801                                 "use '--stripe-size|-S' instead\n");
802 #endif
803 #endif /* LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0) */
804                 case 'S':
805                         stripe_size_arg = optarg;
806                         break;
807                 case 'p':
808                         pool_name_arg = optarg;
809                         break;
810                 default:
811                         return CMD_HELP;
812                 }
813         }
814
815         fname = argv[optind];
816
817         if (delete &&
818             (stripe_size_arg != NULL || stripe_off_arg != NULL ||
819              stripe_count_arg != NULL || pool_name_arg != NULL)) {
820                 fprintf(stderr, "error: %s: cannot specify -d with "
821                         "-s, -c, -o, or -p options\n",
822                         argv[0]);
823                 return CMD_HELP;
824         }
825
826         if (optind == argc) {
827                 fprintf(stderr, "error: %s: missing filename|dirname\n",
828                         argv[0]);
829                 return CMD_HELP;
830         }
831
832         if (pool_name_arg && strlen(pool_name_arg) > LOV_MAXPOOLNAME) {
833                 fprintf(stderr,
834                         "error: %s: pool name '%s' is too long (max is %d characters)\n",
835                         argv[0], pool_name_arg, LOV_MAXPOOLNAME);
836                 return CMD_HELP;
837         }
838
839         /* get the stripe size */
840         if (stripe_size_arg != NULL) {
841                 result = llapi_parse_size(stripe_size_arg, &st_size,
842                                           &size_units, 0);
843                 if (result) {
844                         fprintf(stderr, "error: %s: bad stripe size '%s'\n",
845                                 argv[0], stripe_size_arg);
846                         return CMD_HELP;
847                 }
848         }
849         /* get the stripe offset */
850         if (stripe_off_arg != NULL) {
851                 st_offset = strtol(stripe_off_arg, &end, 0);
852                 if (*end != '\0') {
853                         fprintf(stderr, "error: %s: bad stripe offset '%s'\n",
854                                 argv[0], stripe_off_arg);
855                         return CMD_HELP;
856                 }
857         }
858         /* get the stripe count */
859         if (stripe_count_arg != NULL) {
860                 st_count = strtoul(stripe_count_arg, &end, 0);
861                 if (*end != '\0') {
862                         fprintf(stderr, "error: %s: bad stripe count '%s'\n",
863                                 argv[0], stripe_count_arg);
864                         return CMD_HELP;
865                 }
866         }
867
868         /* initialize stripe parameters */
869         param = calloc(1, offsetof(typeof(*param), lsp_osts[nr_osts]));
870         if (param == NULL) {
871                 fprintf(stderr, "error: %s: run out of memory\n", argv[0]);
872                 return CMD_HELP;
873         }
874
875         param->lsp_stripe_size = st_size;
876         param->lsp_stripe_offset = st_offset;
877         param->lsp_stripe_count = st_count;
878         param->lsp_stripe_pattern = 0;
879         param->lsp_pool = pool_name_arg;
880         param->lsp_is_specific = false;
881         if (nr_osts > 0) {
882                 if (st_count > 0 && nr_osts != st_count) {
883                         fprintf(stderr, "error: %s: stripe count '%d' doesn't "
884                                 "match the number of OSTs: %d\n",
885                                 argv[0], st_count, nr_osts);
886                         return CMD_HELP;
887                 }
888
889                 param->lsp_is_specific = true;
890                 param->lsp_stripe_count = nr_osts;
891                 memcpy(param->lsp_osts, osts, sizeof(*osts) * nr_osts);
892         }
893
894         do {
895                 if (!migrate_mode) {
896                         result = llapi_file_open_param(fname,
897                                                        O_CREAT | O_WRONLY,
898                                                        0644, param);
899                         if (result >= 0) {
900                                 close(result);
901                                 result = 0;
902                         }
903                 } else {
904                         result = lfs_migrate(fname, migration_flags, param);
905                 }
906                 if (result) {
907                         fprintf(stderr,
908                                 "error: %s: %s stripe file '%s' failed\n",
909                                 argv[0], migrate_mode ? "migrate" : "create",
910                                 fname);
911                         break;
912                 }
913                 fname = argv[++optind];
914         } while (fname != NULL);
915
916         free(param);
917         return result;
918 }
919
920 static int lfs_poollist(int argc, char **argv)
921 {
922         if (argc != 2)
923                 return CMD_HELP;
924
925         return llapi_poollist(argv[1]);
926 }
927
928 static int set_time(time_t *time, time_t *set, char *str)
929 {
930         time_t t;
931         int res = 0;
932
933         if (str[0] == '+')
934                 res = 1;
935         else if (str[0] == '-')
936                 res = -1;
937
938         if (res)
939                 str++;
940
941         t = strtol(str, NULL, 0);
942         if (*time < t * 24 * 60 * 60) {
943                 if (res)
944                         str--;
945                 fprintf(stderr, "Wrong time '%s' is specified.\n", str);
946                 return INT_MAX;
947         }
948
949         *set = *time - t * 24 * 60 * 60;
950         return res;
951 }
952
953 #define USER 0
954 #define GROUP 1
955
956 static int name2id(unsigned int *id, char *name, int type)
957 {
958         if (type == USER) {
959                 struct passwd *entry;
960
961                 if (!(entry = getpwnam(name))) {
962                         if (!errno)
963                                 errno = ENOENT;
964                         return -1;
965                 }
966
967                 *id = entry->pw_uid;
968         } else {
969                 struct group *entry;
970
971                 if (!(entry = getgrnam(name))) {
972                         if (!errno)
973                                 errno = ENOENT;
974                         return -1;
975                 }
976
977                 *id = entry->gr_gid;
978         }
979
980         return 0;
981 }
982
983 static int id2name(char **name, unsigned int id, int type)
984 {
985         if (type == USER) {
986                 struct passwd *entry;
987
988                 if (!(entry = getpwuid(id))) {
989                         if (!errno)
990                                 errno = ENOENT;
991                         return -1;
992                 }
993
994                 *name = entry->pw_name;
995         } else {
996                 struct group *entry;
997
998                 if (!(entry = getgrgid(id))) {
999                         if (!errno)
1000                                 errno = ENOENT;
1001                         return -1;
1002                 }
1003
1004                 *name = entry->gr_name;
1005         }
1006
1007         return 0;
1008 }
1009
1010 static int name2layout(__u32 *layout, char *name)
1011 {
1012         char *ptr, *lyt;
1013
1014         *layout = 0;
1015         for (ptr = name; ; ptr = NULL) {
1016                 lyt = strtok(ptr, ",");
1017                 if (lyt == NULL)
1018                         break;
1019                 if (strcmp(lyt, "released") == 0)
1020                         *layout |= LOV_PATTERN_F_RELEASED;
1021                 else if (strcmp(lyt, "raid0") == 0)
1022                         *layout |= LOV_PATTERN_RAID0;
1023                 else
1024                         return -1;
1025         }
1026         return 0;
1027 }
1028
1029 #define FIND_POOL_OPT 3
1030 static int lfs_find(int argc, char **argv)
1031 {
1032         int c, rc;
1033         int ret = 0;
1034         time_t t;
1035         struct find_param param = {
1036                 .fp_max_depth = -1,
1037                 .fp_quiet = 1,
1038         };
1039         struct option long_opts[] = {
1040                 {"atime",        required_argument, 0, 'A'},
1041                 {"stripe-count", required_argument, 0, 'c'},
1042                 {"stripe_count", required_argument, 0, 'c'},
1043                 {"ctime",        required_argument, 0, 'C'},
1044                 {"maxdepth",     required_argument, 0, 'D'},
1045                 {"gid",          required_argument, 0, 'g'},
1046                 {"group",        required_argument, 0, 'G'},
1047                 {"stripe-index", required_argument, 0, 'i'},
1048                 {"stripe_index", required_argument, 0, 'i'},
1049                 {"layout",       required_argument, 0, 'L'},
1050                 {"mdt",          required_argument, 0, 'm'},
1051                 {"mtime",        required_argument, 0, 'M'},
1052                 {"name",         required_argument, 0, 'n'},
1053      /* reserve {"or",           no_argument,     , 0, 'o'}, to match find(1) */
1054                 {"obd",          required_argument, 0, 'O'},
1055                 {"ost",          required_argument, 0, 'O'},
1056                 /* no short option for pool, p/P already used */
1057                 {"pool",         required_argument, 0, FIND_POOL_OPT},
1058                 {"print0",       no_argument,       0, 'p'},
1059                 {"print",        no_argument,       0, 'P'},
1060                 {"size",         required_argument, 0, 's'},
1061                 {"stripe-size",  required_argument, 0, 'S'},
1062                 {"stripe_size",  required_argument, 0, 'S'},
1063                 {"type",         required_argument, 0, 't'},
1064                 {"uid",          required_argument, 0, 'u'},
1065                 {"user",         required_argument, 0, 'U'},
1066                 {0, 0, 0, 0}
1067         };
1068         int pathstart = -1;
1069         int pathend = -1;
1070         int neg_opt = 0;
1071         time_t *xtime;
1072         int *xsign;
1073         int isoption;
1074         char *endptr;
1075
1076         time(&t);
1077
1078         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
1079         while ((c = getopt_long_only(argc, argv,
1080                                      "-A:c:C:D:g:G:i:L:m:M:n:O:Ppqrs:S:t:u:U:v",
1081                                      long_opts, NULL)) >= 0) {
1082                 xtime = NULL;
1083                 xsign = NULL;
1084                 if (neg_opt)
1085                         --neg_opt;
1086                 /* '!' is part of option */
1087                 /* when getopt_long_only() finds a string which is not
1088                  * an option nor a known option argument it returns 1
1089                  * in that case if we already have found pathstart and pathend
1090                  * (i.e. we have the list of pathnames),
1091                  * the only supported value is "!"
1092                  */
1093                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
1094                 if (!isoption && pathend != -1) {
1095                         fprintf(stderr, "err: %s: filename|dirname must either "
1096                                         "precede options or follow options\n",
1097                                         argv[0]);
1098                         ret = CMD_HELP;
1099                         goto err;
1100                 }
1101                 if (!isoption && pathstart == -1)
1102                         pathstart = optind - 1;
1103                 if (isoption && pathstart != -1 && pathend == -1)
1104                         pathend = optind - 2;
1105                 switch (c) {
1106                 case 0:
1107                         /* Long options. */
1108                         break;
1109                 case 1:
1110                         /* unknown; opt is "!" or path component,
1111                          * checking done above.
1112                          */
1113                         if (strcmp(optarg, "!") == 0)
1114                                 neg_opt = 2;
1115                         break;
1116                 case 'A':
1117                         xtime = &param.fp_atime;
1118                         xsign = &param.fp_asign;
1119                         param.fp_exclude_atime = !!neg_opt;
1120                         /* no break, this falls through to 'C' for ctime */
1121                 case 'C':
1122                         if (c == 'C') {
1123                                 xtime = &param.fp_ctime;
1124                                 xsign = &param.fp_csign;
1125                                 param.fp_exclude_ctime = !!neg_opt;
1126                         }
1127                         /* no break, this falls through to 'M' for mtime */
1128                 case 'M':
1129                         if (c == 'M') {
1130                                 xtime = &param.fp_mtime;
1131                                 xsign = &param.fp_msign;
1132                                 param.fp_exclude_mtime = !!neg_opt;
1133                         }
1134                         rc = set_time(&t, xtime, optarg);
1135                         if (rc == INT_MAX) {
1136                                 ret = -1;
1137                                 goto err;
1138                         }
1139                         if (rc)
1140                                 *xsign = rc;
1141                         break;
1142                 case 'c':
1143                         if (optarg[0] == '+') {
1144                                 param.fp_stripe_count_sign = -1;
1145                                 optarg++;
1146                         } else if (optarg[0] == '-') {
1147                                 param.fp_stripe_count_sign =  1;
1148                                 optarg++;
1149                         }
1150
1151                         param.fp_stripe_count = strtoul(optarg, &endptr, 0);
1152                         if (*endptr != '\0') {
1153                                 fprintf(stderr,"error: bad stripe_count '%s'\n",
1154                                         optarg);
1155                                 ret = -1;
1156                                 goto err;
1157                         }
1158                         param.fp_check_stripe_count = 1;
1159                         param.fp_exclude_stripe_count = !!neg_opt;
1160                         break;
1161                 case 'D':
1162                         param.fp_max_depth = strtol(optarg, 0, 0);
1163                         break;
1164                 case 'g':
1165                 case 'G':
1166                         rc = name2id(&param.fp_gid, optarg, GROUP);
1167                         if (rc) {
1168                                 param.fp_gid = strtoul(optarg, &endptr, 10);
1169                                 if (*endptr != '\0') {
1170                                         fprintf(stderr, "Group/GID: %s cannot "
1171                                                 "be found.\n", optarg);
1172                                         ret = -1;
1173                                         goto err;
1174                                 }
1175                         }
1176                         param.fp_exclude_gid = !!neg_opt;
1177                         param.fp_check_gid = 1;
1178                         break;
1179                 case 'L':
1180                         ret = name2layout(&param.fp_layout, optarg);
1181                         if (ret)
1182                                 goto err;
1183                         param.fp_exclude_layout = !!neg_opt;
1184                         param.fp_check_layout = 1;
1185                         break;
1186                 case 'u':
1187                 case 'U':
1188                         rc = name2id(&param.fp_uid, optarg, USER);
1189                         if (rc) {
1190                                 param.fp_uid = strtoul(optarg, &endptr, 10);
1191                                 if (*endptr != '\0') {
1192                                         fprintf(stderr, "User/UID: %s cannot "
1193                                                 "be found.\n", optarg);
1194                                         ret = -1;
1195                                         goto err;
1196                                 }
1197                         }
1198                         param.fp_exclude_uid = !!neg_opt;
1199                         param.fp_check_uid = 1;
1200                         break;
1201                 case FIND_POOL_OPT:
1202                         if (strlen(optarg) > LOV_MAXPOOLNAME) {
1203                                 fprintf(stderr,
1204                                         "Pool name %s is too long"
1205                                         " (max is %d)\n", optarg,
1206                                         LOV_MAXPOOLNAME);
1207                                 ret = -1;
1208                                 goto err;
1209                         }
1210                         /* we do check for empty pool because empty pool
1211                          * is used to find V1 lov attributes */
1212                         strncpy(param.fp_poolname, optarg, LOV_MAXPOOLNAME);
1213                         param.fp_poolname[LOV_MAXPOOLNAME] = '\0';
1214                         param.fp_exclude_pool = !!neg_opt;
1215                         param.fp_check_pool = 1;
1216                         break;
1217                 case 'n':
1218                         param.fp_pattern = (char *)optarg;
1219                         param.fp_exclude_pattern = !!neg_opt;
1220                         break;
1221                 case 'm':
1222                 case 'i':
1223                 case 'O': {
1224                         char *buf, *token, *next, *p;
1225                         int len = 1;
1226                         void *tmp;
1227
1228                         buf = strdup(optarg);
1229                         if (buf == NULL) {
1230                                 ret = -ENOMEM;
1231                                 goto err;
1232                         }
1233
1234                         param.fp_exclude_obd = !!neg_opt;
1235
1236                         token = buf;
1237                         while (token && *token) {
1238                                 token = strchr(token, ',');
1239                                 if (token) {
1240                                         len++;
1241                                         token++;
1242                                 }
1243                         }
1244                         if (c == 'm') {
1245                                 param.fp_exclude_mdt = !!neg_opt;
1246                                 param.fp_num_alloc_mdts += len;
1247                                 tmp = realloc(param.fp_mdt_uuid,
1248                                               param.fp_num_alloc_mdts *
1249                                               sizeof(*param.fp_mdt_uuid));
1250                                 if (tmp == NULL) {
1251                                         ret = -ENOMEM;
1252                                         goto err_free;
1253                                 }
1254
1255                                 param.fp_mdt_uuid = tmp;
1256                         } else {
1257                                 param.fp_exclude_obd = !!neg_opt;
1258                                 param.fp_num_alloc_obds += len;
1259                                 tmp = realloc(param.fp_obd_uuid,
1260                                               param.fp_num_alloc_obds *
1261                                               sizeof(*param.fp_obd_uuid));
1262                                 if (tmp == NULL) {
1263                                         ret = -ENOMEM;
1264                                         goto err_free;
1265                                 }
1266
1267                                 param.fp_obd_uuid = tmp;
1268                         }
1269                         for (token = buf; token && *token; token = next) {
1270                                 struct obd_uuid *puuid;
1271                                 if (c == 'm') {
1272                                         puuid =
1273                                         &param.fp_mdt_uuid[param.fp_num_mdts++];
1274                                 } else {
1275                                         puuid =
1276                                         &param.fp_obd_uuid[param.fp_num_obds++];
1277                                 }
1278                                 p = strchr(token, ',');
1279                                 next = 0;
1280                                 if (p) {
1281                                         *p = 0;
1282                                         next = p+1;
1283                                 }
1284
1285                                 if (strlen(token) > sizeof(puuid->uuid) - 1) {
1286                                         ret = -E2BIG;
1287                                         goto err_free;
1288                                 }
1289
1290                                 strncpy(puuid->uuid, token,
1291                                         sizeof(puuid->uuid));
1292                         }
1293 err_free:
1294                         if (buf)
1295                                 free(buf);
1296                         break;
1297                 }
1298                 case 'p':
1299                         param.fp_zero_end = 1;
1300                         break;
1301                 case 'P':
1302                         break;
1303                 case 's':
1304                         if (optarg[0] == '+') {
1305                                 param.fp_size_sign = -1;
1306                                 optarg++;
1307                         } else if (optarg[0] == '-') {
1308                                 param.fp_size_sign =  1;
1309                                 optarg++;
1310                         }
1311
1312                         ret = llapi_parse_size(optarg, &param.fp_size,
1313                                                &param.fp_size_units, 0);
1314                         if (ret) {
1315                                 fprintf(stderr, "error: bad file size '%s'\n",
1316                                         optarg);
1317                                 goto err;
1318                         }
1319                         param.fp_check_size = 1;
1320                         param.fp_exclude_size = !!neg_opt;
1321                         break;
1322                 case 'S':
1323                         if (optarg[0] == '+') {
1324                                 param.fp_stripe_size_sign = -1;
1325                                 optarg++;
1326                         } else if (optarg[0] == '-') {
1327                                 param.fp_stripe_size_sign =  1;
1328                                 optarg++;
1329                         }
1330
1331                         ret = llapi_parse_size(optarg, &param.fp_stripe_size,
1332                                                &param.fp_stripe_size_units, 0);
1333                         if (ret) {
1334                                 fprintf(stderr, "error: bad stripe_size '%s'\n",
1335                                         optarg);
1336                                 goto err;
1337                         }
1338                         param.fp_check_stripe_size = 1;
1339                         param.fp_exclude_stripe_size = !!neg_opt;
1340                         break;
1341                 case 't':
1342                         param.fp_exclude_type = !!neg_opt;
1343                         switch (optarg[0]) {
1344                         case 'b':
1345                                 param.fp_type = S_IFBLK;
1346                                 break;
1347                         case 'c':
1348                                 param.fp_type = S_IFCHR;
1349                                 break;
1350                         case 'd':
1351                                 param.fp_type = S_IFDIR;
1352                                 break;
1353                         case 'f':
1354                                 param.fp_type = S_IFREG;
1355                                 break;
1356                         case 'l':
1357                                 param.fp_type = S_IFLNK;
1358                                 break;
1359                         case 'p':
1360                                 param.fp_type = S_IFIFO;
1361                                 break;
1362                         case 's':
1363                                 param.fp_type = S_IFSOCK;
1364                                 break;
1365                         default:
1366                                 fprintf(stderr, "error: %s: bad type '%s'\n",
1367                                         argv[0], optarg);
1368                                 ret = CMD_HELP;
1369                                 goto err;
1370                         };
1371                         break;
1372                 default:
1373                         ret = CMD_HELP;
1374                         goto err;
1375                 };
1376         }
1377
1378         if (pathstart == -1) {
1379                 fprintf(stderr, "error: %s: no filename|pathname\n",
1380                         argv[0]);
1381                 ret = CMD_HELP;
1382                 goto err;
1383         } else if (pathend == -1) {
1384                 /* no options */
1385                 pathend = argc;
1386         }
1387
1388         do {
1389                 rc = llapi_find(argv[pathstart], &param);
1390                 if (rc != 0 && ret == 0)
1391                         ret = rc;
1392         } while (++pathstart < pathend);
1393
1394         if (ret)
1395                 fprintf(stderr, "error: %s failed for %s.\n",
1396                         argv[0], argv[optind - 1]);
1397 err:
1398         if (param.fp_obd_uuid && param.fp_num_alloc_obds)
1399                 free(param.fp_obd_uuid);
1400
1401         if (param.fp_mdt_uuid && param.fp_num_alloc_mdts)
1402                 free(param.fp_mdt_uuid);
1403
1404         return ret;
1405 }
1406
1407 static int lfs_getstripe_internal(int argc, char **argv,
1408                                   struct find_param *param)
1409 {
1410         struct option long_opts[] = {
1411 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1412                 /* This formerly implied "stripe-count", but was explicitly
1413                  * made "stripe-count" for consistency with other options,
1414                  * and to separate it from "mdt-count" when DNE arrives. */
1415                 {"count",               no_argument,            0, 'c'},
1416 #endif
1417                 {"stripe-count",        no_argument,            0, 'c'},
1418                 {"stripe_count",        no_argument,            0, 'c'},
1419                 {"directory",           no_argument,            0, 'd'},
1420                 {"default",             no_argument,            0, 'D'},
1421                 {"generation",          no_argument,            0, 'g'},
1422 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1423                 /* This formerly implied "stripe-index", but was explicitly
1424                  * made "stripe-index" for consistency with other options,
1425                  * and to separate it from "mdt-index" when DNE arrives. */
1426                 {"index",               no_argument,            0, 'i'},
1427 #endif
1428                 {"stripe-index",        no_argument,            0, 'i'},
1429                 {"stripe_index",        no_argument,            0, 'i'},
1430                 {"layout",              no_argument,            0, 'L'},
1431                 {"mdt-index",           no_argument,            0, 'M'},
1432                 {"mdt_index",           no_argument,            0, 'M'},
1433 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1434                 /* This formerly implied "stripe-index", but was confusing
1435                  * with "file offset" (which will eventually be needed for
1436                  * with different layouts by offset), so deprecate it. */
1437                 {"offset",              no_argument,            0, 'o'},
1438 #endif
1439                 {"obd",                 required_argument,      0, 'O'},
1440                 {"ost",                 required_argument,      0, 'O'},
1441                 {"pool",                no_argument,            0, 'p'},
1442                 {"quiet",               no_argument,            0, 'q'},
1443                 {"recursive",           no_argument,            0, 'r'},
1444                 {"raw",                 no_argument,            0, 'R'},
1445 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1446                 /* This formerly implied "--stripe-size", but was confusing
1447                  * with "lfs find --size|-s", which means "file size", so use
1448                  * the consistent "--stripe-size|-S" for all commands. */
1449                 {"size",                no_argument,            0, 's'},
1450 #endif
1451                 {"stripe-size",         no_argument,            0, 'S'},
1452                 {"stripe_size",         no_argument,            0, 'S'},
1453                 {"verbose",             no_argument,            0, 'v'},
1454                 {0, 0, 0, 0}
1455         };
1456         int c, rc;
1457
1458         param->fp_max_depth = 1;
1459         while ((c = getopt_long(argc, argv, "cdDghiLMoO:pqrRsSv",
1460                                 long_opts, NULL)) != -1) {
1461                 switch (c) {
1462                 case 'O':
1463                         if (param->fp_obd_uuid) {
1464                                 fprintf(stderr,
1465                                         "error: %s: only one obduuid allowed",
1466                                         argv[0]);
1467                                 return CMD_HELP;
1468                         }
1469                         param->fp_obd_uuid = (struct obd_uuid *)optarg;
1470                         break;
1471                 case 'q':
1472                         param->fp_quiet++;
1473                         break;
1474                 case 'd':
1475                         param->fp_max_depth = 0;
1476                         break;
1477                 case 'D':
1478                         param->fp_get_default_lmv = 1;
1479                         break;
1480                 case 'r':
1481                         param->fp_recursive = 1;
1482                         break;
1483                 case 'v':
1484                         param->fp_verbose = VERBOSE_ALL | VERBOSE_DETAIL;
1485                         break;
1486                 case 'c':
1487 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 6, 53, 0)
1488                         if (strcmp(argv[optind - 1], "--count") == 0)
1489                                 fprintf(stderr, "warning: '--count' deprecated,"
1490                                         " use '--stripe-count' instead\n");
1491 #endif
1492                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
1493                                 param->fp_verbose |= VERBOSE_COUNT;
1494                                 param->fp_max_depth = 0;
1495                         }
1496                         break;
1497 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1498                 case 's':
1499 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 6, 53, 0)
1500                         fprintf(stderr, "warning: '--size|-s' deprecated, "
1501                                 "use '--stripe-size|-S' instead\n");
1502 #endif
1503 #endif /* LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0) */
1504                 case 'S':
1505                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
1506                                 param->fp_verbose |= VERBOSE_SIZE;
1507                                 param->fp_max_depth = 0;
1508                         }
1509                         break;
1510 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 9, 53, 0)
1511                 case 'o':
1512                         fprintf(stderr, "warning: '--offset|-o' deprecated, "
1513                                 "use '--stripe-index|-i' instead\n");
1514 #endif
1515                 case 'i':
1516 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(2, 6, 53, 0)
1517                         if (strcmp(argv[optind - 1], "--index") == 0)
1518                                 fprintf(stderr, "warning: '--index' deprecated"
1519                                         ", use '--stripe-index' instead\n");
1520 #endif
1521                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
1522                                 param->fp_verbose |= VERBOSE_OFFSET;
1523                                 param->fp_max_depth = 0;
1524                         }
1525                         break;
1526                 case 'p':
1527                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
1528                                 param->fp_verbose |= VERBOSE_POOL;
1529                                 param->fp_max_depth = 0;
1530                         }
1531                         break;
1532                 case 'g':
1533                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
1534                                 param->fp_verbose |= VERBOSE_GENERATION;
1535                                 param->fp_max_depth = 0;
1536                         }
1537                         break;
1538                 case 'L':
1539                         if (!(param->fp_verbose & VERBOSE_DETAIL)) {
1540                                 param->fp_verbose |= VERBOSE_LAYOUT;
1541                                 param->fp_max_depth = 0;
1542                         }
1543                         break;
1544                 case 'M':
1545                         if (!(param->fp_verbose & VERBOSE_DETAIL))
1546                                 param->fp_max_depth = 0;
1547                         param->fp_verbose |= VERBOSE_MDTINDEX;
1548                         break;
1549                 case 'R':
1550                         param->fp_raw = 1;
1551                         break;
1552                 default:
1553                         return CMD_HELP;
1554                 }
1555         }
1556
1557         if (optind >= argc)
1558                 return CMD_HELP;
1559
1560         if (param->fp_recursive)
1561                 param->fp_max_depth = -1;
1562
1563         if (!param->fp_verbose)
1564                 param->fp_verbose = VERBOSE_ALL;
1565         if (param->fp_quiet)
1566                 param->fp_verbose = VERBOSE_OBJID;
1567
1568         do {
1569                 rc = llapi_getstripe(argv[optind], param);
1570         } while (++optind < argc && !rc);
1571
1572         if (rc)
1573                 fprintf(stderr, "error: %s failed for %s.\n",
1574                         argv[0], argv[optind - 1]);
1575         return rc;
1576 }
1577
1578 static int lfs_tgts(int argc, char **argv)
1579 {
1580         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
1581         struct find_param param;
1582         int index = 0, rc=0;
1583
1584         if (argc > 2)
1585                 return CMD_HELP;
1586
1587         if (argc == 2 && !realpath(argv[1], path)) {
1588                 rc = -errno;
1589                 fprintf(stderr, "error: invalid path '%s': %s\n",
1590                         argv[1], strerror(-rc));
1591                 return rc;
1592         }
1593
1594         while (!llapi_search_mounts(path, index++, mntdir, NULL)) {
1595                 /* Check if we have a mount point */
1596                 if (mntdir[0] == '\0')
1597                         continue;
1598
1599                 memset(&param, 0, sizeof(param));
1600                 if (!strcmp(argv[0], "mdts"))
1601                         param.fp_get_lmv = 1;
1602
1603                 rc = llapi_ostlist(mntdir, &param);
1604                 if (rc) {
1605                         fprintf(stderr, "error: %s: failed on %s\n",
1606                                 argv[0], mntdir);
1607                 }
1608                 if (path[0] != '\0')
1609                         break;
1610                 memset(mntdir, 0, PATH_MAX);
1611         }
1612
1613         return rc;
1614 }
1615
1616 static int lfs_getstripe(int argc, char **argv)
1617 {
1618         struct find_param param = { 0 };
1619         return lfs_getstripe_internal(argc, argv, &param);
1620 }
1621
1622 /* functions */
1623 static int lfs_getdirstripe(int argc, char **argv)
1624 {
1625         struct find_param param = { 0 };
1626
1627         param.fp_get_lmv = 1;
1628         return lfs_getstripe_internal(argc, argv, &param);
1629 }
1630
1631 /* functions */
1632 static int lfs_setdirstripe(int argc, char **argv)
1633 {
1634         char                    *dname;
1635         int                     result;
1636         unsigned int            stripe_offset = -1;
1637         unsigned int            stripe_count = 1;
1638         enum lmv_hash_type      hash_type;
1639         char                    *end;
1640         int                     c;
1641         char                    *stripe_offset_opt = NULL;
1642         char                    *stripe_count_opt = NULL;
1643         char                    *stripe_hash_opt = NULL;
1644         char                    *mode_opt = NULL;
1645         bool                    default_stripe = false;
1646         mode_t                  mode = S_IRWXU | S_IRWXG | S_IRWXO;
1647         mode_t                  previous_mode = 0;
1648         bool                    delete = false;
1649
1650         struct option long_opts[] = {
1651                 {"count",       required_argument, 0, 'c'},
1652                 {"delete",      no_argument, 0, 'd'},
1653                 {"index",       required_argument, 0, 'i'},
1654                 {"mode",        required_argument, 0, 'm'},
1655                 {"hash-type",   required_argument, 0, 't'},
1656                 {"default_stripe", no_argument, 0, 'D'},
1657                 {0, 0, 0, 0}
1658         };
1659
1660         while ((c = getopt_long(argc, argv, "c:dDi:m:t:", long_opts,
1661                                 NULL)) >= 0) {
1662                 switch (c) {
1663                 case 0:
1664                         /* Long options. */
1665                         break;
1666                 case 'c':
1667                         stripe_count_opt = optarg;
1668                         break;
1669                 case 'd':
1670                         delete = true;
1671                         default_stripe = true;
1672                         break;
1673                 case 'D':
1674                         default_stripe = true;
1675                         break;
1676                 case 'i':
1677                         stripe_offset_opt = optarg;
1678                         break;
1679                 case 'm':
1680                         mode_opt = optarg;
1681                         break;
1682                 case 't':
1683                         stripe_hash_opt = optarg;
1684                         break;
1685                 default:
1686                         fprintf(stderr, "error: %s: option '%s' "
1687                                         "unrecognized\n",
1688                                         argv[0], argv[optind - 1]);
1689                         return CMD_HELP;
1690                 }
1691         }
1692
1693         if (optind == argc) {
1694                 fprintf(stderr, "error: %s: missing dirname\n",
1695                         argv[0]);
1696                 return CMD_HELP;
1697         }
1698
1699         if (!delete && stripe_offset_opt == NULL && stripe_count_opt == NULL) {
1700                 fprintf(stderr, "error: %s: missing stripe offset and count.\n",
1701                         argv[0]);
1702                 return CMD_HELP;
1703         }
1704
1705         if (stripe_offset_opt != NULL) {
1706                 /* get the stripe offset */
1707                 stripe_offset = strtoul(stripe_offset_opt, &end, 0);
1708                 if (*end != '\0') {
1709                         fprintf(stderr, "error: %s: bad stripe offset '%s'\n",
1710                                 argv[0], stripe_offset_opt);
1711                         return CMD_HELP;
1712                 }
1713         }
1714
1715         if (delete) {
1716                 if (stripe_offset_opt != NULL || stripe_count_opt != NULL) {
1717                         fprintf(stderr, "error: %s: cannot specify -d with -s,"
1718                                 " or -i options.\n", argv[0]);
1719                         return CMD_HELP;
1720                 } else {
1721                         stripe_count = 0;
1722                 }
1723         }
1724
1725
1726         if (mode_opt != NULL) {
1727                 mode = strtoul(mode_opt, &end, 8);
1728                 if (*end != '\0') {
1729                         fprintf(stderr, "error: %s: bad mode '%s'\n",
1730                                 argv[0], mode_opt);
1731                         return CMD_HELP;
1732                 }
1733                 previous_mode = umask(0);
1734         }
1735
1736         if (stripe_hash_opt == NULL ||
1737             strcmp(stripe_hash_opt, LMV_HASH_NAME_FNV_1A_64) == 0) {
1738                 hash_type = LMV_HASH_TYPE_FNV_1A_64;
1739         } else if (strcmp(stripe_hash_opt, LMV_HASH_NAME_ALL_CHARS) == 0) {
1740                 hash_type = LMV_HASH_TYPE_ALL_CHARS;
1741         } else {
1742                 fprintf(stderr, "error: %s: bad stripe hash type '%s'\n",
1743                         argv[0], stripe_hash_opt);
1744                 return CMD_HELP;
1745         }
1746
1747         /* get the stripe count */
1748         if (stripe_count_opt != NULL) {
1749                 stripe_count = strtoul(stripe_count_opt, &end, 0);
1750                 if (*end != '\0') {
1751                         fprintf(stderr, "error: %s: bad stripe count '%s'\n",
1752                                 argv[0], stripe_count_opt);
1753                         return CMD_HELP;
1754                 }
1755         }
1756
1757         dname = argv[optind];
1758         do {
1759                 if (default_stripe) {
1760                         result = llapi_dir_set_default_lmv_stripe(dname,
1761                                                     stripe_offset, stripe_count,
1762                                                     hash_type, NULL);
1763                 } else {
1764                         result = llapi_dir_create_pool(dname, mode,
1765                                                        stripe_offset,
1766                                                        stripe_count, hash_type,
1767                                                        NULL);
1768                 }
1769
1770                 if (result) {
1771                         fprintf(stderr, "error: %s: create stripe dir '%s' "
1772                                 "failed\n", argv[0], dname);
1773                         break;
1774                 }
1775                 dname = argv[++optind];
1776         } while (dname != NULL);
1777
1778         if (mode_opt != NULL)
1779                 umask(previous_mode);
1780
1781         return result;
1782 }
1783
1784 /* functions */
1785 static int lfs_rmentry(int argc, char **argv)
1786 {
1787         char *dname;
1788         int   index;
1789         int   result = 0;
1790
1791         if (argc <= 1) {
1792                 fprintf(stderr, "error: %s: missing dirname\n",
1793                         argv[0]);
1794                 return CMD_HELP;
1795         }
1796
1797         index = 1;
1798         dname = argv[index];
1799         while (dname != NULL) {
1800                 result = llapi_direntry_remove(dname);
1801                 if (result) {
1802                         fprintf(stderr, "error: %s: remove dir entry '%s' "
1803                                 "failed\n", argv[0], dname);
1804                         break;
1805                 }
1806                 dname = argv[++index];
1807         }
1808         return result;
1809 }
1810
1811 static int lfs_mv(int argc, char **argv)
1812 {
1813         struct  find_param param = {
1814                 .fp_max_depth = -1,
1815                 .fp_mdt_index = -1,
1816         };
1817         char   *end;
1818         int     c;
1819         int     rc = 0;
1820         struct option long_opts[] = {
1821                 {"mdt-index", required_argument, 0, 'M'},
1822                 {"verbose",     no_argument,       0, 'v'},
1823                 {0, 0, 0, 0}
1824         };
1825
1826         while ((c = getopt_long(argc, argv, "M:v", long_opts, NULL)) != -1) {
1827                 switch (c) {
1828                 case 'M': {
1829                         param.fp_mdt_index = strtoul(optarg, &end, 0);
1830                         if (*end != '\0') {
1831                                 fprintf(stderr, "%s: invalid MDT index'%s'\n",
1832                                         argv[0], optarg);
1833                                 return CMD_HELP;
1834                         }
1835                         break;
1836                 }
1837                 case 'v': {
1838                         param.fp_verbose = VERBOSE_DETAIL;
1839                         break;
1840                 }
1841                 default:
1842                         fprintf(stderr, "error: %s: unrecognized option '%s'\n",
1843                                 argv[0], argv[optind - 1]);
1844                         return CMD_HELP;
1845                 }
1846         }
1847
1848         if (param.fp_mdt_index == -1) {
1849                 fprintf(stderr, "%s: MDT index must be specified\n", argv[0]);
1850                 return CMD_HELP;
1851         }
1852
1853         if (optind >= argc) {
1854                 fprintf(stderr, "%s: missing operand path\n", argv[0]);
1855                 return CMD_HELP;
1856         }
1857
1858         param.fp_migrate = 1;
1859         rc = llapi_mv(argv[optind], &param);
1860         if (rc != 0)
1861                 fprintf(stderr, "%s: cannot migrate '%s' to MDT%04x: %s\n",
1862                         argv[0], argv[optind], param.fp_mdt_index,
1863                         strerror(-rc));
1864         return rc;
1865 }
1866
1867 static int lfs_osts(int argc, char **argv)
1868 {
1869         return lfs_tgts(argc, argv);
1870 }
1871
1872 static int lfs_mdts(int argc, char **argv)
1873 {
1874         return lfs_tgts(argc, argv);
1875 }
1876
1877 #define COOK(value)                                                     \
1878 ({                                                                      \
1879         int radix = 0;                                                  \
1880         while (value > 1024) {                                          \
1881                 value /= 1024;                                          \
1882                 radix++;                                                \
1883         }                                                               \
1884         radix;                                                          \
1885 })
1886 #define UUF     "%-20s"
1887 #define CSF     "%11s"
1888 #define CDF     "%11llu"
1889 #define HDF     "%8.1f%c"
1890 #define RSF     "%4s"
1891 #define RDF     "%3d%%"
1892
1893 static int showdf(char *mntdir, struct obd_statfs *stat,
1894                   char *uuid, int ishow, int cooked,
1895                   char *type, int index, int rc)
1896 {
1897         long long avail, used, total;
1898         double ratio = 0;
1899         char *suffix = "KMGTPEZY";
1900         /* Note if we have >2^64 bytes/fs these buffers will need to be grown */
1901         char tbuf[3 * sizeof(__u64)];
1902         char ubuf[3 * sizeof(__u64)];
1903         char abuf[3 * sizeof(__u64)];
1904         char rbuf[3 * sizeof(__u64)];
1905
1906         if (!uuid || !stat)
1907                 return -EINVAL;
1908
1909         switch (rc) {
1910         case 0:
1911                 if (ishow) {
1912                         avail = stat->os_ffree;
1913                         used = stat->os_files - stat->os_ffree;
1914                         total = stat->os_files;
1915                 } else {
1916                         int shift = cooked ? 0 : 10;
1917
1918                         avail = (stat->os_bavail * stat->os_bsize) >> shift;
1919                         used  = ((stat->os_blocks - stat->os_bfree) *
1920                                  stat->os_bsize) >> shift;
1921                         total = (stat->os_blocks * stat->os_bsize) >> shift;
1922                 }
1923
1924                 if ((used + avail) > 0)
1925                         ratio = (double)used / (double)(used + avail);
1926
1927                 if (cooked) {
1928                         int i;
1929                         double cook_val;
1930
1931                         cook_val = (double)total;
1932                         i = COOK(cook_val);
1933                         if (i > 0)
1934                                 sprintf(tbuf, HDF, cook_val, suffix[i - 1]);
1935                         else
1936                                 sprintf(tbuf, CDF, total);
1937
1938                         cook_val = (double)used;
1939                         i = COOK(cook_val);
1940                         if (i > 0)
1941                                 sprintf(ubuf, HDF, cook_val, suffix[i - 1]);
1942                         else
1943                                 sprintf(ubuf, CDF, used);
1944
1945                         cook_val = (double)avail;
1946                         i = COOK(cook_val);
1947                         if (i > 0)
1948                                 sprintf(abuf, HDF, cook_val, suffix[i - 1]);
1949                         else
1950                                 sprintf(abuf, CDF, avail);
1951                 } else {
1952                         sprintf(tbuf, CDF, total);
1953                         sprintf(ubuf, CDF, used);
1954                         sprintf(abuf, CDF, avail);
1955                 }
1956
1957                 sprintf(rbuf, RDF, (int)(ratio * 100 + 0.5));
1958                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s",
1959                        uuid, tbuf, ubuf, abuf, rbuf, mntdir);
1960                 if (type)
1961                         printf("[%s:%d]\n", type, index);
1962                 else
1963                         printf("\n");
1964
1965                 break;
1966         case -ENODATA:
1967                 printf(UUF": inactive device\n", uuid);
1968                 break;
1969         default:
1970                 printf(UUF": %s\n", uuid, strerror(-rc));
1971                 break;
1972         }
1973
1974         return 0;
1975 }
1976
1977 struct ll_stat_type {
1978         int   st_op;
1979         char *st_name;
1980 };
1981
1982 static int mntdf(char *mntdir, char *fsname, char *pool, int ishow,
1983                 int cooked, int lazy)
1984 {
1985         struct obd_statfs stat_buf, sum = { .os_bsize = 1 };
1986         struct obd_uuid uuid_buf;
1987         char *poolname = NULL;
1988         struct ll_stat_type types[] = { { LL_STATFS_LMV, "MDT" },
1989                                         { LL_STATFS_LOV, "OST" },
1990                                         { 0, NULL } };
1991         struct ll_stat_type *tp;
1992         __u64 ost_ffree = 0;
1993         __u32 index;
1994         __u32 type;
1995         int rc;
1996
1997         if (pool) {
1998                 poolname = strchr(pool, '.');
1999                 if (poolname != NULL) {
2000                         if (strncmp(fsname, pool, strlen(fsname))) {
2001                                 fprintf(stderr, "filesystem name incorrect\n");
2002                                 return -ENODEV;
2003                         }
2004                         poolname++;
2005                 } else
2006                         poolname = pool;
2007         }
2008
2009         if (ishow)
2010                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
2011                        "UUID", "Inodes", "IUsed", "IFree",
2012                        "IUse%", "Mounted on");
2013         else
2014                 printf(UUF" "CSF" "CSF" "CSF" "RSF" %-s\n",
2015                        "UUID", cooked ? "bytes" : "1K-blocks",
2016                        "Used", "Available", "Use%", "Mounted on");
2017
2018         for (tp = types; tp->st_name != NULL; tp++) {
2019                 for (index = 0; ; index++) {
2020                         memset(&stat_buf, 0, sizeof(struct obd_statfs));
2021                         memset(&uuid_buf, 0, sizeof(struct obd_uuid));
2022                         type = lazy ? tp->st_op | LL_STATFS_NODELAY : tp->st_op;
2023                         rc = llapi_obd_statfs(mntdir, type, index,
2024                                               &stat_buf, &uuid_buf);
2025                         if (rc == -ENODEV)
2026                                 break;
2027
2028                         if (rc == -EAGAIN)
2029                                 continue;
2030
2031                         if (poolname && tp->st_op == LL_STATFS_LOV &&
2032                             llapi_search_ost(fsname, poolname,
2033                                              obd_uuid2str(&uuid_buf)) != 1)
2034                                 continue;
2035
2036                         /* the llapi_obd_statfs() call may have returned with
2037                          * an error, but if it filled in uuid_buf we will at
2038                          * lease use that to print out a message for that OBD.
2039                          * If we didn't get anything in the uuid_buf, then fill
2040                          * it in so that we can print an error message. */
2041                         if (uuid_buf.uuid[0] == '\0')
2042                                 sprintf(uuid_buf.uuid, "%s%04x",
2043                                         tp->st_name, index);
2044                         showdf(mntdir, &stat_buf, obd_uuid2str(&uuid_buf),
2045                                ishow, cooked, tp->st_name, index, rc);
2046
2047                         if (rc == 0) {
2048                                 if (tp->st_op == LL_STATFS_LMV) {
2049                                         sum.os_ffree += stat_buf.os_ffree;
2050                                         sum.os_files += stat_buf.os_files;
2051                                 } else /* if (tp->st_op == LL_STATFS_LOV) */ {
2052                                         sum.os_blocks += stat_buf.os_blocks *
2053                                                 stat_buf.os_bsize;
2054                                         sum.os_bfree  += stat_buf.os_bfree *
2055                                                 stat_buf.os_bsize;
2056                                         sum.os_bavail += stat_buf.os_bavail *
2057                                                 stat_buf.os_bsize;
2058                                         ost_ffree += stat_buf.os_ffree;
2059                                 }
2060                         } else if (rc == -EINVAL || rc == -EFAULT) {
2061                                 break;
2062                         }
2063                 }
2064         }
2065
2066         /* If we don't have as many objects free on the OST as inodes
2067          * on the MDS, we reduce the total number of inodes to
2068          * compensate, so that the "inodes in use" number is correct.
2069          * Matches ll_statfs_internal() so the results are consistent. */
2070         if (ost_ffree < sum.os_ffree) {
2071                 sum.os_files = (sum.os_files - sum.os_ffree) + ost_ffree;
2072                 sum.os_ffree = ost_ffree;
2073         }
2074         printf("\n");
2075         showdf(mntdir, &sum, "filesystem summary:", ishow, cooked, NULL, 0, 0);
2076         printf("\n");
2077         return 0;
2078 }
2079
2080 static int lfs_df(int argc, char **argv)
2081 {
2082         char mntdir[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
2083         int ishow = 0, cooked = 0;
2084         int lazy = 0;
2085         int c, rc = 0, index = 0;
2086         char fsname[PATH_MAX] = "", *pool_name = NULL;
2087         struct option long_opts[] = {
2088                 {"pool", required_argument, 0, 'p'},
2089                 {"lazy", 0, 0, 'l'},
2090                 {0, 0, 0, 0}
2091         };
2092
2093         while ((c = getopt_long(argc, argv, "hilp:", long_opts, NULL)) != -1) {
2094                 switch (c) {
2095                 case 'i':
2096                         ishow = 1;
2097                         break;
2098                 case 'h':
2099                         cooked = 1;
2100                         break;
2101                 case 'l':
2102                         lazy = 1;
2103                         break;
2104                 case 'p':
2105                         pool_name = optarg;
2106                         break;
2107                 default:
2108                         return CMD_HELP;
2109                 }
2110         }
2111         if (optind < argc && !realpath(argv[optind], path)) {
2112                 rc = -errno;
2113                 fprintf(stderr, "error: invalid path '%s': %s\n",
2114                         argv[optind], strerror(-rc));
2115                 return rc;
2116         }
2117
2118         while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
2119                 /* Check if we have a mount point */
2120                 if (mntdir[0] == '\0')
2121                         continue;
2122
2123                 rc = mntdf(mntdir, fsname, pool_name, ishow, cooked, lazy);
2124                 if (rc || path[0] != '\0')
2125                         break;
2126                 fsname[0] = '\0'; /* avoid matching in next loop */
2127                 mntdir[0] = '\0'; /* avoid matching in next loop */
2128         }
2129
2130         return rc;
2131 }
2132
2133 static int lfs_getname(int argc, char **argv)
2134 {
2135         char mntdir[PATH_MAX] = "", path[PATH_MAX] = "", fsname[PATH_MAX] = "";
2136         int rc = 0, index = 0, c;
2137         char buf[sizeof(struct obd_uuid)];
2138
2139         while ((c = getopt(argc, argv, "h")) != -1)
2140                 return CMD_HELP;
2141
2142         if (optind == argc) { /* no paths specified, get all paths. */
2143                 while (!llapi_search_mounts(path, index++, mntdir, fsname)) {
2144                         rc = llapi_getname(mntdir, buf, sizeof(buf));
2145                         if (rc < 0) {
2146                                 fprintf(stderr,
2147                                         "cannot get name for `%s': %s\n",
2148                                         mntdir, strerror(-rc));
2149                                 break;
2150                         }
2151
2152                         printf("%s %s\n", buf, mntdir);
2153
2154                         path[0] = fsname[0] = mntdir[0] = 0;
2155                 }
2156         } else { /* paths specified, only attempt to search these. */
2157                 for (; optind < argc; optind++) {
2158                         rc = llapi_getname(argv[optind], buf, sizeof(buf));
2159                         if (rc < 0) {
2160                                 fprintf(stderr,
2161                                         "cannot get name for `%s': %s\n",
2162                                         argv[optind], strerror(-rc));
2163                                 break;
2164                         }
2165
2166                         printf("%s %s\n", buf, argv[optind]);
2167                 }
2168         }
2169         return rc;
2170 }
2171
2172 static int lfs_check(int argc, char **argv)
2173 {
2174         int rc;
2175         char mntdir[PATH_MAX] = {'\0'};
2176         int num_types = 1;
2177         char *obd_types[2];
2178         char obd_type1[4];
2179         char obd_type2[4];
2180
2181         if (argc != 2)
2182                 return CMD_HELP;
2183
2184         obd_types[0] = obd_type1;
2185         obd_types[1] = obd_type2;
2186
2187         if (strcmp(argv[1], "osts") == 0) {
2188                 strcpy(obd_types[0], "osc");
2189         } else if (strcmp(argv[1], "mds") == 0) {
2190                 strcpy(obd_types[0], "mdc");
2191         } else if (strcmp(argv[1], "servers") == 0) {
2192                 num_types = 2;
2193                 strcpy(obd_types[0], "osc");
2194                 strcpy(obd_types[1], "mdc");
2195         } else {
2196                 fprintf(stderr, "error: %s: option '%s' unrecognized\n",
2197                                 argv[0], argv[1]);
2198                         return CMD_HELP;
2199         }
2200
2201         rc = llapi_search_mounts(NULL, 0, mntdir, NULL);
2202         if (rc < 0 || mntdir[0] == '\0') {
2203                 fprintf(stderr, "No suitable Lustre mount found\n");
2204                 return rc;
2205         }
2206
2207         rc = llapi_target_check(num_types, obd_types, mntdir);
2208         if (rc)
2209                 fprintf(stderr, "error: %s: %s status failed\n",
2210                                 argv[0],argv[1]);
2211
2212         return rc;
2213
2214 }
2215
2216 static int lfs_join(int argc, char **argv)
2217 {
2218         fprintf(stderr, "join two lustre files into one.\n"
2219                         "obsolete, HEAD does not support it anymore.\n");
2220         return 0;
2221 }
2222
2223 #ifdef HAVE_SYS_QUOTA_H
2224 static int lfs_quotacheck(int argc, char **argv)
2225 {
2226         int c, check_type = 0;
2227         char *mnt;
2228         struct if_quotacheck qchk;
2229         struct if_quotactl qctl;
2230         char *obd_type = (char *)qchk.obd_type;
2231         int rc;
2232
2233         memset(&qchk, 0, sizeof(qchk));
2234
2235         while ((c = getopt(argc, argv, "gu")) != -1) {
2236                 switch (c) {
2237                 case 'u':
2238                         check_type |= 0x01;
2239                         break;
2240                 case 'g':
2241                         check_type |= 0x02;
2242                         break;
2243                 default:
2244                         fprintf(stderr, "error: %s: option '-%c' "
2245                                         "unrecognized\n", argv[0], c);
2246                         return CMD_HELP;
2247                 }
2248         }
2249
2250         if (check_type)
2251                 check_type--;
2252         else    /* do quotacheck for both user & group quota by default */
2253                 check_type = 0x02;
2254
2255         if (argc == optind)
2256                 return CMD_HELP;
2257
2258         mnt = argv[optind];
2259
2260         rc = llapi_quotacheck(mnt, check_type);
2261         if (rc == -EOPNOTSUPP) {
2262                 fprintf(stderr, "error: quotacheck not supported by the quota "
2263                         "master.\nPlease note that quotacheck is deprecated as "
2264                         "of lustre 2.4.0 since space accounting is always "
2265                         "enabled.\nFilesystems not formatted with 2.4 utils or "
2266                         "beyond can be upgraded with tunefs.lustre --quota.\n");
2267                 return rc;
2268         } else if (rc) {
2269                 fprintf(stderr, "quotacheck failed: %s\n", strerror(-rc));
2270                 return rc;
2271         }
2272
2273         rc = llapi_poll_quotacheck(mnt, &qchk);
2274         if (rc) {
2275                 if (*obd_type)
2276                         fprintf(stderr, "%s %s ", obd_type,
2277                                 obd_uuid2str(&qchk.obd_uuid));
2278                 fprintf(stderr, "quota check failed: %s\n", strerror(-rc));
2279                 return rc;
2280         }
2281
2282         memset(&qctl, 0, sizeof(qctl));
2283         qctl.qc_cmd = LUSTRE_Q_QUOTAON;
2284         qctl.qc_type = check_type;
2285         rc = llapi_quotactl(mnt, &qctl);
2286         if (rc && rc != -EALREADY) {
2287                 if (*obd_type)
2288                         fprintf(stderr, "%s %s ", (char *)qctl.obd_type,
2289                                 obd_uuid2str(&qctl.obd_uuid));
2290                 fprintf(stderr, "%s turn on quota failed: %s\n",
2291                         argv[0], strerror(-rc));
2292                 return rc;
2293         }
2294
2295         return 0;
2296 }
2297
2298 static int lfs_quotaon(int argc, char **argv)
2299 {
2300         int c;
2301         char *mnt;
2302         struct if_quotactl qctl;
2303         char *obd_type = (char *)qctl.obd_type;
2304         int rc;
2305
2306         memset(&qctl, 0, sizeof(qctl));
2307         qctl.qc_cmd = LUSTRE_Q_QUOTAON;
2308
2309         while ((c = getopt(argc, argv, "fgu")) != -1) {
2310                 switch (c) {
2311                 case 'u':
2312                         qctl.qc_type |= 0x01;
2313                         break;
2314                 case 'g':
2315                         qctl.qc_type |= 0x02;
2316                         break;
2317                 case 'f':
2318                         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
2319                         break;
2320                 default:
2321                         fprintf(stderr, "error: %s: option '-%c' "
2322                                         "unrecognized\n", argv[0], c);
2323                         return CMD_HELP;
2324                 }
2325         }
2326
2327         if (qctl.qc_type)
2328                 qctl.qc_type--;
2329         else /* by default, enable quota for both user & group */
2330                 qctl.qc_type = 0x02;
2331
2332         if (argc == optind)
2333                 return CMD_HELP;
2334
2335         mnt = argv[optind];
2336
2337         rc = llapi_quotactl(mnt, &qctl);
2338         if (rc) {
2339                 if (rc == -EOPNOTSUPP) {
2340                         fprintf(stderr, "error: quotaon not supported by the "
2341                                 "quota master.\nPlease note that quotaon/off is"
2342                                 " deprecated as of lustre 2.4.0.\nQuota "
2343                                 "enforcement should now be enabled on the MGS "
2344                                 "via:\nmgs# lctl conf_param ${FSNAME}.quota."
2345                                 "<ost|mdt>=<u|g|ug>\n(ost for block quota, mdt "
2346                                 "for inode quota, u for user and g for group"
2347                                 "\n");
2348                 } else if (rc == -EALREADY) {
2349                         rc = 0;
2350                 } else if (rc == -ENOENT) {
2351                         fprintf(stderr, "error: cannot find quota database, "
2352                                         "make sure you have run quotacheck\n");
2353                 } else {
2354                         if (*obd_type)
2355                                 fprintf(stderr, "%s %s ", obd_type,
2356                                         obd_uuid2str(&qctl.obd_uuid));
2357                         fprintf(stderr, "%s failed: %s\n", argv[0],
2358                                 strerror(-rc));
2359                 }
2360         }
2361
2362         return rc;
2363 }
2364
2365 static int lfs_quotaoff(int argc, char **argv)
2366 {
2367         int c;
2368         char *mnt;
2369         struct if_quotactl qctl;
2370         char *obd_type = (char *)qctl.obd_type;
2371         int rc;
2372
2373         memset(&qctl, 0, sizeof(qctl));
2374         qctl.qc_cmd = LUSTRE_Q_QUOTAOFF;
2375
2376         while ((c = getopt(argc, argv, "gu")) != -1) {
2377                 switch (c) {
2378                 case 'u':
2379                         qctl.qc_type |= 0x01;
2380                         break;
2381                 case 'g':
2382                         qctl.qc_type |= 0x02;
2383                         break;
2384                 default:
2385                         fprintf(stderr, "error: %s: option '-%c' "
2386                                         "unrecognized\n", argv[0], c);
2387                         return CMD_HELP;
2388                 }
2389         }
2390
2391         if (qctl.qc_type)
2392                 qctl.qc_type--;
2393         else /* by default, disable quota for both user & group */
2394                 qctl.qc_type = 0x02;
2395
2396         if (argc == optind)
2397                 return CMD_HELP;
2398
2399         mnt = argv[optind];
2400
2401         rc = llapi_quotactl(mnt, &qctl);
2402         if (rc) {
2403                 if (rc == -EOPNOTSUPP) {
2404                         fprintf(stderr, "error: quotaoff not supported by the "
2405                                 "quota master.\nPlease note that quotaon/off is"
2406                                 " deprecated as of lustre 2.4.0.\nQuota "
2407                                 "enforcement can be disabled on the MGS via:\n"
2408                                 "mgs# lctl conf_param ${FSNAME}.quota.<ost|mdt>"
2409                                 "=\"\"\n");
2410                 } else if (rc == -EALREADY) {
2411                         rc = 0;
2412                 } else {
2413                         if (*obd_type)
2414                                 fprintf(stderr, "%s %s ", obd_type,
2415                                         obd_uuid2str(&qctl.obd_uuid));
2416                         fprintf(stderr, "quotaoff failed: %s\n",
2417                                 strerror(-rc));
2418                 }
2419         }
2420
2421         return rc;
2422 }
2423
2424 #define ARG2INT(nr, str, msg)                                           \
2425 do {                                                                    \
2426         char *endp;                                                     \
2427         nr = strtol(str, &endp, 0);                                     \
2428         if (*endp) {                                                    \
2429                 fprintf(stderr, "error: bad %s: %s\n", msg, str);       \
2430                 return CMD_HELP;                                        \
2431         }                                                               \
2432 } while (0)
2433
2434 #define ADD_OVERFLOW(a,b) ((a + b) < a) ? (a = ULONG_MAX) : (a = a + b)
2435
2436 /* Convert format time string "XXwXXdXXhXXmXXs" into seconds value
2437  * returns the value or ULONG_MAX on integer overflow or incorrect format
2438  * Notes:
2439  *        1. the order of specifiers is arbitrary (may be: 5w3s or 3s5w)
2440  *        2. specifiers may be encountered multiple times (2s3s is 5 seconds)
2441  *        3. empty integer value is interpreted as 0
2442  */
2443 static unsigned long str2sec(const char* timestr)
2444 {
2445         const char spec[] = "smhdw";
2446         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
2447         unsigned long val = 0;
2448         char *tail;
2449
2450         if (strpbrk(timestr, spec) == NULL) {
2451                 /* no specifiers inside the time string,
2452                    should treat it as an integer value */
2453                 val = strtoul(timestr, &tail, 10);
2454                 return *tail ? ULONG_MAX : val;
2455         }
2456
2457         /* format string is XXwXXdXXhXXmXXs */
2458         while (*timestr) {
2459                 unsigned long v;
2460                 int ind;
2461                 char* ptr;
2462
2463                 v = strtoul(timestr, &tail, 10);
2464                 if (v == ULONG_MAX || *tail == '\0')
2465                         /* value too large (ULONG_MAX or more)
2466                            or missing specifier */
2467                         goto error;
2468
2469                 ptr = strchr(spec, *tail);
2470                 if (ptr == NULL)
2471                         /* unknown specifier */
2472                         goto error;
2473
2474                 ind = ptr - spec;
2475
2476                 /* check if product will overflow the type */
2477                 if (!(v < ULONG_MAX / mult[ind]))
2478                         goto error;
2479
2480                 ADD_OVERFLOW(val, mult[ind] * v);
2481                 if (val == ULONG_MAX)
2482                         goto error;
2483
2484                 timestr = tail + 1;
2485         }
2486
2487         return val;
2488
2489 error:
2490         return ULONG_MAX;
2491 }
2492
2493 #define ARG2ULL(nr, str, def_units)                                     \
2494 do {                                                                    \
2495         unsigned long long limit, units = def_units;                    \
2496         int rc;                                                         \
2497                                                                         \
2498         rc = llapi_parse_size(str, &limit, &units, 1);                  \
2499         if (rc < 0) {                                                   \
2500                 fprintf(stderr, "error: bad limit value %s\n", str);    \
2501                 return CMD_HELP;                                        \
2502         }                                                               \
2503         nr = limit;                                                     \
2504 } while (0)
2505
2506 static inline int has_times_option(int argc, char **argv)
2507 {
2508         int i;
2509
2510         for (i = 1; i < argc; i++)
2511                 if (!strcmp(argv[i], "-t"))
2512                         return 1;
2513
2514         return 0;
2515 }
2516
2517 int lfs_setquota_times(int argc, char **argv)
2518 {
2519         int c, rc;
2520         struct if_quotactl qctl;
2521         char *mnt, *obd_type = (char *)qctl.obd_type;
2522         struct obd_dqblk *dqb = &qctl.qc_dqblk;
2523         struct obd_dqinfo *dqi = &qctl.qc_dqinfo;
2524         struct option long_opts[] = {
2525                 {"block-grace",     required_argument, 0, 'b'},
2526                 {"group",           no_argument,       0, 'g'},
2527                 {"inode-grace",     required_argument, 0, 'i'},
2528                 {"times",           no_argument,       0, 't'},
2529                 {"user",            no_argument,       0, 'u'},
2530                 {0, 0, 0, 0}
2531         };
2532
2533         memset(&qctl, 0, sizeof(qctl));
2534         qctl.qc_cmd  = LUSTRE_Q_SETINFO;
2535         qctl.qc_type = UGQUOTA;
2536
2537         while ((c = getopt_long(argc, argv, "b:gi:tu", long_opts, NULL)) != -1) {
2538                 switch (c) {
2539                 case 'u':
2540                 case 'g':
2541                         if (qctl.qc_type != UGQUOTA) {
2542                                 fprintf(stderr, "error: -u and -g can't be used "
2543                                                 "more than once\n");
2544                                 return CMD_HELP;
2545                         }
2546                         qctl.qc_type = (c == 'u') ? USRQUOTA : GRPQUOTA;
2547                         break;
2548                 case 'b':
2549                         if ((dqi->dqi_bgrace = str2sec(optarg)) == ULONG_MAX) {
2550                                 fprintf(stderr, "error: bad block-grace: %s\n",
2551                                         optarg);
2552                                 return CMD_HELP;
2553                         }
2554                         dqb->dqb_valid |= QIF_BTIME;
2555                         break;
2556                 case 'i':
2557                         if ((dqi->dqi_igrace = str2sec(optarg)) == ULONG_MAX) {
2558                                 fprintf(stderr, "error: bad inode-grace: %s\n",
2559                                         optarg);
2560                                 return CMD_HELP;
2561                         }
2562                         dqb->dqb_valid |= QIF_ITIME;
2563                         break;
2564                 case 't': /* Yes, of course! */
2565                         break;
2566                 default: /* getopt prints error message for us when opterr != 0 */
2567                         return CMD_HELP;
2568                 }
2569         }
2570
2571         if (qctl.qc_type == UGQUOTA) {
2572                 fprintf(stderr, "error: neither -u nor -g specified\n");
2573                 return CMD_HELP;
2574         }
2575
2576         if (optind != argc - 1) {
2577                 fprintf(stderr, "error: unexpected parameters encountered\n");
2578                 return CMD_HELP;
2579         }
2580
2581         mnt = argv[optind];
2582         rc = llapi_quotactl(mnt, &qctl);
2583         if (rc) {
2584                 if (*obd_type)
2585                         fprintf(stderr, "%s %s ", obd_type,
2586                                 obd_uuid2str(&qctl.obd_uuid));
2587                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
2588                 return rc;
2589         }
2590
2591         return 0;
2592 }
2593
2594 #define BSLIMIT (1 << 0)
2595 #define BHLIMIT (1 << 1)
2596 #define ISLIMIT (1 << 2)
2597 #define IHLIMIT (1 << 3)
2598
2599 int lfs_setquota(int argc, char **argv)
2600 {
2601         int c, rc;
2602         struct if_quotactl qctl;
2603         char *mnt, *obd_type = (char *)qctl.obd_type;
2604         struct obd_dqblk *dqb = &qctl.qc_dqblk;
2605         struct option long_opts[] = {
2606                 {"block-softlimit", required_argument, 0, 'b'},
2607                 {"block-hardlimit", required_argument, 0, 'B'},
2608                 {"group",           required_argument, 0, 'g'},
2609                 {"inode-softlimit", required_argument, 0, 'i'},
2610                 {"inode-hardlimit", required_argument, 0, 'I'},
2611                 {"user",            required_argument, 0, 'u'},
2612                 {0, 0, 0, 0}
2613         };
2614         unsigned limit_mask = 0;
2615         char *endptr;
2616
2617         if (has_times_option(argc, argv))
2618                 return lfs_setquota_times(argc, argv);
2619
2620         memset(&qctl, 0, sizeof(qctl));
2621         qctl.qc_cmd  = LUSTRE_Q_SETQUOTA;
2622         qctl.qc_type = UGQUOTA; /* UGQUOTA makes no sense for setquota,
2623                                  * so it can be used as a marker that qc_type
2624                                  * isn't reinitialized from command line */
2625
2626         while ((c = getopt_long(argc, argv, "b:B:g:i:I:u:", long_opts, NULL)) != -1) {
2627                 switch (c) {
2628                 case 'u':
2629                 case 'g':
2630                         if (qctl.qc_type != UGQUOTA) {
2631                                 fprintf(stderr, "error: -u and -g can't be used"
2632                                                 " more than once\n");
2633                                 return CMD_HELP;
2634                         }
2635                         qctl.qc_type = (c == 'u') ? USRQUOTA : GRPQUOTA;
2636                         rc = name2id(&qctl.qc_id, optarg,
2637                                      (qctl.qc_type == USRQUOTA) ? USER : GROUP);
2638                         if (rc) {
2639                                 qctl.qc_id = strtoul(optarg, &endptr, 10);
2640                                 if (*endptr != '\0') {
2641                                         fprintf(stderr, "error: can't find id "
2642                                                 "for name %s\n", optarg);
2643                                         return CMD_HELP;
2644                                 }
2645                         }
2646                         break;
2647                 case 'b':
2648                         ARG2ULL(dqb->dqb_bsoftlimit, optarg, 1024);
2649                         dqb->dqb_bsoftlimit >>= 10;
2650                         limit_mask |= BSLIMIT;
2651                         if (dqb->dqb_bsoftlimit &&
2652                             dqb->dqb_bsoftlimit <= 1024) /* <= 1M? */
2653                                 fprintf(stderr, "warning: block softlimit is "
2654                                         "smaller than the miminal qunit size, "
2655                                         "please see the help of setquota or "
2656                                         "Lustre manual for details.\n");
2657                         break;
2658                 case 'B':
2659                         ARG2ULL(dqb->dqb_bhardlimit, optarg, 1024);
2660                         dqb->dqb_bhardlimit >>= 10;
2661                         limit_mask |= BHLIMIT;
2662                         if (dqb->dqb_bhardlimit &&
2663                             dqb->dqb_bhardlimit <= 1024) /* <= 1M? */
2664                                 fprintf(stderr, "warning: block hardlimit is "
2665                                         "smaller than the miminal qunit size, "
2666                                         "please see the help of setquota or "
2667                                         "Lustre manual for details.\n");
2668                         break;
2669                 case 'i':
2670                         ARG2ULL(dqb->dqb_isoftlimit, optarg, 1);
2671                         limit_mask |= ISLIMIT;
2672                         if (dqb->dqb_isoftlimit &&
2673                             dqb->dqb_isoftlimit <= 1024) /* <= 1K inodes? */
2674                                 fprintf(stderr, "warning: inode softlimit is "
2675                                         "smaller than the miminal qunit size, "
2676                                         "please see the help of setquota or "
2677                                         "Lustre manual for details.\n");
2678                         break;
2679                 case 'I':
2680                         ARG2ULL(dqb->dqb_ihardlimit, optarg, 1);
2681                         limit_mask |= IHLIMIT;
2682                         if (dqb->dqb_ihardlimit &&
2683                             dqb->dqb_ihardlimit <= 1024) /* <= 1K inodes? */
2684                                 fprintf(stderr, "warning: inode hardlimit is "
2685                                         "smaller than the miminal qunit size, "
2686                                         "please see the help of setquota or "
2687                                         "Lustre manual for details.\n");
2688                         break;
2689                 default: /* getopt prints error message for us when opterr != 0 */
2690                         return CMD_HELP;
2691                 }
2692         }
2693
2694         if (qctl.qc_type == UGQUOTA) {
2695                 fprintf(stderr, "error: neither -u nor -g was specified\n");
2696                 return CMD_HELP;
2697         }
2698
2699         if (limit_mask == 0) {
2700                 fprintf(stderr, "error: at least one limit must be specified\n");
2701                 return CMD_HELP;
2702         }
2703
2704         if (optind != argc - 1) {
2705                 fprintf(stderr, "error: unexpected parameters encountered\n");
2706                 return CMD_HELP;
2707         }
2708
2709         mnt = argv[optind];
2710
2711         if ((!(limit_mask & BHLIMIT) ^ !(limit_mask & BSLIMIT)) ||
2712             (!(limit_mask & IHLIMIT) ^ !(limit_mask & ISLIMIT))) {
2713                 /* sigh, we can't just set blimits/ilimits */
2714                 struct if_quotactl tmp_qctl = {.qc_cmd  = LUSTRE_Q_GETQUOTA,
2715                                                .qc_type = qctl.qc_type,
2716                                                .qc_id   = qctl.qc_id};
2717
2718                 rc = llapi_quotactl(mnt, &tmp_qctl);
2719                 if (rc < 0) {
2720                         fprintf(stderr, "error: setquota failed while retrieving"
2721                                         " current quota settings (%s)\n",
2722                                         strerror(-rc));
2723                         return rc;
2724                 }
2725
2726                 if (!(limit_mask & BHLIMIT))
2727                         dqb->dqb_bhardlimit = tmp_qctl.qc_dqblk.dqb_bhardlimit;
2728                 if (!(limit_mask & BSLIMIT))
2729                         dqb->dqb_bsoftlimit = tmp_qctl.qc_dqblk.dqb_bsoftlimit;
2730                 if (!(limit_mask & IHLIMIT))
2731                         dqb->dqb_ihardlimit = tmp_qctl.qc_dqblk.dqb_ihardlimit;
2732                 if (!(limit_mask & ISLIMIT))
2733                         dqb->dqb_isoftlimit = tmp_qctl.qc_dqblk.dqb_isoftlimit;
2734
2735                 /* Keep grace times if we have got no softlimit arguments */
2736                 if ((limit_mask & BHLIMIT) && !(limit_mask & BSLIMIT)) {
2737                         dqb->dqb_valid |= QIF_BTIME;
2738                         dqb->dqb_btime = tmp_qctl.qc_dqblk.dqb_btime;
2739                 }
2740
2741                 if ((limit_mask & IHLIMIT) && !(limit_mask & ISLIMIT)) {
2742                         dqb->dqb_valid |= QIF_ITIME;
2743                         dqb->dqb_itime = tmp_qctl.qc_dqblk.dqb_itime;
2744                 }
2745         }
2746
2747         dqb->dqb_valid |= (limit_mask & (BHLIMIT | BSLIMIT)) ? QIF_BLIMITS : 0;
2748         dqb->dqb_valid |= (limit_mask & (IHLIMIT | ISLIMIT)) ? QIF_ILIMITS : 0;
2749
2750         rc = llapi_quotactl(mnt, &qctl);
2751         if (rc) {
2752                 if (*obd_type)
2753                         fprintf(stderr, "%s %s ", obd_type,
2754                                 obd_uuid2str(&qctl.obd_uuid));
2755                 fprintf(stderr, "setquota failed: %s\n", strerror(-rc));
2756                 return rc;
2757         }
2758
2759         return 0;
2760 }
2761
2762 static inline char *type2name(int check_type)
2763 {
2764         if (check_type == USRQUOTA)
2765                 return "user";
2766         else if (check_type == GRPQUOTA)
2767                 return "group";
2768         else
2769                 return "unknown";
2770 }
2771
2772 /* Converts seconds value into format string
2773  * result is returned in buf
2774  * Notes:
2775  *        1. result is in descenting order: 1w2d3h4m5s
2776  *        2. zero fields are not filled (except for p. 3): 5d1s
2777  *        3. zero seconds value is presented as "0s"
2778  */
2779 static char * __sec2str(time_t seconds, char *buf)
2780 {
2781         const char spec[] = "smhdw";
2782         const unsigned long mult[] = {1, 60, 60*60, 24*60*60, 7*24*60*60};
2783         unsigned long c;
2784         char *tail = buf;
2785         int i;
2786
2787         for (i = sizeof(mult) / sizeof(mult[0]) - 1 ; i >= 0; i--) {
2788                 c = seconds / mult[i];
2789
2790                 if (c > 0 || (i == 0 && buf == tail))
2791                         tail += snprintf(tail, 40-(tail-buf), "%lu%c", c, spec[i]);
2792
2793                 seconds %= mult[i];
2794         }
2795
2796         return tail;
2797 }
2798
2799 static void sec2str(time_t seconds, char *buf, int rc)
2800 {
2801         char *tail = buf;
2802
2803         if (rc)
2804                 *tail++ = '[';
2805
2806         tail = __sec2str(seconds, tail);
2807
2808         if (rc && tail - buf < 39) {
2809                 *tail++ = ']';
2810                 *tail++ = 0;
2811         }
2812 }
2813
2814 static void diff2str(time_t seconds, char *buf, time_t now)
2815 {
2816
2817         buf[0] = 0;
2818         if (!seconds)
2819                 return;
2820         if (seconds <= now) {
2821                 strcpy(buf, "none");
2822                 return;
2823         }
2824         __sec2str(seconds - now, buf);
2825 }
2826
2827 static void print_quota_title(char *name, struct if_quotactl *qctl,
2828                               bool human_readable)
2829 {
2830         printf("Disk quotas for %s %s (%cid %u):\n",
2831                type2name(qctl->qc_type), name,
2832                *type2name(qctl->qc_type), qctl->qc_id);
2833         printf("%15s%8s %7s%8s%8s%8s %7s%8s%8s\n",
2834                "Filesystem", human_readable ? "used" : "kbytes",
2835                "quota", "limit", "grace",
2836                "files", "quota", "limit", "grace");
2837 }
2838
2839 static void kbytes2str(__u64 num, char *buf, bool h)
2840 {
2841         if (!h) {
2842                 sprintf(buf, LPU64, num);
2843         } else {
2844                 if (num >> 30)
2845                         sprintf(buf, "%5.4gT", (double)num / (1 << 30));
2846                 else if (num >> 20)
2847                         sprintf(buf, "%5.4gG", (double)num / (1 << 20));
2848                 else if (num >> 10)
2849                         sprintf(buf, "%5.4gM", (double)num / (1 << 10));
2850                 else
2851                         sprintf(buf, LPU64"%s", num, "k");
2852         }
2853 }
2854
2855 static void print_quota(char *mnt, struct if_quotactl *qctl, int type,
2856                         int rc, bool h)
2857 {
2858         time_t now;
2859
2860         time(&now);
2861
2862         if (qctl->qc_cmd == LUSTRE_Q_GETQUOTA || qctl->qc_cmd == Q_GETOQUOTA) {
2863                 int bover = 0, iover = 0;
2864                 struct obd_dqblk *dqb = &qctl->qc_dqblk;
2865                 char numbuf[3][32];
2866                 char timebuf[40];
2867                 char strbuf[32];
2868
2869                 if (dqb->dqb_bhardlimit &&
2870                     lustre_stoqb(dqb->dqb_curspace) >= dqb->dqb_bhardlimit) {
2871                         bover = 1;
2872                 } else if (dqb->dqb_bsoftlimit && dqb->dqb_btime) {
2873                         if (dqb->dqb_btime > now) {
2874                                 bover = 2;
2875                         } else {
2876                                 bover = 3;
2877                         }
2878                 }
2879
2880                 if (dqb->dqb_ihardlimit &&
2881                     dqb->dqb_curinodes >= dqb->dqb_ihardlimit) {
2882                         iover = 1;
2883                 } else if (dqb->dqb_isoftlimit && dqb->dqb_itime) {
2884                         if (dqb->dqb_itime > now) {
2885                                 iover = 2;
2886                         } else {
2887                                 iover = 3;
2888                         }
2889                 }
2890
2891
2892                 if (strlen(mnt) > 15)
2893                         printf("%s\n%15s", mnt, "");
2894                 else
2895                         printf("%15s", mnt);
2896
2897                 if (bover)
2898                         diff2str(dqb->dqb_btime, timebuf, now);
2899
2900                 kbytes2str(lustre_stoqb(dqb->dqb_curspace), strbuf, h);
2901                 if (rc == -EREMOTEIO)
2902                         sprintf(numbuf[0], "%s*", strbuf);
2903                 else
2904                         sprintf(numbuf[0], (dqb->dqb_valid & QIF_SPACE) ?
2905                                 "%s" : "[%s]", strbuf);
2906
2907                 kbytes2str(dqb->dqb_bsoftlimit, strbuf, h);
2908                 if (type == QC_GENERAL)
2909                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_BLIMITS) ?
2910                                 "%s" : "[%s]", strbuf);
2911                 else
2912                         sprintf(numbuf[1], "%s", "-");
2913
2914                 kbytes2str(dqb->dqb_bhardlimit, strbuf, h);
2915                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_BLIMITS) ?
2916                         "%s" : "[%s]", strbuf);
2917
2918                 printf(" %7s%c %6s %7s %7s",
2919                        numbuf[0], bover ? '*' : ' ', numbuf[1],
2920                        numbuf[2], bover > 1 ? timebuf : "-");
2921
2922                 if (iover)
2923                         diff2str(dqb->dqb_itime, timebuf, now);
2924
2925                 sprintf(numbuf[0], (dqb->dqb_valid & QIF_INODES) ?
2926                         LPU64 : "["LPU64"]", dqb->dqb_curinodes);
2927
2928                 if (type == QC_GENERAL)
2929                         sprintf(numbuf[1], (dqb->dqb_valid & QIF_ILIMITS) ?
2930                                 LPU64 : "["LPU64"]", dqb->dqb_isoftlimit);
2931                 else
2932                         sprintf(numbuf[1], "%s", "-");
2933
2934                 sprintf(numbuf[2], (dqb->dqb_valid & QIF_ILIMITS) ?
2935                         LPU64 : "["LPU64"]", dqb->dqb_ihardlimit);
2936
2937                 if (type != QC_OSTIDX)
2938                         printf(" %7s%c %6s %7s %7s",
2939                                numbuf[0], iover ? '*' : ' ', numbuf[1],
2940                                numbuf[2], iover > 1 ? timebuf : "-");
2941                 else
2942                         printf(" %7s %7s %7s %7s", "-", "-", "-", "-");
2943                 printf("\n");
2944
2945         } else if (qctl->qc_cmd == LUSTRE_Q_GETINFO ||
2946                    qctl->qc_cmd == Q_GETOINFO) {
2947                 char bgtimebuf[40];
2948                 char igtimebuf[40];
2949
2950                 sec2str(qctl->qc_dqinfo.dqi_bgrace, bgtimebuf, rc);
2951                 sec2str(qctl->qc_dqinfo.dqi_igrace, igtimebuf, rc);
2952                 printf("Block grace time: %s; Inode grace time: %s\n",
2953                        bgtimebuf, igtimebuf);
2954         }
2955 }
2956
2957 static int print_obd_quota(char *mnt, struct if_quotactl *qctl, int is_mdt,
2958                            bool h, __u64 *total)
2959 {
2960         int rc = 0, rc1 = 0, count = 0;
2961         __u32 valid = qctl->qc_valid;
2962
2963         rc = llapi_get_obd_count(mnt, &count, is_mdt);
2964         if (rc) {
2965                 fprintf(stderr, "can not get %s count: %s\n",
2966                         is_mdt ? "mdt": "ost", strerror(-rc));
2967                 return rc;
2968         }
2969
2970         for (qctl->qc_idx = 0; qctl->qc_idx < count; qctl->qc_idx++) {
2971                 qctl->qc_valid = is_mdt ? QC_MDTIDX : QC_OSTIDX;
2972                 rc = llapi_quotactl(mnt, qctl);
2973                 if (rc) {
2974                         /* It is remote client case. */
2975                         if (-rc == EOPNOTSUPP) {
2976                                 rc = 0;
2977                                 goto out;
2978                         }
2979
2980                         if (!rc1)
2981                                 rc1 = rc;
2982                         fprintf(stderr, "quotactl %s%d failed.\n",
2983                                 is_mdt ? "mdt": "ost", qctl->qc_idx);
2984                         continue;
2985                 }
2986
2987                 print_quota(obd_uuid2str(&qctl->obd_uuid), qctl,
2988                             qctl->qc_valid, 0, h);
2989