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