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