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