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