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