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