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