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