Whamcloud - gitweb
8c011552bfea483a72eb377878b008e3404285d3
[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.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/utils/lfs.c
33  *
34  * Author: Peter J. Braam <braam@clusterfs.com>
35  * Author: Phil Schwan <phil@clusterfs.com>
36  * Author: Robert Read <rread@clusterfs.com>
37  */
38
39 /* for O_DIRECTORY */
40 #ifndef _GNU_SOURCE
41 #define _GNU_SOURCE
42 #endif
43
44 #include <stdlib.h>
45 #include <stdio.h>
46 #include <inttypes.h>
47 #include <getopt.h>
48 #include <string.h>
49 #include <mntent.h>
50 #include <unistd.h>
51 #include <errno.h>
52 #include <err.h>
53 #include <pwd.h>
54 #include <grp.h>
55 #include <sys/ioctl.h>
56 #include <sys/quota.h>
57 #include <sys/time.h>
58 #include <sys/types.h>
59 #include <sys/stat.h>
60 #include <sys/param.h>
61 #include <fcntl.h>
62 #include <dirent.h>
63 #include <time.h>
64 #include <ctype.h>
65 #include <zlib.h>
66 #include <libgen.h>
67 #include "lfs_project.h"
68
69 #include <libcfs/util/string.h>
70 #include <libcfs/util/ioctl.h>
71 #include <libcfs/util/parser.h>
72 #include <lustre/lustreapi.h>
73 #include <linux/lustre/lustre_ver.h>
74 #include <linux/lustre/lustre_param.h>
75 #include <linux/lnet/nidstr.h>
76
77 #ifndef ARRAY_SIZE
78 # define ARRAY_SIZE(a) ((sizeof(a)) / (sizeof((a)[0])))
79 #endif /* !ARRAY_SIZE */
80
81 /* all functions */
82 static int lfs_find(int argc, char **argv);
83 static int lfs_getstripe(int argc, char **argv);
84 static int lfs_getdirstripe(int argc, char **argv);
85 static int lfs_setdirstripe(int argc, char **argv);
86 static int lfs_rmentry(int argc, char **argv);
87 static int lfs_osts(int argc, char **argv);
88 static int lfs_mdts(int argc, char **argv);
89 static int lfs_df(int argc, char **argv);
90 static int lfs_getname(int argc, char **argv);
91 static int lfs_check(int argc, char **argv);
92 #ifdef HAVE_SYS_QUOTA_H
93 static int lfs_setquota(int argc, char **argv);
94 static int lfs_quota(int argc, char **argv);
95 static int lfs_project(int argc, char **argv);
96 #endif
97 static int lfs_flushctx(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 static int lfs_ladvise(int argc, char **argv);
118 static int lfs_mirror(int argc, char **argv);
119 static int lfs_mirror_list_commands(int argc, char **argv);
120 static int lfs_list_commands(int argc, char **argv);
121 static inline int lfs_mirror_resync(int argc, char **argv);
122 static inline int lfs_mirror_verify(int argc, char **argv);
123
124 enum setstripe_origin {
125         SO_SETSTRIPE,
126         SO_MIGRATE,
127         SO_MIRROR_CREATE,
128         SO_MIRROR_EXTEND,
129         SO_MIRROR_SPLIT,
130 };
131 static int lfs_setstripe_internal(int argc, char **argv,
132                                   enum setstripe_origin opc);
133
134 static inline int lfs_setstripe(int argc, char **argv)
135 {
136         return lfs_setstripe_internal(argc, argv, SO_SETSTRIPE);
137 }
138 static inline int lfs_setstripe_migrate(int argc, char **argv)
139 {
140         return lfs_setstripe_internal(argc, argv, SO_MIGRATE);
141 }
142 static inline int lfs_mirror_create(int argc, char **argv)
143 {
144         return lfs_setstripe_internal(argc, argv, SO_MIRROR_CREATE);
145 }
146 static inline int lfs_mirror_extend(int argc, char **argv)
147 {
148         return lfs_setstripe_internal(argc, argv, SO_MIRROR_EXTEND);
149 }
150 static inline int lfs_mirror_split(int argc, char **argv)
151 {
152         return lfs_setstripe_internal(argc, argv, SO_MIRROR_SPLIT);
153 }
154
155 /* Setstripe and migrate share mostly the same parameters */
156 #define SSM_CMD_COMMON(cmd) \
157         "usage: "cmd" [--component-end|-E <comp_end>]\n"                \
158         "                 [--stripe-count|-c <stripe_count>]\n"         \
159         "                 [--stripe-index|-i <start_ost_idx>]\n"        \
160         "                 [--stripe-size|-S <stripe_size>]\n"           \
161         "                 [--layout|-L <pattern>]\n"            \
162         "                 [--pool|-p <pool_name>]\n"                    \
163         "                 [--ost|-o <ost_indices>]\n"
164
165 #define SSM_HELP_COMMON \
166         "\tstripe_count: Number of OSTs to stripe over (0=fs default, -1 all)\n" \
167         "\tstart_ost_idx: OST index of first stripe (-1=default round robin)\n"\
168         "\tstripe_size:  Number of bytes on each OST (0=fs default)\n" \
169         "\t              Can be specified with K, M or G (for KB, MB, GB\n" \
170         "\t              respectively)\n"                               \
171         "\tpool_name:    Name of OST pool to use (default none)\n"      \
172         "\tlayout:       stripe pattern type: raid0, mdt (default raid0)\n"\
173         "\tost_indices:  List of OST indices, can be repeated multiple times\n"\
174         "\t              Indices be specified in a format of:\n"        \
175         "\t                -o <ost_1>,<ost_i>-<ost_j>,<ost_n>\n"        \
176         "\t              Or:\n"                                         \
177         "\t                -o <ost_1> -o <ost_i>-<ost_j> -o <ost_n>\n"  \
178         "\t              If --pool is set with --ost, then the OSTs\n"  \
179         "\t              must be the members of the pool.\n"            \
180         "\tcomp_end:     Extent end of component, start after previous end.\n"\
181         "\t              Can be specified with K, M or G (for KB, MB, GB\n" \
182         "\t              respectively, -1 for EOF). Must be a multiple of\n"\
183         "\t              stripe_size.\n"
184
185 #define MIRROR_CREATE_HELP                                                     \
186         "\tmirror_count: Number of mirrors to be created with the upcoming\n"  \
187         "\t              setstripe layout options\n"                           \
188         "\t              It defaults to 1 if not specified; if specified,\n"   \
189         "\t              it must follow the option without a space.\n"         \
190         "\t              The option can also be repeated multiple times to\n"  \
191         "\t              separate mirrors that have different layouts.\n"      \
192         "\tsetstripe options: Mirror layout\n"                                 \
193         "\t              It can be a plain layout or a composite layout.\n"    \
194         "\t              If not specified, the stripe options inherited\n"     \
195         "\t              from the previous component will be used.\n"          \
196         "\tparent:       Use default stripe options from parent directory\n"   \
197         "\tflags:        set flags to the component of the current mirror.\n"  \
198         "\t              Only \"prefer\" flag is supported so far.\n"
199
200 #define MIRROR_EXTEND_HELP                                                     \
201         MIRROR_CREATE_HELP                                                     \
202         "\tvictim_file:  The layout of victim_file will be split and used\n"   \
203         "\t              as a mirror added to the mirrored file.\n"            \
204         "\tno-verify:    This option indicates not to verify the mirror(s)\n"  \
205         "\t              from victim file(s) in case the victim file(s)\n"     \
206         "\t              contains the same data as the original mirrored\n"    \
207         "\t              file.\n"
208
209 #define MIRROR_EXTEND_USAGE                                                    \
210         "                 <--mirror-count|-N[mirror_count]>\n"                 \
211         "                 [setstripe options|--parent|-f <victim_file>]\n"     \
212         "                 [--no-verify]\n"
213
214 #define SETSTRIPE_USAGE                                                 \
215         SSM_CMD_COMMON("setstripe")                                     \
216         MIRROR_EXTEND_USAGE                                             \
217         "                 <directory|filename>\n"                       \
218         SSM_HELP_COMMON                                                 \
219         MIRROR_EXTEND_HELP
220
221 #define MIGRATE_USAGE                                                   \
222         SSM_CMD_COMMON("migrate  ")                                     \
223         "                 [--block|-b]\n"                               \
224         "                 [--non-block|-n]\n"                           \
225         "                 [--non-direct|-D]\n"                          \
226         "                 <filename>\n"                                 \
227         SSM_HELP_COMMON                                                 \
228         "\n"                                                            \
229         "\tblock:        Block file access during data migration (default)\n" \
230         "\tnon-block:    Abort migrations if concurrent access is detected\n" \
231         "\tnon-direct:   Do not use direct I/O to copy file contents\n" \
232
233 #define SETDIRSTRIPE_USAGE                                      \
234         "               [--mdt-count|-c stripe_count>\n"        \
235         "               [--mdt-index|-i mdt_index]\n"           \
236         "               [--mdt-hash|-H mdt_hash]\n"             \
237         "               [--default|-D] [--mode|-m mode] <dir>\n"        \
238         "\tstripe_count: stripe count of the striped directory\n"       \
239         "\tmdt_index: MDT index of first stripe\n"                      \
240         "\tmdt_hash:  hash type of the striped directory. mdt types:\n" \
241         "       fnv_1a_64 FNV-1a hash algorithm (default)\n"            \
242         "       all_char  sum of characters % MDT_COUNT (not recommended)\n" \
243         "\tdefault_stripe: set default dirstripe of the directory\n"    \
244         "\tmode: the mode of the directory\n"
245
246 /**
247  * command_t mirror_cmdlist - lfs mirror commands.
248  */
249 command_t mirror_cmdlist[] = {
250         { .pc_name = "create", .pc_func = lfs_mirror_create,
251           .pc_help = "Create a mirrored file.\n"
252                 "usage: lfs mirror create "
253                 "<--mirror-count|-N[mirror_count]> "
254                 "[setstripe options|--parent] ... <filename|directory>\n"
255           MIRROR_CREATE_HELP },
256         { .pc_name = "extend", .pc_func = lfs_mirror_extend,
257           .pc_help = "Extend a mirrored file.\n"
258                 "usage: lfs mirror extend "
259                 "<--mirror-count|-N[mirror_count]> [--no-verify] "
260                 "[setstripe options|--parent|-f <victim_file>] ... <filename>\n"
261           MIRROR_EXTEND_HELP },
262         { .pc_name = "split", .pc_func = lfs_mirror_split,
263           .pc_help = "Split a mirrored file.\n"
264         "usage: lfs mirror split <--mirror-id <mirror_id>> [--destroy|-d] "
265         "[-f <new_file>] <mirrored file>\n"
266         "\tmirror_id:    The numerical unique identifier for a mirror. It\n"
267         "\t              can be fetched by lfs getstripe command.\n"
268         "\tnew_file:     This option indicates the layout of the split\n"
269         "\t              mirror will be stored into. If not specified,\n"
270         "\t              a new file named <mirrored_file>.mirror~<mirror_id>\n"
271         "\t              will be used.\n" },
272         { .pc_name = "resync", .pc_func = lfs_mirror_resync,
273           .pc_help = "Resynchronizes out-of-sync mirrored file(s).\n"
274                 "usage: lfs mirror resync [--only <mirror_id[,...]>] "
275                 "<mirrored file> [<mirrored file2>...]\n"},
276         { .pc_name = "verify", .pc_func = lfs_mirror_verify,
277           .pc_help = "Verify mirrored file(s).\n"
278                 "usage: lfs mirror verify "
279                 "[--only <mirror_id,mirror_id2[,...]>] "
280                 "[--verbose|-v] <mirrored_file> [<mirrored_file2> ...]\n"},
281         { .pc_name = "--list-commands", .pc_func = lfs_mirror_list_commands,
282           .pc_help = "list commands supported by lfs mirror"},
283         { .pc_name = "help", .pc_func = Parser_help, .pc_help = "help" },
284         { .pc_name = "exit", .pc_func = Parser_quit, .pc_help = "quit" },
285         { .pc_name = "quit", .pc_func = Parser_quit, .pc_help = "quit" },
286         { .pc_help = NULL }
287 };
288
289 /* all available commands */
290 command_t cmdlist[] = {
291         {"setstripe", lfs_setstripe, 0,
292          "To create a file with specified striping/composite layout, or\n"
293          "create/replace the default layout on an existing directory:\n"
294          SSM_CMD_COMMON("setstripe")
295          "                 <directory|filename>\n"
296          " or\n"
297          "To add component(s) to an existing composite file:\n"
298          SSM_CMD_COMMON("setstripe --component-add")
299          SSM_HELP_COMMON
300          "To totally delete the default striping from an existing directory:\n"
301          "usage: setstripe -d <directory>\n"
302          " or\n"
303          "To delete the last component(s) from an existing composite file\n"
304          "(note that this will also delete any data in those components):\n"
305          "usage: setstripe --component-del [--component-id|-I <comp_id>]\n"
306          "                               [--component-flags|-F <comp_flags>]\n"
307          "                               <filename>\n"
308          "\tcomp_id:     Unique component ID to delete\n"
309          "\tcomp_flags:  'init' indicating all instantiated components\n"
310          "\t             '^init' indicating all uninstantiated components\n"
311          "\t-I and -F cannot be specified at the same time\n"},
312         {"getstripe", lfs_getstripe, 0,
313          "To list the layout pattern for a given file or files in a\n"
314          "directory or recursively for all files in a directory tree.\n"
315          "usage: getstripe [--ost|-O <uuid>] [--quiet|-q] [--verbose|-v]\n"
316          "                 [--stripe-count|-c] [--stripe-index|-i] [--fid|-F]\n"
317          "                 [--pool|-p] [--stripe-size|-S] [--directory|-d]\n"
318          "                 [--mdt-index|-m] [--recursive|-r] [--raw|-R]\n"
319          "                 [--layout|-L] [--generation|-g] [--yaml|-y]\n"
320          "                 [--component-id[=comp_id]|-I[comp_id]]\n"
321          "                 [--component-flags[=comp_flags]]\n"
322          "                 [--component-count]\n"
323          "                 [--component-start[=[+-]comp_start]]\n"
324          "                 [--component-end[=[+-]comp_end]|-E[[+-]comp_end]]\n"
325          "                 <directory|filename> ..."},
326         {"setdirstripe", lfs_setdirstripe, 0,
327          "To create a striped directory on a specified MDT. This can only\n"
328          "be done on MDT0 with the right of administrator.\n"
329          "usage: setdirstripe [OPTION] <directory>\n"
330          SETDIRSTRIPE_USAGE},
331         {"getdirstripe", lfs_getdirstripe, 0,
332          "To list the layout pattern info for a given directory\n"
333          "or recursively for all directories in a directory tree.\n"
334          "usage: getdirstripe [--mdt-count|-c] [--mdt-index|-m|-i]\n"
335          "                    [--mdt-hash|-H] [--obd|-O <uuid>]\n"
336          "                    [--recursive|-r] [--yaml|-y]\n"
337          "                    [--default|-D] <dir> ..."},
338         {"mkdir", lfs_setdirstripe, 0,
339          "To create a striped directory on a specified MDT. This can only\n"
340          "be done on MDT0 with the right of administrator.\n"
341          "usage: mkdir [OPTION] <directory>\n"
342          SETDIRSTRIPE_USAGE},
343         {"rm_entry", lfs_rmentry, 0,
344          "To remove the name entry of the remote directory. Note: This\n"
345          "command will only delete the name entry, i.e. the remote directory\n"
346          "will become inaccessable after this command. This can only be done\n"
347          "by the administrator\n"
348          "usage: rm_entry <dir>\n"},
349         {"pool_list", lfs_poollist, 0,
350          "List pools or pool OSTs\n"
351          "usage: pool_list <fsname>[.<pool>] | <pathname>\n"},
352         {"find", lfs_find, 0,
353          "find files matching given attributes recursively in directory tree.\n"
354          "usage: find <directory|filename> ...\n"
355          "     [[!] --atime|-A [+-]N] [[!] --ctime|-C [+-]N]\n"
356          "     [[!] --mtime|-M [+-]N] [--maxdepth|-D N]\n"
357          "     [[!] --mdt-index|--mdt|-m <uuid|index,...>]\n"
358          "     [[!] --name|-n <pattern>] [[!] --ost|-O <uuid|index,...>]\n"
359          "     [--print|-P] [--print0|-0] [[!] --size|-s [+-]N[bkMGTPE]]\n"
360          "     [[!] --stripe-count|-c [+-]<stripes>]\n"
361          "     [[!] --stripe-index|-i <index,...>]\n"
362          "     [[!] --stripe-size|-S [+-]N[kMGT]] [[!] --type|-t <filetype>]\n"
363          "     [[!] --gid|-g|--group|-G <gid>|<gname>]\n"
364          "     [[!] --uid|-u|--user|-U <uid>|<uname>] [[!] --pool <pool>]\n"
365          "     [[!] --projid <projid>]\n"
366          "     [[!] --layout|-L released,raid0,mdt]\n"
367          "     [[!] --component-count [+-]<comp_cnt>]\n"
368          "     [[!] --component-start [+-]N[kMGTPE]]\n"
369          "     [[!] --component-end|-E [+-]N[kMGTPE]]\n"
370          "     [[!] --component-flags <comp_flags>]\n"
371          "     [[!] --mirror-count|-N [+-]<n>]\n"
372          "     [[!] --mirror-state <[^]state>]\n"
373          "     [[!] --mdt-count|-T [+-]<stripes>]\n"
374          "     [[!] --mdt-hash|-H <hashtype>\n"
375          "\t !: used before an option indicates 'NOT' requested attribute\n"
376          "\t -: used before a value indicates less than requested value\n"
377          "\t +: used before a value indicates more than requested value\n"
378          "\thashtype:   hash type of the striped directory.\n"
379          "\t            fnv_1a_64 FNV-1a hash algorithm\n"
380          "\t            all_char  sum of characters % MDT_COUNT\n"},
381         {"check", lfs_check, 0,
382          "Display the status of MDS or OSTs (as specified in the command)\n"
383          "or all the servers (MDS and OSTs).\n"
384          "usage: check <osts|mds|servers>"},
385         {"osts", lfs_osts, 0, "list OSTs connected to client "
386          "[for specified path only]\n" "usage: osts [path]"},
387         {"mdts", lfs_mdts, 0, "list MDTs connected to client "
388          "[for specified path only]\n" "usage: mdts [path]"},
389         {"df", lfs_df, 0,
390          "report filesystem disk space usage or inodes usage"
391          "of each MDS and all OSDs or a batch belonging to a specific pool .\n"
392          "Usage: df [-i] [-h] [--lazy|-l] [--pool|-p <fsname>[.<pool>] [path]"},
393         {"getname", lfs_getname, 0, "list instances and specified mount points "
394          "[for specified path only]\n"
395          "Usage: getname [-h]|[path ...] "},
396 #ifdef HAVE_SYS_QUOTA_H
397         {"setquota", lfs_setquota, 0, "Set filesystem quotas.\n"
398          "usage: setquota <-u|-g|-p> <uname>|<uid>|<gname>|<gid>|<projid>\n"
399          "                -b <block-softlimit> -B <block-hardlimit>\n"
400          "                -i <inode-softlimit> -I <inode-hardlimit> <filesystem>\n"
401          "       setquota <-u|--user|-g|--group|-p|--projid> <uname>|<uid>|<gname>|<gid>|<projid>\n"
402          "                [--block-softlimit <block-softlimit>]\n"
403          "                [--block-hardlimit <block-hardlimit>]\n"
404          "                [--inode-softlimit <inode-softlimit>]\n"
405          "                [--inode-hardlimit <inode-hardlimit>] <filesystem>\n"
406          "       setquota [-t] <-u|--user|-g|--group|-p|--projid>\n"
407          "                [--block-grace <block-grace>]\n"
408          "                [--inode-grace <inode-grace>] <filesystem>\n"
409          "       -b can be used instead of --block-softlimit/--block-grace\n"
410          "       -B can be used instead of --block-hardlimit\n"
411          "       -i can be used instead of --inode-softlimit/--inode-grace\n"
412          "       -I can be used instead of --inode-hardlimit\n\n"
413          "Note: The total quota space will be split into many qunits and\n"
414          "      balanced over all server targets, the minimal qunit size is\n"
415          "      1M bytes for block space and 1K inodes for inode space.\n\n"
416          "      Quota space rebalancing process will stop when this mininum\n"
417          "      value is reached. As a result, quota exceeded can be returned\n"
418          "      while many targets still have 1MB or 1K inodes of spare\n"
419          "      quota space."},
420         {"quota", lfs_quota, 0, "Display disk usage and limits.\n"
421          "usage: quota [-q] [-v] [-h] [-o <obd_uuid>|-i <mdt_idx>|-I "
422                        "<ost_idx>]\n"
423          "             [<-u|-g|-p> <uname>|<uid>|<gname>|<gid>|<projid>] <filesystem>\n"
424          "       quota [-o <obd_uuid>|-i <mdt_idx>|-I <ost_idx>] -t <-u|-g|-p> <filesystem>"},
425         {"project", lfs_project, 0,
426          "Change or list project attribute for specified file or directory.\n"
427          "usage: project [-d|-r] <file|directory...>\n"
428          "         list project ID and flags on file(s) or directories\n"
429          "       project [-p id] [-s] [-r] <file|directory...>\n"
430          "         set project ID and/or inherit flag for specified file(s) or directories\n"
431          "       project -c [-d|-r [-p id] [-0]] <file|directory...>\n"
432          "         check project ID and flags on file(s) or directories, print outliers\n"
433          "       project -C [-r] [-k] <file|directory...>\n"
434          "         clear the project inherit flag and ID on the file or directory\n"
435         },
436 #endif
437         {"flushctx", lfs_flushctx, 0, "Flush security context for current user.\n"
438          "usage: flushctx [-k] [mountpoint...]"},
439         {"cp", lfs_cp, 0,
440          "Remote user copy files and directories.\n"
441          "usage: cp [OPTION]... [-T] SOURCE DEST\n\tcp [OPTION]... SOURCE... DIRECTORY\n\tcp [OPTION]... -t DIRECTORY SOURCE..."},
442         {"ls", lfs_ls, 0,
443          "Remote user list directory contents.\n"
444          "usage: ls [OPTION]... [FILE]..."},
445         {"changelog", lfs_changelog, 0,
446          "Show the metadata changes on an MDT."
447          "\nusage: changelog <mdtname> [startrec [endrec]]"},
448         {"changelog_clear", lfs_changelog_clear, 0,
449          "Indicate that old changelog records up to <endrec> are no longer of "
450          "interest to consumer <id>, allowing the system to free up space.\n"
451          "An <endrec> of 0 means all records.\n"
452          "usage: changelog_clear <mdtname> <id> <endrec>"},
453         {"fid2path", lfs_fid2path, 0,
454          "Resolve the full path(s) for given FID(s). For a specific hardlink "
455          "specify link number <linkno>.\n"
456         /* "For a historical link name, specify changelog record <recno>.\n" */
457          "usage: fid2path [--link <linkno>] <fsname|rootpath> <fid> ..."
458                 /* [ --rec <recno> ] */ },
459         {"path2fid", lfs_path2fid, 0, "Display the fid(s) for a given path(s).\n"
460          "usage: path2fid [--parents] <path> ..."},
461         {"data_version", lfs_data_version, 0, "Display file data version for "
462          "a given path.\n" "usage: data_version -[n|r|w] <path>"},
463         {"hsm_state", lfs_hsm_state, 0, "Display the HSM information (states, "
464          "undergoing actions) for given files.\n usage: hsm_state <file> ..."},
465         {"hsm_set", lfs_hsm_set, 0, "Set HSM user flag on specified files.\n"
466          "usage: hsm_set [--norelease] [--noarchive] [--dirty] [--exists] "
467          "[--archived] [--lost] [--archive-id NUM] <file> ..."},
468         {"hsm_clear", lfs_hsm_clear, 0, "Clear HSM user flag on specified "
469          "files.\n"
470          "usage: hsm_clear [--norelease] [--noarchive] [--dirty] [--exists] "
471          "[--archived] [--lost] <file> ..."},
472         {"hsm_action", lfs_hsm_action, 0, "Display current HSM request for "
473          "given files.\n" "usage: hsm_action <file> ..."},
474         {"hsm_archive", lfs_hsm_archive, 0,
475          "Archive file to external storage.\n"
476          "usage: hsm_archive [--filelist FILELIST] [--data DATA] [--archive NUM] "
477          "<file> ..."},
478         {"hsm_restore", lfs_hsm_restore, 0,
479          "Restore file from external storage.\n"
480          "usage: hsm_restore [--filelist FILELIST] [--data DATA] <file> ..."},
481         {"hsm_release", lfs_hsm_release, 0,
482          "Release files from Lustre.\n"
483          "usage: hsm_release [--filelist FILELIST] [--data DATA] <file> ..."},
484         {"hsm_remove", lfs_hsm_remove, 0,
485          "Remove file copy from external storage.\n"
486          "usage: hsm_remove [--filelist FILELIST] [--data DATA] "
487          "[--archive NUM]\n"
488          "                  (FILE [FILE ...] | "
489          "--mntpath MOUNTPATH FID [FID ...])\n"
490          "\n"
491          "Note: To remove an archived copy of a file already deleted from a "
492          "Lustre FS, the\n"
493          "--mntpath option and a list of FIDs must be specified"
494         },
495         {"hsm_cancel", lfs_hsm_cancel, 0,
496          "Cancel requests related to specified files.\n"
497          "usage: hsm_cancel [--filelist FILELIST] [--data DATA] <file> ..."},
498         {"swap_layouts", lfs_swap_layouts, 0, "Swap layouts between 2 files.\n"
499          "usage: swap_layouts <path1> <path2>"},
500         {"migrate", lfs_setstripe_migrate, 0,
501          "migrate a directory between MDTs.\n"
502          "usage: migrate --mdt-index <mdt_idx> [--verbose|-v] "
503          "<directory>\n"
504          "\tmdt_idx:      index of the destination MDT\n"
505          "\n"
506          "migrate file objects from one OST "
507          "layout\nto another (may be not safe with concurent writes).\n"
508          "usage: migrate  "
509          "[--stripe-count|-c] <stripe_count>\n"
510          "              [--stripe-index|-i] <start_ost_index>\n"
511          "              [--stripe-size|-S] <stripe_size>\n"
512          "              [--pool|-p] <pool_name>\n"
513          "              [--ost|-o] <ost_indices>\n"
514          "              [--block|-b]\n"
515          "              [--non-block|-n]\n"
516          "              [--non-direct|-D]\n"
517          "              <file|directory>\n"
518          "\tstripe_count:     number of OSTs to stripe a file over\n"
519          "\tstripe_ost_index: index of the first OST to stripe a file over\n"
520          "\tstripe_size:      number of bytes to store before moving to the next OST\n"
521          "\tpool_name:        name of the predefined pool of OSTs\n"
522          "\tost_indices:      OSTs to stripe over, in order\n"
523          "\tblock:            wait for the operation to return before continuing\n"
524          "\tnon-block:        do not wait for the operation to return\n"
525          "\tnon-direct:       do not use direct I/O to copy file contents.\n"},
526         {"mv", lfs_mv, 0,
527          "To move directories between MDTs. This command is deprecated, "
528          "use \"migrate\" instead.\n"
529          "usage: mv <directory|filename> [--mdt-index|-m] <mdt_index> "
530          "[--verbose|-v]\n"},
531         {"ladvise", lfs_ladvise, 0,
532          "Provide servers with advice about access patterns for a file.\n"
533          "usage: ladvise [--advice|-a ADVICE] [--start|-s START[kMGT]]\n"
534          "               [--background|-b] [--unset|-u]\n\n"
535          "               {[--end|-e END[kMGT]] | [--length|-l LENGTH[kMGT]]}\n"
536          "               {[--mode|-m [READ,WRITE]}\n"
537          "               <file> ...\n"},
538         {"mirror", lfs_mirror, mirror_cmdlist,
539          "lfs commands used to manage files with mirrored components:\n"
540          "lfs mirror create - create a mirrored file or directory\n"
541          "lfs mirror extend - add mirror(s) to an existing file\n"
542          "lfs mirror split  - split a mirror from an existing mirrored file\n"
543          "lfs mirror resync - resynchronize out-of-sync mirrored file(s)\n"
544          "lfs mirror verify - verify mirrored file(s)\n"},
545         {"help", Parser_help, 0, "help"},
546         {"exit", Parser_quit, 0, "quit"},
547         {"quit", Parser_quit, 0, "quit"},
548         {"--version", Parser_version, 0,
549          "output build version of the utility and exit"},
550         {"--list-commands", lfs_list_commands, 0,
551          "list commands supported by the utility and exit"},
552         { 0, 0, 0, NULL }
553 };
554
555
556 static int check_hashtype(const char *hashtype)
557 {
558         int i;
559
560         for (i = LMV_HASH_TYPE_ALL_CHARS; i < LMV_HASH_TYPE_MAX; i++)
561                 if (strcmp(hashtype, mdt_hash_name[i]) == 0)
562                         return i;
563
564         return 0;
565 }
566
567
568 static const char *error_loc = "syserror";
569
570 enum {
571         MIGRATION_NONBLOCK      = 1 << 0,
572         MIGRATION_MIRROR        = 1 << 1,
573         MIGRATION_NONDIRECT     = 1 << 2,
574 };
575
576 static int lfs_component_create(char *fname, int open_flags, mode_t open_mode,
577                                 struct llapi_layout *layout);
578
579 static int
580 migrate_open_files(const char *name, __u64 migration_flags,
581                    const struct llapi_stripe_param *param,
582                    struct llapi_layout *layout, int *fd_src, int *fd_tgt)
583 {
584         int                      fd = -1;
585         int                      fdv = -1;
586         int                      rflags;
587         int                      mdt_index;
588         int                      random_value;
589         char                     parent[PATH_MAX];
590         char                     volatile_file[PATH_MAX];
591         char                    *ptr;
592         int                      rc;
593         struct stat              st;
594         struct stat              stv;
595
596         if (param == NULL && layout == NULL) {
597                 error_loc = "layout information";
598                 return -EINVAL;
599         }
600
601         /* search for file directory pathname */
602         if (strlen(name) > sizeof(parent) - 1) {
603                 error_loc = "source file name";
604                 return -ERANGE;
605         }
606
607         strncpy(parent, name, sizeof(parent));
608         ptr = strrchr(parent, '/');
609         if (ptr == NULL) {
610                 if (getcwd(parent, sizeof(parent)) == NULL) {
611                         error_loc = "getcwd";
612                         return -errno;
613                 }
614         } else {
615                 if (ptr == parent) /* leading '/' */
616                         ptr = parent + 1;
617                 *ptr = '\0';
618         }
619
620         /* open file, direct io */
621         /* even if the file is only read, WR mode is nedeed to allow
622          * layout swap on fd */
623         rflags = O_RDWR;
624         if (!(migration_flags & MIGRATION_NONDIRECT))
625                 rflags |= O_DIRECT;
626         fd = open(name, rflags);
627         if (fd < 0) {
628                 rc = -errno;
629                 error_loc = "cannot open source file";
630                 return rc;
631         }
632
633         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
634         if (rc < 0) {
635                 error_loc = "cannot get MDT index";
636                 goto out;
637         }
638
639         do {
640                 int open_flags = O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW;
641                 mode_t open_mode = S_IRUSR | S_IWUSR;
642
643                 random_value = random();
644                 rc = snprintf(volatile_file, sizeof(volatile_file),
645                               "%s/%s:%.4X:%.4X", parent, LUSTRE_VOLATILE_HDR,
646                               mdt_index, random_value);
647                 if (rc >= sizeof(volatile_file)) {
648                         rc = -ENAMETOOLONG;
649                         break;
650                 }
651
652                 /* create, open a volatile file, use caching (ie no directio) */
653                 if (param != NULL)
654                         fdv = llapi_file_open_param(volatile_file, open_flags,
655                                                     open_mode, param);
656                 else
657                         fdv = lfs_component_create(volatile_file, open_flags,
658                                                    open_mode, layout);
659         } while (fdv < 0 && (rc = fdv) == -EEXIST);
660
661         if (rc < 0) {
662                 error_loc = "cannot create volatile file";
663                 goto out;
664         }
665
666         /* In case the MDT does not support creation of volatile files
667          * we should try to unlink it. */
668         (void)unlink(volatile_file);
669
670         /* Not-owner (root?) special case.
671          * Need to set owner/group of volatile file like original.
672          * This will allow to pass related check during layout_swap.
673          */
674         rc = fstat(fd, &st);
675         if (rc != 0) {
676                 rc = -errno;
677                 error_loc = "cannot stat source file";
678                 goto out;
679         }
680
681         rc = fstat(fdv, &stv);
682         if (rc != 0) {
683                 rc = -errno;
684                 error_loc = "cannot stat volatile";
685                 goto out;
686         }
687
688         if (st.st_uid != stv.st_uid || st.st_gid != stv.st_gid) {
689                 rc = fchown(fdv, st.st_uid, st.st_gid);
690                 if (rc != 0) {
691                         rc = -errno;
692                         error_loc = "cannot change ownwership of volatile";
693                         goto out;
694                 }
695         }
696
697 out:
698         if (rc < 0) {
699                 if (fd > 0)
700                         close(fd);
701                 if (fdv > 0)
702                         close(fdv);
703         } else {
704                 *fd_src = fd;
705                 *fd_tgt = fdv;
706                 error_loc = NULL;
707         }
708         return rc;
709 }
710
711 static int migrate_copy_data(int fd_src, int fd_dst, int (*check_file)(int))
712 {
713         struct llapi_layout *layout;
714         size_t   buf_size = 4 * 1024 * 1024;
715         void    *buf = NULL;
716         ssize_t  rsize = -1;
717         ssize_t  wsize = 0;
718         size_t   rpos = 0;
719         size_t   wpos = 0;
720         off_t    bufoff = 0;
721         int      rc;
722
723         layout = llapi_layout_get_by_fd(fd_src, 0);
724         if (layout != NULL) {
725                 uint64_t stripe_size;
726
727                 rc = llapi_layout_stripe_size_get(layout, &stripe_size);
728                 if (rc == 0)
729                         buf_size = stripe_size;
730
731                 llapi_layout_free(layout);
732         }
733
734         /* Use a page-aligned buffer for direct I/O */
735         rc = posix_memalign(&buf, getpagesize(), buf_size);
736         if (rc != 0)
737                 return -rc;
738
739         while (1) {
740                 /* read new data only if we have written all
741                  * previously read data */
742                 if (wpos == rpos) {
743                         if (check_file) {
744                                 rc = check_file(fd_src);
745                                 if (rc < 0)
746                                         break;
747                         }
748
749                         rsize = read(fd_src, buf, buf_size);
750                         if (rsize < 0) {
751                                 rc = -errno;
752                                 break;
753                         }
754                         rpos += rsize;
755                         bufoff = 0;
756                 }
757                 /* eof ? */
758                 if (rsize == 0)
759                         break;
760
761                 wsize = write(fd_dst, buf + bufoff, rpos - wpos);
762                 if (wsize < 0) {
763                         rc = -errno;
764                         break;
765                 }
766                 wpos += wsize;
767                 bufoff += wsize;
768         }
769
770         if (rc == 0) {
771                 rc = fsync(fd_dst);
772                 if (rc < 0)
773                         rc = -errno;
774         }
775
776         free(buf);
777         return rc;
778 }
779
780 static int migrate_copy_timestamps(int fd, int fdv)
781 {
782         struct stat st;
783
784         if (fstat(fd, &st) == 0) {
785                 struct timeval tv[2] = {
786                         {.tv_sec = st.st_atime},
787                         {.tv_sec = st.st_mtime}
788                 };
789
790                 return futimes(fdv, tv);
791         }
792
793         return -errno;
794 }
795
796 static int migrate_block(int fd, int fdv)
797 {
798         __u64   dv1;
799         int     gid;
800         int     rc;
801         int     rc2;
802
803         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
804         if (rc < 0) {
805                 error_loc = "cannot get dataversion";
806                 return rc;
807         }
808
809         do
810                 gid = random();
811         while (gid == 0);
812
813         /* The grouplock blocks all concurrent accesses to the file.
814          * It has to be taken after llapi_get_data_version as it would
815          * block it too. */
816         rc = llapi_group_lock(fd, gid);
817         if (rc < 0) {
818                 error_loc = "cannot get group lock";
819                 return rc;
820         }
821
822         rc = migrate_copy_data(fd, fdv, NULL);
823         if (rc < 0) {
824                 error_loc = "data copy failed";
825                 goto out_unlock;
826         }
827
828         /* Make sure we keep original atime/mtime values */
829         rc = migrate_copy_timestamps(fd, fdv);
830         if (rc < 0) {
831                 error_loc = "timestamp copy failed";
832                 goto out_unlock;
833         }
834
835         /* swap layouts
836          * for a migration we need to check data version on file did
837          * not change.
838          *
839          * Pass in gid=0 since we already own grouplock. */
840         rc = llapi_fswap_layouts_grouplock(fd, fdv, dv1, 0, 0,
841                                            SWAP_LAYOUTS_CHECK_DV1);
842         if (rc == -EAGAIN) {
843                 error_loc = "file changed";
844                 goto out_unlock;
845         } else if (rc < 0) {
846                 error_loc = "cannot swap layout";
847                 goto out_unlock;
848         }
849
850 out_unlock:
851         rc2 = llapi_group_unlock(fd, gid);
852         if (rc2 < 0 && rc == 0) {
853                 error_loc = "unlock group lock";
854                 rc = rc2;
855         }
856
857         return rc;
858 }
859
860 /**
861  * Internal helper for migrate_copy_data(). Check lease and report error if
862  * need be.
863  *
864  * \param[in]  fd           File descriptor on which to check the lease.
865  *
866  * \retval 0       Migration can keep on going.
867  * \retval -errno  Error occurred, abort migration.
868  */
869 static int check_lease(int fd)
870 {
871         int rc;
872
873         rc = llapi_lease_check(fd);
874         if (rc > 0)
875                 return 0; /* llapi_check_lease returns > 0 on success. */
876
877         return -EBUSY;
878 }
879
880 static int migrate_nonblock(int fd, int fdv)
881 {
882         __u64   dv1;
883         __u64   dv2;
884         int     rc;
885
886         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
887         if (rc < 0) {
888                 error_loc = "cannot get data version";
889                 return rc;
890         }
891
892         rc = migrate_copy_data(fd, fdv, check_lease);
893         if (rc < 0) {
894                 error_loc = "data copy failed";
895                 return rc;
896         }
897
898         rc = llapi_get_data_version(fd, &dv2, LL_DV_RD_FLUSH);
899         if (rc != 0) {
900                 error_loc = "cannot get data version";
901                 return rc;
902         }
903
904         if (dv1 != dv2) {
905                 rc = -EAGAIN;
906                 error_loc = "source file changed";
907                 return rc;
908         }
909
910         /* Make sure we keep original atime/mtime values */
911         rc = migrate_copy_timestamps(fd, fdv);
912         if (rc < 0) {
913                 error_loc = "timestamp copy failed";
914                 return rc;
915         }
916
917         return 0;
918 }
919
920 static int lfs_component_set(char *fname, int comp_id,
921                              __u32 flags, __u32 neg_flags)
922 {
923         __u32 ids[2];
924         __u32 flags_array[2];
925         size_t count = 0;
926         int rc;
927
928         if (flags) {
929                 ids[count] = comp_id;
930                 flags_array[count] = flags;
931                 ++count;
932         }
933
934         if (neg_flags) {
935                 ids[count] = comp_id;
936                 flags_array[count] = neg_flags | LCME_FL_NEG;
937                 ++count;
938         }
939
940         rc = llapi_layout_file_comp_set(fname, ids, flags_array, count);
941         if (rc)
942                 fprintf(stderr,
943                         "%s: cannot change the flags of component '%#x' of file '%s': %x / ^(%x)\n",
944                         progname, comp_id, fname, flags, neg_flags);
945
946         return rc;
947 }
948
949 static int lfs_component_del(char *fname, __u32 comp_id,
950                              __u32 flags, __u32 neg_flags)
951 {
952         int     rc = 0;
953
954         if (flags && neg_flags)
955                 return -EINVAL;
956
957         if (!flags && neg_flags)
958                 flags = neg_flags | LCME_FL_NEG;
959
960         if ((flags && comp_id) || (!flags && !comp_id))
961                 return -EINVAL;
962
963         /* LCME_FL_INIT is the only supported flag in PFL */
964         if (flags) {
965                 if (flags & ~LCME_KNOWN_FLAGS) {
966                         fprintf(stderr,
967                                 "%s setstripe: unknown flags %#x\n",
968                                 progname, flags);
969                         return -EINVAL;
970                 }
971         } else if (comp_id > LCME_ID_MAX) {
972                 fprintf(stderr, "%s setstripe: invalid component id %u\n",
973                         progname, comp_id);
974                 return -EINVAL;
975         }
976
977         rc = llapi_layout_file_comp_del(fname, comp_id, flags);
978         if (rc)
979                 fprintf(stderr,
980                         "%s setstripe: cannot delete component %#x from '%s': %s\n",
981                         progname, comp_id, fname, strerror(errno));
982         return rc;
983 }
984
985 static int lfs_component_add(char *fname, struct llapi_layout *layout)
986 {
987         int     rc;
988
989         if (layout == NULL)
990                 return -EINVAL;
991
992         rc = llapi_layout_file_comp_add(fname, layout);
993         if (rc)
994                 fprintf(stderr, "Add layout component(s) to %s failed. %s\n",
995                         fname, strerror(errno));
996         return rc;
997 }
998
999 static int lfs_component_create(char *fname, int open_flags, mode_t open_mode,
1000                                 struct llapi_layout *layout)
1001 {
1002         struct stat     st;
1003         int     fd;
1004
1005         if (layout == NULL)
1006                 return -EINVAL;
1007
1008         fd = lstat(fname, &st);
1009         if (fd == 0 && S_ISDIR(st.st_mode))
1010                 open_flags = O_DIRECTORY | O_RDONLY;
1011
1012         fd = llapi_layout_file_open(fname, open_flags, open_mode, layout);
1013         if (fd < 0)
1014                 fprintf(stderr, "%s: cannot %s '%s': %s\n", progname,
1015                         S_ISDIR(st.st_mode) ?
1016                                 "set default composite layout for" :
1017                                 "create composite file",
1018                         fname, strerror(errno));
1019         return fd;
1020 }
1021
1022 static int lfs_migrate(char *name, __u64 migration_flags,
1023                        struct llapi_stripe_param *param,
1024                        struct llapi_layout *layout)
1025 {
1026         int fd = -1;
1027         int fdv = -1;
1028         int rc;
1029
1030         rc = migrate_open_files(name, migration_flags, param, layout,
1031                                 &fd, &fdv);
1032         if (rc < 0)
1033                 goto out;
1034
1035         if (!(migration_flags & MIGRATION_NONBLOCK)) {
1036                 /* Blocking mode (forced if servers do not support file lease).
1037                  * It is also the default mode, since we cannot distinguish
1038                  * between a broken lease and a server that does not support
1039                  * atomic swap/close (LU-6785) */
1040                 rc = migrate_block(fd, fdv);
1041                 goto out;
1042         }
1043
1044         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1045         if (rc < 0) {
1046                 error_loc = "cannot get lease";
1047                 goto out;
1048         }
1049
1050         rc = migrate_nonblock(fd, fdv);
1051         if (rc < 0) {
1052                 llapi_lease_release(fd);
1053                 goto out;
1054         }
1055
1056         /* Atomically put lease, swap layouts and close.
1057          * for a migration we need to check data version on file did
1058          * not change. */
1059         rc = llapi_fswap_layouts(fd, fdv, 0, 0, SWAP_LAYOUTS_CLOSE);
1060         if (rc < 0) {
1061                 error_loc = "cannot swap layout";
1062                 goto out;
1063         }
1064
1065 out:
1066         if (fd >= 0)
1067                 close(fd);
1068
1069         if (fdv >= 0)
1070                 close(fdv);
1071
1072         if (rc < 0)
1073                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1074                         progname, name, error_loc, strerror(-rc));
1075         return rc;
1076 }
1077
1078 static int comp_str2flags(char *string, __u32 *flags, __u32 *neg_flags)
1079 {
1080         char *name;
1081
1082         if (string == NULL)
1083                 return -EINVAL;
1084
1085         *flags = 0;
1086         *neg_flags = 0;
1087         for (name = strtok(string, ","); name; name = strtok(NULL, ",")) {
1088                 bool found = false;
1089                 int i;
1090
1091                 for (i = 0; i < ARRAY_SIZE(comp_flags_table); i++) {
1092                         __u32 comp_flag = comp_flags_table[i].cfn_flag;
1093                         const char *comp_name = comp_flags_table[i].cfn_name;
1094
1095                         if (strcmp(name, comp_name) == 0) {
1096                                 *flags |= comp_flag;
1097                                 found = true;
1098                         } else if (strncmp(name, "^", 1) == 0 &&
1099                                    strcmp(name + 1, comp_name) == 0) {
1100                                 *neg_flags |= comp_flag;
1101                                 found = true;
1102                         }
1103                 }
1104                 if (!found) {
1105                         llapi_printf(LLAPI_MSG_ERROR,
1106                                      "%s: component flag '%s' not supported\n",
1107                                      progname, name);
1108                         return -EINVAL;
1109                 }
1110         }
1111
1112         if (!*flags && !*neg_flags)
1113                 return -EINVAL;
1114
1115         /* don't allow to set and exclude the same flag */
1116         if (*flags & *neg_flags)
1117                 return -EINVAL;
1118
1119         return 0;
1120 }
1121
1122 static int mirror_str2state(char *string, __u16 *state, __u16 *neg_state)
1123 {
1124         if (string == NULL)
1125                 return -EINVAL;
1126
1127         *state = 0;
1128         *neg_state = 0;
1129
1130         if (strncmp(string, "^", 1) == 0) {
1131                 *neg_state = llapi_layout_string_flags(string + 1);
1132                 if (*neg_state != 0)
1133                         return 0;
1134         } else {
1135                 *state = llapi_layout_string_flags(string);
1136                 if (*state != 0)
1137                         return 0;
1138         }
1139
1140         llapi_printf(LLAPI_MSG_ERROR,
1141                      "%s: mirrored file state '%s' not supported\n",
1142                      progname, string);
1143         return -EINVAL;
1144 }
1145
1146 /**
1147  * struct mirror_args - Command-line arguments for mirror(s).
1148  * @m_count:  Number of mirrors to be created with this layout.
1149  * @m_flags:  Mirror level flags, only 'prefer' is supported.
1150  * @m_layout: Mirror layout.
1151  * @m_file:   A victim file. Its layout will be split and used as a mirror.
1152  * @m_next:   Point to the next node of the list.
1153  *
1154  * Command-line arguments for mirror(s) will be parsed and stored in
1155  * a linked list that consists of this structure.
1156  */
1157 struct mirror_args {
1158         __u32                   m_count;
1159         __u32                   m_flags;
1160         struct llapi_layout     *m_layout;
1161         const char              *m_file;
1162         struct mirror_args      *m_next;
1163 };
1164
1165 static int mirror_sanity_check_flags(struct llapi_layout *layout, void *unused)
1166 {
1167         uint32_t flags;
1168         int rc;
1169
1170         rc = llapi_layout_comp_flags_get(layout, &flags);
1171         if (rc)
1172                 return -errno;
1173
1174         if (flags & LCME_FL_NEG) {
1175                 fprintf(stderr, "error: %s: negative flags are not supported\n",
1176                         progname);
1177                 return -EINVAL;
1178         }
1179
1180         if (flags & LCME_FL_STALE) {
1181                 fprintf(stderr, "error: %s: setting '%s' is not supported\n",
1182                         progname, comp_flags_table[LCME_FL_STALE].cfn_name);
1183                 return -EINVAL;
1184         }
1185
1186         return LLAPI_LAYOUT_ITER_CONT;
1187 }
1188
1189 static inline int mirror_sanity_check_one(struct llapi_layout *layout)
1190 {
1191         uint64_t start, end;
1192         uint64_t pattern;
1193         int rc;
1194
1195         /* LU-10112: do not support dom+flr in phase 1 */
1196         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
1197         if (rc)
1198                 return -errno;
1199
1200         rc = llapi_layout_pattern_get(layout, &pattern);
1201         if (rc)
1202                 return -errno;
1203
1204         if (pattern == LOV_PATTERN_MDT || pattern == LLAPI_LAYOUT_MDT) {
1205                 fprintf(stderr, "error: %s: doesn't support dom+flr for now\n",
1206                         progname);
1207                 return -ENOTSUP;
1208         }
1209
1210         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_LAST);
1211         if (rc)
1212                 return -errno;
1213
1214         rc = llapi_layout_comp_extent_get(layout, &start, &end);
1215         if (rc)
1216                 return -errno;
1217
1218         if (end != LUSTRE_EOF) {
1219                 fprintf(stderr, "error: %s: mirror layout doesn't reach eof\n",
1220                         progname);
1221                 return -EINVAL;
1222         }
1223
1224         rc = llapi_layout_comp_iterate(layout, mirror_sanity_check_flags, NULL);
1225         return rc;
1226 }
1227
1228 /**
1229  * enum mirror_flags - Flags for extending a mirrored file.
1230  * @MF_NO_VERIFY: Indicates not to verify the mirror(s) from victim file(s)
1231  *             in case the victim file(s) contains the same data as the
1232  *             original mirrored file.
1233  * @MF_DESTROY: Indicates to delete the mirror from the mirrored file.
1234  *
1235  * Flags for extending a mirrored file.
1236  */
1237 enum mirror_flags {
1238         MF_NO_VERIFY    = 0x1,
1239         MF_DESTROY      = 0x2,
1240 };
1241
1242 /**
1243  * mirror_create_sanity_check() - Check mirror list.
1244  * @list:  A linked list that stores the mirror arguments.
1245  *
1246  * This function does a sanity check on @list for creating
1247  * a mirrored file.
1248  *
1249  * Return: 0 on success or a negative error code on failure.
1250  */
1251 static int mirror_create_sanity_check(const char *fname,
1252                                       struct mirror_args *list)
1253 {
1254         int rc = 0;
1255         bool has_m_file = false;
1256         bool has_m_layout = false;
1257
1258         if (list == NULL)
1259                 return -EINVAL;
1260
1261         if (fname) {
1262                 struct llapi_layout *layout;
1263
1264                 layout = llapi_layout_get_by_path(fname, 0);
1265                 if (!layout) {
1266                         fprintf(stderr,
1267                                 "error: %s: file '%s' couldn't get layout\n",
1268                                 progname, fname);
1269                         return -ENODATA;
1270                 }
1271
1272                 rc = mirror_sanity_check_one(layout);
1273                 llapi_layout_free(layout);
1274
1275                 if (rc)
1276                         return rc;
1277         }
1278
1279         while (list != NULL) {
1280                 if (list->m_file != NULL) {
1281                         has_m_file = true;
1282                         llapi_layout_free(list->m_layout);
1283
1284                         list->m_layout =
1285                                 llapi_layout_get_by_path(list->m_file, 0);
1286                         if (list->m_layout == NULL) {
1287                                 fprintf(stderr,
1288                                         "error: %s: file '%s' has no layout\n",
1289                                         progname, list->m_file);
1290                                 return -ENODATA;
1291                         }
1292                 } else {
1293                         has_m_layout = true;
1294                         if (list->m_layout == NULL) {
1295                                 fprintf(stderr, "error: %s: no mirror layout\n",
1296                                         progname);
1297                                 return -EINVAL;
1298                         }
1299                 }
1300
1301                 rc = mirror_sanity_check_one(list->m_layout);
1302                 if (rc)
1303                         return rc;
1304
1305                 list = list->m_next;
1306         }
1307
1308         if (has_m_file && has_m_layout) {
1309                 fprintf(stderr, "error: %s: -f <victim_file> option should not "
1310                         "be specified with setstripe options or "
1311                         "--parent option\n", progname);
1312                 return -EINVAL;
1313         }
1314
1315         return 0;
1316 }
1317
1318 static int mirror_set_flags(struct llapi_layout *layout, void *cbdata)
1319 {
1320         __u32 mirror_flags = *(__u32 *)cbdata;
1321         uint32_t flags;
1322         int rc;
1323
1324         rc = llapi_layout_comp_flags_get(layout, &flags);
1325         if (rc < 0)
1326                 return rc;
1327
1328         if (!flags) {
1329                 rc = llapi_layout_comp_flags_set(layout, mirror_flags);
1330                 if (rc)
1331                         return rc;
1332         }
1333
1334         return LLAPI_LAYOUT_ITER_CONT;
1335 }
1336
1337 /**
1338  * mirror_create() - Create a mirrored file.
1339  * @fname:        The file to be created.
1340  * @mirror_list:  A linked list that stores the mirror arguments.
1341  *
1342  * This function creates a mirrored file @fname with the mirror(s)
1343  * from @mirror_list.
1344  *
1345  * Return: 0 on success or a negative error code on failure.
1346  */
1347 static int mirror_create(char *fname, struct mirror_args *mirror_list)
1348 {
1349         struct llapi_layout *layout = NULL;
1350         struct mirror_args *cur_mirror = NULL;
1351         uint16_t mirror_count = 0;
1352         int i = 0;
1353         int rc = 0;
1354
1355         rc = mirror_create_sanity_check(NULL, mirror_list);
1356         if (rc)
1357                 return rc;
1358
1359         cur_mirror = mirror_list;
1360         while (cur_mirror != NULL) {
1361                 rc = llapi_layout_comp_iterate(cur_mirror->m_layout,
1362                                                mirror_set_flags,
1363                                                &cur_mirror->m_flags);
1364                 if (rc) {
1365                         rc = -errno;
1366                         fprintf(stderr, "%s: failed to set mirror flags\n",
1367                                 progname);
1368                         goto error;
1369                 }
1370
1371                 for (i = 0; i < cur_mirror->m_count; i++) {
1372                         rc = llapi_layout_merge(&layout, cur_mirror->m_layout);
1373                         if (rc) {
1374                                 rc = -errno;
1375                                 fprintf(stderr, "error: %s: "
1376                                         "merge layout failed: %s\n",
1377                                         progname, strerror(errno));
1378                                 goto error;
1379                         }
1380                 }
1381                 mirror_count += cur_mirror->m_count;
1382                 cur_mirror = cur_mirror->m_next;
1383         }
1384
1385         if (layout == NULL) {
1386                 fprintf(stderr, "error: %s: layout is NULL\n", progname);
1387                 return -EINVAL;
1388         }
1389
1390         rc = llapi_layout_mirror_count_set(layout, mirror_count);
1391         if (rc) {
1392                 rc = -errno;
1393                 fprintf(stderr, "error: %s: set mirror count failed: %s\n",
1394                         progname, strerror(errno));
1395                 goto error;
1396         }
1397
1398         rc = lfs_component_create(fname, O_CREAT | O_WRONLY, 0644,
1399                                   layout);
1400         if (rc >= 0) {
1401                 close(rc);
1402                 rc = 0;
1403         }
1404
1405 error:
1406         llapi_layout_free(layout);
1407         return rc;
1408 }
1409
1410 /**
1411  * Compare files and check lease on @fd.
1412  *
1413  * \retval bytes number of bytes are the same
1414  */
1415 static ssize_t mirror_file_compare(int fd, int fdv)
1416 {
1417         const size_t buflen = 4 * 1024 * 1024; /* 4M */
1418         void *buf;
1419         ssize_t bytes_done = 0;
1420         ssize_t bytes_read = 0;
1421
1422         buf = malloc(buflen * 2);
1423         if (!buf)
1424                 return -ENOMEM;
1425
1426         while (1) {
1427                 if (!llapi_lease_check(fd)) {
1428                         bytes_done = -EBUSY;
1429                         break;
1430                 }
1431
1432                 bytes_read = read(fd, buf, buflen);
1433                 if (bytes_read <= 0)
1434                         break;
1435
1436                 if (bytes_read != read(fdv, buf + buflen, buflen))
1437                         break;
1438
1439                 /* XXX: should compute the checksum on each buffer and then
1440                  * compare checksum to avoid cache collision */
1441                 if (memcmp(buf, buf + buflen, bytes_read))
1442                         break;
1443
1444                 bytes_done += bytes_read;
1445         }
1446
1447         free(buf);
1448
1449         return bytes_done;
1450 }
1451
1452 static int mirror_extend_file(const char *fname, const char *victim_file,
1453                               enum mirror_flags mirror_flags)
1454 {
1455         int fd = -1;
1456         int fdv = -1;
1457         struct stat stbuf;
1458         struct stat stbuf_v;
1459         struct ll_ioc_lease *data = NULL;
1460         int rc;
1461
1462         fd = open(fname, O_RDWR);
1463         if (fd < 0) {
1464                 error_loc = "open source file";
1465                 rc = -errno;
1466                 goto out;
1467         }
1468
1469         fdv = open(victim_file, O_RDWR);
1470         if (fdv < 0) {
1471                 error_loc = "open target file";
1472                 rc = -errno;
1473                 goto out;
1474         }
1475
1476         if (fstat(fd, &stbuf) || fstat(fdv, &stbuf_v)) {
1477                 error_loc = "stat source or target file";
1478                 rc = -errno;
1479                 goto out;
1480         }
1481
1482         if (stbuf.st_dev != stbuf_v.st_dev) {
1483                 error_loc = "stat source and target file";
1484                 rc = -EXDEV;
1485                 goto out;
1486         }
1487
1488         /* mirrors should be of the same size */
1489         if (stbuf.st_size != stbuf_v.st_size) {
1490                 error_loc = "file sizes don't match";
1491                 rc = -EINVAL;
1492                 goto out;
1493         }
1494
1495         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1496         if (rc < 0) {
1497                 error_loc = "cannot get lease";
1498                 goto out;
1499         }
1500
1501         if (!(mirror_flags & MF_NO_VERIFY)) {
1502                 ssize_t ret;
1503                 /* mirrors should have the same contents */
1504                 ret = mirror_file_compare(fd, fdv);
1505                 if (ret != stbuf.st_size) {
1506                         error_loc = "file busy or contents don't match";
1507                         rc = ret < 0 ? ret : -EINVAL;
1508                         goto out;
1509                 }
1510         }
1511
1512         /* Get rid of caching pages from clients */
1513         rc = llapi_file_flush(fd);
1514         if (rc < 0) {
1515                 error_loc = "cannot get data version";
1516                 goto out;
1517         }
1518
1519         rc = llapi_file_flush(fdv);
1520         if (rc < 0) {
1521                 error_loc = "cannot get data version";
1522                 goto out;
1523
1524         }
1525
1526         /* Make sure we keep original atime/mtime values */
1527         rc = migrate_copy_timestamps(fd, fdv);
1528         if (rc < 0) {
1529                 error_loc = "cannot copy timestamp";
1530                 goto out;
1531         }
1532
1533         /* Atomically put lease, merge layouts and close. */
1534         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1535         if (!data) {
1536                 error_loc = "memory allocation";
1537                 goto out;
1538         }
1539         data->lil_mode = LL_LEASE_UNLCK;
1540         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1541         data->lil_count = 1;
1542         data->lil_ids[0] = fdv;
1543         rc = llapi_lease_set(fd, data);
1544         if (rc < 0) {
1545                 error_loc = "cannot merge layout";
1546                 goto out;
1547         } else if (rc == 0) {
1548                 rc = -EBUSY;
1549                 error_loc = "lost lease lock";
1550                 goto out;
1551         }
1552         rc = 0;
1553
1554 out:
1555         if (data)
1556                 free(data);
1557         if (fd >= 0)
1558                 close(fd);
1559         if (fdv >= 0)
1560                 close(fdv);
1561         if (!rc)
1562                 (void) unlink(victim_file);
1563         if (rc < 0)
1564                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1565                         progname, fname, error_loc, strerror(-rc));
1566         return rc;
1567 }
1568
1569 static int mirror_extend_layout(char *name, struct llapi_layout *layout)
1570 {
1571         struct ll_ioc_lease *data = NULL;
1572         int fd = -1;
1573         int fdv = -1;
1574         int rc;
1575
1576         rc = migrate_open_files(name, 0, NULL, layout, &fd, &fdv);
1577         if (rc < 0)
1578                 goto out;
1579
1580         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1581         if (rc < 0) {
1582                 error_loc = "cannot get lease";
1583                 goto out;
1584         }
1585
1586         rc = migrate_nonblock(fd, fdv);
1587         if (rc < 0) {
1588                 llapi_lease_release(fd);
1589                 goto out;
1590         }
1591
1592         /* Atomically put lease, merge layouts and close. */
1593         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1594         if (!data) {
1595                 error_loc = "memory allocation";
1596                 goto out;
1597         }
1598         data->lil_mode = LL_LEASE_UNLCK;
1599         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1600         data->lil_count = 1;
1601         data->lil_ids[0] = fdv;
1602         rc = llapi_lease_set(fd, data);
1603         if (rc < 0) {
1604                 error_loc = "cannot merge layout";
1605                 goto out;
1606         } else if (rc == 0) {
1607                 rc = -EBUSY;
1608                 error_loc = "lost lease lock";
1609                 goto out;
1610         }
1611         rc = 0;
1612
1613 out:
1614         if (data)
1615                 free(data);
1616         if (fd >= 0)
1617                 close(fd);
1618         if (fdv >= 0)
1619                 close(fdv);
1620         if (rc < 0)
1621                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1622                         progname, name, error_loc, strerror(-rc));
1623         return rc;
1624 }
1625
1626 static int mirror_extend(char *fname, struct mirror_args *mirror_list,
1627                          enum mirror_flags mirror_flags)
1628 {
1629         int rc;
1630
1631         rc = mirror_create_sanity_check(fname, mirror_list);
1632         if (rc)
1633                 return rc;
1634
1635         while (mirror_list) {
1636                 if (mirror_list->m_file != NULL) {
1637                         rc = mirror_extend_file(fname, mirror_list->m_file,
1638                                                 mirror_flags);
1639                 } else {
1640                         __u32 mirror_count = mirror_list->m_count;
1641
1642                         while (mirror_count > 0) {
1643                                 rc = mirror_extend_layout(fname,
1644                                                         mirror_list->m_layout);
1645                                 if (rc)
1646                                         break;
1647
1648                                 --mirror_count;
1649                         }
1650                 }
1651                 if (rc)
1652                         break;
1653
1654                 mirror_list = mirror_list->m_next;
1655         }
1656
1657         return rc;
1658 }
1659
1660 static int verify_id(struct llapi_layout *layout, void *cbdata)
1661 {
1662         uint32_t id;
1663         int rc;
1664
1665         rc = llapi_layout_mirror_id_get(layout, &id);
1666         if (rc < 0)
1667                 return rc;
1668
1669         if ((__u16)id == *(__u16 *)cbdata)
1670                 return LLAPI_LAYOUT_ITER_STOP;
1671
1672         return LLAPI_LAYOUT_ITER_CONT;
1673 }
1674
1675 static int mirror_split(const char *fname, __u16 mirror_id,
1676                         enum mirror_flags mflags, const char *victim_file)
1677 {
1678         struct llapi_layout *layout;
1679         char parent[PATH_MAX];
1680         char victim[PATH_MAX];
1681         int flags = O_CREAT | O_EXCL | O_LOV_DELAY_CREATE | O_NOFOLLOW;
1682         char *ptr;
1683         struct ll_ioc_lease *data;
1684         uint16_t mirror_count;
1685         int mdt_index;
1686         int fd, fdv;
1687         int rc;
1688
1689         /* check fname contains mirror with mirror_id */
1690         layout = llapi_layout_get_by_path(fname, 0);
1691         if (!layout) {
1692                 fprintf(stderr,
1693                         "error %s: file '%s' couldn't get layout\n",
1694                         progname, fname);
1695                 return -EINVAL;
1696         }
1697
1698         rc = mirror_sanity_check_one(layout);
1699         if (rc)
1700                 goto free_layout;
1701
1702         rc = llapi_layout_mirror_count_get(layout, &mirror_count);
1703         if (rc) {
1704                 fprintf(stderr,
1705                         "error %s: file '%s' couldn't get mirror count\n",
1706                         progname, fname);
1707                 goto free_layout;
1708         }
1709         if (mirror_count < 2) {
1710                 fprintf(stderr,
1711                         "error %s: file '%s' has %d component, cannot split\n",
1712                         progname, fname, mirror_count);
1713                 goto free_layout;
1714         }
1715
1716         rc = llapi_layout_comp_iterate(layout, verify_id, &mirror_id);
1717         if (rc < 0) {
1718                 fprintf(stderr, "error %s: failed to iterate layout of '%s'\n",
1719                         progname, fname);
1720                 goto free_layout;
1721         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
1722                 fprintf(stderr,
1723                      "error %s: file '%s' does not contain mirror with id %u\n",
1724                         progname, fname, mirror_id);
1725                 goto free_layout;
1726         }
1727
1728         fd = open(fname, O_RDWR);
1729         if (fd < 0) {
1730                 fprintf(stderr,
1731                         "error %s: open file '%s' failed: %s\n",
1732                         progname, fname, strerror(errno));
1733                 goto free_layout;
1734         }
1735
1736         /* get victim file directory pathname */
1737         if (strlen(fname) > sizeof(parent) - 1) {
1738                 fprintf(stderr, "error %s: file name of '%s' too long\n",
1739                         progname, fname);
1740                 rc = -ERANGE;
1741                 goto free_layout;
1742         }
1743         strncpy(parent, fname, sizeof(parent));
1744         ptr = strrchr(parent, '/');
1745         if (ptr == NULL) {
1746                 if (getcwd(parent, sizeof(parent)) == NULL) {
1747                         fprintf(stderr, "error %s: getcwd failed: %s\n",
1748                                 progname, strerror(errno));
1749                         rc = -errno;
1750                         goto free_layout;
1751                 }
1752         } else {
1753                 if (ptr == parent)
1754                         ptr = parent + 1;
1755                 *ptr = '\0';
1756         }
1757
1758         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
1759         if (rc < 0) {
1760                 fprintf(stderr, "%s: cannot get MDT index of '%s'\n",
1761                         progname, fname);
1762                 goto free_layout;
1763         }
1764
1765         if (victim_file == NULL) {
1766                 /* use a temp file to store the splitted layout */
1767                 if (mflags & MF_DESTROY) {
1768                         fdv = llapi_create_volatile_idx(parent, mdt_index,
1769                                                         O_LOV_DELAY_CREATE);
1770                 } else {
1771                         snprintf(victim, sizeof(victim), "%s.mirror~%u",
1772                                  fname, mirror_id);
1773                         fdv = open(victim, flags, S_IRUSR | S_IWUSR);
1774                 }
1775         } else {
1776                 /* user specified victim file */
1777                 fdv = open(victim_file, flags, S_IRUSR | S_IWUSR);
1778         }
1779
1780         if (fdv < 0) {
1781                 fprintf(stderr,
1782                         "error %s: create victim file failed: %s\n",
1783                         progname, strerror(errno));
1784                 goto close_fd;
1785         }
1786
1787         /* get lease lock of fname */
1788         rc = llapi_lease_acquire(fd, LL_LEASE_WRLCK);
1789         if (rc < 0) {
1790                 fprintf(stderr,
1791                         "error %s: cannot get lease of file '%s': %d\n",
1792                         progname, fname, rc);
1793                 goto close_victim;
1794         }
1795
1796         /* Atomatically put lease, split layouts and close. */
1797         data = malloc(offsetof(typeof(*data), lil_ids[2]));
1798         if (!data) {
1799                 rc = -ENOMEM;
1800                 goto close_victim;
1801         }
1802
1803         data->lil_mode = LL_LEASE_UNLCK;
1804         data->lil_flags = LL_LEASE_LAYOUT_SPLIT;
1805         data->lil_count = 2;
1806         data->lil_ids[0] = fdv;
1807         data->lil_ids[1] = mirror_id;
1808         rc = llapi_lease_set(fd, data);
1809         if (rc <= 0) {
1810                 if (rc == 0) /* lost lease lock */
1811                         rc = -EBUSY;
1812                 fprintf(stderr,
1813                         "error %s: cannot split '%s': %s\n",
1814                         progname, fname, strerror(-rc));
1815         } else {
1816                 rc = 0;
1817         }
1818         free(data);
1819
1820 close_victim:
1821         close(fdv);
1822 close_fd:
1823         close(fd);
1824 free_layout:
1825         llapi_layout_free(layout);
1826         return rc;
1827 }
1828
1829 /**
1830  * Parse a string containing an target index list into an array of integers.
1831  *
1832  * The input string contains a comma delimited list of individual
1833  * indices and ranges, for example "1,2-4,7". Add the indices into the
1834  * \a tgts array and remove duplicates.
1835  *
1836  * \param[out] tgts    array to store indices in
1837  * \param[in] size     size of \a tgts array
1838  * \param[in] offset   starting index in \a tgts
1839  * \param[in] arg      string containing OST index list
1840  *
1841  * \retval positive    number of indices in \a tgts
1842  * \retval -EINVAL     unable to parse \a arg
1843  */
1844 static int parse_targets(__u32 *tgts, int size, int offset, char *arg)
1845 {
1846         int rc;
1847         int nr = offset;
1848         int slots = size - offset;
1849         char *ptr = NULL;
1850         bool end_of_loop;
1851
1852         if (arg == NULL)
1853                 return -EINVAL;
1854
1855         end_of_loop = false;
1856         while (!end_of_loop) {
1857                 int start_index;
1858                 int end_index;
1859                 int i;
1860                 char *endptr = NULL;
1861
1862                 rc = -EINVAL;
1863
1864                 ptr = strchrnul(arg, ',');
1865
1866                 end_of_loop = *ptr == '\0';
1867                 *ptr = '\0';
1868
1869                 start_index = strtol(arg, &endptr, 0);
1870                 if (endptr == arg) /* no data at all */
1871                         break;
1872                 if (*endptr != '-' && *endptr != '\0') /* has invalid data */
1873                         break;
1874
1875                 end_index = start_index;
1876                 if (*endptr == '-') {
1877                         end_index = strtol(endptr + 1, &endptr, 0);
1878                         if (*endptr != '\0')
1879                                 break;
1880                         if (end_index < start_index)
1881                                 break;
1882                 }
1883
1884                 for (i = start_index; i <= end_index && slots > 0; i++) {
1885                         int j;
1886
1887                         /* remove duplicate */
1888                         for (j = 0; j < offset; j++) {
1889                                 if (tgts[j] == i)
1890                                         break;
1891                         }
1892                         if (j == offset) { /* no duplicate */
1893                                 tgts[nr++] = i;
1894                                 --slots;
1895                         }
1896                 }
1897                 if (slots == 0 && i < end_index)
1898                         break;
1899
1900                 *ptr = ',';
1901                 arg = ++ptr;
1902                 offset = nr;
1903                 rc = 0;
1904         }
1905         if (!end_of_loop && ptr != NULL)
1906                 *ptr = ',';
1907
1908         return rc < 0 ? rc : nr;
1909 }
1910
1911 struct lfs_setstripe_args {
1912         unsigned long long       lsa_comp_end;
1913         unsigned long long       lsa_stripe_size;
1914         long long                lsa_stripe_count;
1915         long long                lsa_stripe_off;
1916         __u32                    lsa_comp_flags;
1917         __u32                    lsa_comp_neg_flags;
1918         unsigned long long       lsa_pattern;
1919         int                      lsa_nr_tgts;
1920         __u32                   *lsa_tgts;
1921         char                    *lsa_pool_name;
1922 };
1923
1924 static inline void setstripe_args_init(struct lfs_setstripe_args *lsa)
1925 {
1926         memset(lsa, 0, sizeof(*lsa));
1927
1928         lsa->lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
1929         lsa->lsa_stripe_count = LLAPI_LAYOUT_DEFAULT;
1930         lsa->lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
1931         lsa->lsa_pattern = LLAPI_LAYOUT_RAID0;
1932         lsa->lsa_pool_name = NULL;
1933 }
1934
1935 /**
1936  * setstripe_args_init_inherit() - Initialize and inherit stripe options.
1937  * @lsa: Stripe options to be initialized and inherited.
1938  *
1939  * This function initializes stripe options in @lsa and inherit
1940  * stripe_size, stripe_count and OST pool_name options.
1941  *
1942  * Return: void.
1943  */
1944 static inline void setstripe_args_init_inherit(struct lfs_setstripe_args *lsa)
1945 {
1946         unsigned long long stripe_size;
1947         long long stripe_count;
1948         char *pool_name = NULL;
1949
1950         stripe_size = lsa->lsa_stripe_size;
1951         stripe_count = lsa->lsa_stripe_count;
1952         pool_name = lsa->lsa_pool_name;
1953
1954         setstripe_args_init(lsa);
1955
1956         lsa->lsa_stripe_size = stripe_size;
1957         lsa->lsa_stripe_count = stripe_count;
1958         lsa->lsa_pool_name = pool_name;
1959 }
1960
1961 static inline bool setstripe_args_specified(struct lfs_setstripe_args *lsa)
1962 {
1963         return (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT ||
1964                 lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ||
1965                 lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
1966                 lsa->lsa_pattern != LLAPI_LAYOUT_RAID0 ||
1967                 lsa->lsa_pool_name != NULL ||
1968                 lsa->lsa_comp_end != 0);
1969 }
1970
1971 /**
1972  * comp_args_to_layout() - Create or extend a composite layout.
1973  * @composite:       Pointer to the composite layout.
1974  * @lsa:             Stripe options for the new component.
1975  *
1976  * This function creates or extends a composite layout by adding a new
1977  * component with stripe options from @lsa.
1978  *
1979  * Return: 0 on success or an error code on failure.
1980  */
1981 static int comp_args_to_layout(struct llapi_layout **composite,
1982                                struct lfs_setstripe_args *lsa)
1983 {
1984         struct llapi_layout *layout = *composite;
1985         uint64_t prev_end = 0;
1986         int i = 0, rc;
1987
1988         if (layout == NULL) {
1989                 layout = llapi_layout_alloc();
1990                 if (layout == NULL) {
1991                         fprintf(stderr, "Alloc llapi_layout failed. %s\n",
1992                                 strerror(errno));
1993                         return -ENOMEM;
1994                 }
1995                 *composite = layout;
1996         } else {
1997                 uint64_t start;
1998
1999                 /* Get current component extent, current component
2000                  * must be the tail component. */
2001                 rc = llapi_layout_comp_extent_get(layout, &start, &prev_end);
2002                 if (rc) {
2003                         fprintf(stderr, "Get comp extent failed. %s\n",
2004                                 strerror(errno));
2005                         return rc;
2006                 }
2007
2008                 rc = llapi_layout_comp_add(layout);
2009                 if (rc) {
2010                         fprintf(stderr, "Add component failed. %s\n",
2011                                 strerror(errno));
2012                         return rc;
2013                 }
2014         }
2015
2016         rc = llapi_layout_comp_extent_set(layout, prev_end, lsa->lsa_comp_end);
2017         if (rc) {
2018                 fprintf(stderr, "Set extent [%lu, %llu) failed. %s\n",
2019                         prev_end, lsa->lsa_comp_end, strerror(errno));
2020                 return rc;
2021         }
2022
2023         /* Data-on-MDT component setting */
2024         if (lsa->lsa_pattern == LLAPI_LAYOUT_MDT) {
2025                 /* In case of Data-on-MDT patterns the only extra option
2026                  * applicable is stripe size option. */
2027                 if (lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
2028                         fprintf(stderr, "Option 'stripe-count' can't be "
2029                                 "specified with Data-on-MDT component: %lld\n",
2030                                 lsa->lsa_stripe_count);
2031                         return -EINVAL;
2032                 }
2033                 if (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT) {
2034                         fprintf(stderr, "Option 'stripe-size' can't be "
2035                                 "specified with Data-on-MDT component: %llu\n",
2036                                 lsa->lsa_stripe_size);
2037                         return -EINVAL;
2038                 }
2039                 if (lsa->lsa_nr_tgts != 0) {
2040                         fprintf(stderr, "Option 'ost-list' can't be specified "
2041                                 "with Data-on-MDT component: '%i'\n",
2042                                 lsa->lsa_nr_tgts);
2043                         return -EINVAL;
2044                 }
2045                 if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT) {
2046                         fprintf(stderr, "Option 'stripe-offset' can't be "
2047                                 "specified with Data-on-MDT component: %lld\n",
2048                                 lsa->lsa_stripe_off);
2049                         return -EINVAL;
2050                 }
2051                 if (lsa->lsa_pool_name != 0) {
2052                         fprintf(stderr, "Option 'pool' can't be specified "
2053                                 "with Data-on-MDT component: '%s'\n",
2054                                 lsa->lsa_pool_name);
2055                         return -EINVAL;
2056                 }
2057
2058                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2059                 if (rc) {
2060                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2061                                 lsa->lsa_pattern, strerror(errno));
2062                         return rc;
2063                 }
2064                 /* Data-on-MDT component has always single stripe up to end */
2065                 lsa->lsa_stripe_size = lsa->lsa_comp_end;
2066         }
2067
2068         rc = llapi_layout_stripe_size_set(layout, lsa->lsa_stripe_size);
2069         if (rc) {
2070                 fprintf(stderr, "Set stripe size %llu failed: %s\n",
2071                         lsa->lsa_stripe_size, strerror(errno));
2072                 return rc;
2073         }
2074
2075         rc = llapi_layout_stripe_count_set(layout, lsa->lsa_stripe_count);
2076         if (rc) {
2077                 fprintf(stderr, "Set stripe count %lld failed: %s\n",
2078                         lsa->lsa_stripe_count, strerror(errno));
2079                 return rc;
2080         }
2081
2082         rc = llapi_layout_comp_flags_set(layout, lsa->lsa_comp_flags);
2083         if (rc) {
2084                 fprintf(stderr, "Set flags 0x%x failed: %s\n",
2085                         lsa->lsa_comp_flags, strerror(errno));
2086                 return rc;
2087         }
2088
2089         if (lsa->lsa_pool_name != NULL) {
2090                 rc = llapi_layout_pool_name_set(layout, lsa->lsa_pool_name);
2091                 if (rc) {
2092                         fprintf(stderr, "Set pool name: %s failed. %s\n",
2093                                 lsa->lsa_pool_name, strerror(errno));
2094                         return rc;
2095                 }
2096         } else {
2097                 rc = llapi_layout_pool_name_set(layout, "");
2098                 if (rc) {
2099                         fprintf(stderr, "Clear pool name failed: %s\n",
2100                                 strerror(errno));
2101                         return rc;
2102                 }
2103         }
2104
2105         if (lsa->lsa_nr_tgts > 0) {
2106                 if (lsa->lsa_stripe_count > 0 &&
2107                     lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
2108                     lsa->lsa_stripe_count != LLAPI_LAYOUT_WIDE &&
2109                     lsa->lsa_nr_tgts != lsa->lsa_stripe_count) {
2110                         fprintf(stderr, "stripe_count(%lld) != nr_osts(%d)\n",
2111                                 lsa->lsa_stripe_count, lsa->lsa_nr_tgts);
2112                         return -EINVAL;
2113                 }
2114                 for (i = 0; i < lsa->lsa_nr_tgts; i++) {
2115                         rc = llapi_layout_ost_index_set(layout, i,
2116                                                         lsa->lsa_tgts[i]);
2117                         if (rc)
2118                                 break;
2119                 }
2120         } else if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT) {
2121                 rc = llapi_layout_ost_index_set(layout, 0, lsa->lsa_stripe_off);
2122         }
2123         if (rc) {
2124                 fprintf(stderr, "Set ost index %d failed. %s\n",
2125                         i, strerror(errno));
2126                 return rc;
2127         }
2128
2129         return 0;
2130 }
2131
2132 /* In 'lfs setstripe --component-add' mode, we need to fetch the extent
2133  * end of the last component in the existing file, and adjust the
2134  * first extent start of the components to be added accordingly. */
2135 static int adjust_first_extent(char *fname, struct llapi_layout *layout)
2136 {
2137         struct llapi_layout *head;
2138         uint64_t start, end, stripe_size, prev_end = 0;
2139         int rc;
2140
2141         if (layout == NULL) {
2142                 fprintf(stderr,
2143                         "%s setstripe: layout must be specified\n",
2144                         progname);
2145                 return -EINVAL;
2146         }
2147
2148         errno = 0;
2149         head = llapi_layout_get_by_path(fname, 0);
2150         if (head == NULL) {
2151                 fprintf(stderr,
2152                         "%s setstripe: cannot read layout from '%s': %s\n",
2153                         progname, fname, strerror(errno));
2154                 return -EINVAL;
2155         } else if (errno == ENODATA) {
2156                 /* file without LOVEA, this component-add will be turned
2157                  * into a component-create. */
2158                 llapi_layout_free(head);
2159                 return -ENODATA;
2160         } else if (!llapi_layout_is_composite(head)) {
2161                 fprintf(stderr, "%s setstripe: '%s' not a composite file\n",
2162                         progname, fname);
2163                 llapi_layout_free(head);
2164                 return -EINVAL;
2165         }
2166
2167         rc = llapi_layout_comp_extent_get(head, &start, &prev_end);
2168         if (rc) {
2169                 fprintf(stderr, "%s setstripe: cannot get prev extent: %s\n",
2170                         progname, strerror(errno));
2171                 llapi_layout_free(head);
2172                 return rc;
2173         }
2174
2175         llapi_layout_free(head);
2176
2177         /* Make sure we use the first component of the layout to be added. */
2178         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_FIRST);
2179         if (rc < 0) {
2180                 fprintf(stderr,
2181                         "%s setstripe: cannot move component cursor: %s\n",
2182                         progname, strerror(errno));
2183                 return rc;
2184         }
2185
2186         rc = llapi_layout_comp_extent_get(layout, &start, &end);
2187         if (rc) {
2188                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
2189                         progname, strerror(errno));
2190                 return rc;
2191         }
2192
2193         if (start > prev_end || end <= prev_end) {
2194                 fprintf(stderr,
2195                         "%s setstripe: first extent [%lu, %lu) not adjacent with extent end %lu\n",
2196                         progname, start, end, prev_end);
2197                 return -EINVAL;
2198         }
2199
2200         rc = llapi_layout_stripe_size_get(layout, &stripe_size);
2201         if (rc) {
2202                 fprintf(stderr, "%s setstripe: cannot get stripe size: %s\n",
2203                         progname, strerror(errno));
2204                 return rc;
2205         }
2206
2207         if (stripe_size != LLAPI_LAYOUT_DEFAULT &&
2208             (prev_end & (stripe_size - 1))) {
2209                 fprintf(stderr,
2210                         "%s setstripe: stripe size %lu not aligned with %lu\n",
2211                         progname, stripe_size, prev_end);
2212                 return -EINVAL;
2213         }
2214
2215         rc = llapi_layout_comp_extent_set(layout, prev_end, end);
2216         if (rc) {
2217                 fprintf(stderr,
2218                         "%s setstripe: cannot set component extent [%lu, %lu): %s\n",
2219                         progname, prev_end, end, strerror(errno));
2220                 return rc;
2221         }
2222
2223         return 0;
2224 }
2225
2226 static inline bool arg_is_eof(char *arg)
2227 {
2228         return !strncmp(arg, "-1", strlen("-1")) ||
2229                !strncmp(arg, "EOF", strlen("EOF")) ||
2230                !strncmp(arg, "eof", strlen("eof"));
2231 }
2232
2233 /**
2234  * lfs_mirror_alloc() - Allocate a mirror argument structure.
2235  *
2236  * Return: Valid mirror_args pointer on success and
2237  *         NULL if memory allocation fails.
2238  */
2239 static struct mirror_args *lfs_mirror_alloc(void)
2240 {
2241         struct mirror_args *mirror = NULL;
2242
2243         while (1) {
2244                 mirror = calloc(1, sizeof(*mirror));
2245                 if (mirror != NULL)
2246                         break;
2247
2248                 sleep(1);
2249         }
2250
2251         return mirror;
2252 }
2253
2254 /**
2255  * lfs_mirror_free() - Free memory allocated for a mirror argument
2256  *                     structure.
2257  * @mirror: Previously allocated mirror argument structure by
2258  *          lfs_mirror_alloc().
2259  *
2260  * Free memory allocated for @mirror.
2261  *
2262  * Return: void.
2263  */
2264 static void lfs_mirror_free(struct mirror_args *mirror)
2265 {
2266         if (mirror->m_layout != NULL)
2267                 llapi_layout_free(mirror->m_layout);
2268         free(mirror);
2269 }
2270
2271 /**
2272  * lfs_mirror_list_free() - Free memory allocated for a mirror list.
2273  * @mirror_list: Previously allocated mirror list.
2274  *
2275  * Free memory allocated for @mirror_list.
2276  *
2277  * Return: void.
2278  */
2279 static void lfs_mirror_list_free(struct mirror_args *mirror_list)
2280 {
2281         struct mirror_args *next_mirror = NULL;
2282
2283         while (mirror_list != NULL) {
2284                 next_mirror = mirror_list->m_next;
2285                 lfs_mirror_free(mirror_list);
2286                 mirror_list = next_mirror;
2287         }
2288 }
2289
2290 enum {
2291         LFS_POOL_OPT = 3,
2292         LFS_COMP_COUNT_OPT,
2293         LFS_COMP_START_OPT,
2294         LFS_COMP_FLAGS_OPT,
2295         LFS_COMP_DEL_OPT,
2296         LFS_COMP_SET_OPT,
2297         LFS_COMP_ADD_OPT,
2298         LFS_COMP_USE_PARENT_OPT,
2299         LFS_COMP_NO_VERIFY_OPT,
2300         LFS_PROJID_OPT,
2301         LFS_MIRROR_FLAGS_OPT,
2302         LFS_MIRROR_ID_OPT,
2303         LFS_MIRROR_STATE_OPT,
2304 };
2305
2306 /* functions */
2307 static int lfs_setstripe_internal(int argc, char **argv,
2308                                   enum setstripe_origin opc)
2309 {
2310         struct lfs_setstripe_args        lsa;
2311         struct llapi_stripe_param       *param = NULL;
2312         struct find_param                migrate_mdt_param = {
2313                 .fp_max_depth = -1,
2314                 .fp_mdt_index = -1,
2315         };
2316         char                            *fname;
2317         int                              result;
2318         int                              result2 = 0;
2319         char                            *end;
2320         int                              c;
2321         int                              delete = 0;
2322         char                            *mdt_idx_arg = NULL;
2323         unsigned long long               size_units = 1;
2324         bool                             migrate_mode = false;
2325         bool                             migration_block = false;
2326         __u64                            migration_flags = 0;
2327         __u32                            osts[LOV_MAX_STRIPE_COUNT] = { 0 };
2328         int                              comp_del = 0, comp_set = 0;
2329         int                              comp_add = 0;
2330         __u32                            comp_id = 0;
2331         struct llapi_layout             *layout = NULL;
2332         struct llapi_layout             **lpp = &layout;
2333         bool                             mirror_mode = false;
2334         bool                             has_m_file = false;
2335         __u32                            mirror_count = 0;
2336         enum mirror_flags                mirror_flags = 0;
2337         struct mirror_args              *mirror_list = NULL;
2338         struct mirror_args              *new_mirror = NULL;
2339         struct mirror_args              *last_mirror = NULL;
2340         __u16                            mirror_id = 0;
2341         char                             cmd[PATH_MAX];
2342
2343         struct option long_opts[] = {
2344 /* find { .val = 'A',   .name = "atime",        .has_arg = required_argument }*/
2345         /* --block is only valid in migrate mode */
2346         { .val = 'b',   .name = "block",        .has_arg = no_argument },
2347         { .val = LFS_COMP_ADD_OPT,
2348                         .name = "comp-add",     .has_arg = no_argument },
2349         { .val = LFS_COMP_ADD_OPT,
2350                         .name = "component-add", .has_arg = no_argument },
2351         { .val = LFS_COMP_DEL_OPT,
2352                         .name = "comp-del",     .has_arg = no_argument },
2353         { .val = LFS_COMP_DEL_OPT,
2354                         .name = "component-del", .has_arg = no_argument },
2355         { .val = LFS_COMP_FLAGS_OPT,
2356                         .name = "comp-flags",   .has_arg = required_argument },
2357         { .val = LFS_COMP_FLAGS_OPT,
2358                         .name = "component-flags",
2359                                                 .has_arg = required_argument },
2360         { .val = LFS_COMP_SET_OPT,
2361                         .name = "comp-set",     .has_arg = no_argument },
2362         { .val = LFS_COMP_SET_OPT,
2363                         .name = "component-set",
2364                                                 .has_arg = no_argument},
2365         { .val = LFS_COMP_USE_PARENT_OPT,
2366                         .name = "parent",       .has_arg = no_argument},
2367         { .val = LFS_COMP_NO_VERIFY_OPT,
2368                         .name = "no-verify",    .has_arg = no_argument},
2369         { .val = LFS_MIRROR_FLAGS_OPT,
2370                         .name = "flags",        .has_arg = required_argument},
2371         { .val = LFS_MIRROR_ID_OPT,
2372                         .name = "mirror-id",    .has_arg = required_argument},
2373         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument},
2374         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument},
2375 /* find { .val = 'C',   .name = "ctime",        .has_arg = required_argument }*/
2376         { .val = 'd',   .name = "delete",       .has_arg = no_argument},
2377         { .val = 'd',   .name = "destroy",      .has_arg = no_argument},
2378         /* --non-direct is only valid in migrate mode */
2379         { .val = 'D',   .name = "non-direct",   .has_arg = no_argument },
2380         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument},
2381         { .val = 'E',   .name = "component-end",
2382                                                 .has_arg = required_argument},
2383         { .val = 'f',   .name = "file",         .has_arg = required_argument },
2384 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
2385 /* find { .val = 'g',   .name = "gid",          .has_arg = no_argument }, */
2386 /* find { .val = 'G',   .name = "group",        .has_arg = required_argument }*/
2387 /* dirstripe { .val = 'H', .name = "mdt-hash",  .has_arg = required_argument }*/
2388         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument},
2389         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument},
2390         { .val = 'I',   .name = "comp-id",      .has_arg = required_argument},
2391         { .val = 'I',   .name = "component-id", .has_arg = required_argument},
2392         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
2393         { .val = 'm',   .name = "mdt",          .has_arg = required_argument},
2394         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument},
2395         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument},
2396         /* --non-block is only valid in migrate mode */
2397         { .val = 'n',   .name = "non-block",    .has_arg = no_argument },
2398         { .val = 'N',   .name = "mirror-count", .has_arg = optional_argument},
2399         { .val = 'o',   .name = "ost",          .has_arg = required_argument },
2400 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
2401         { .val = 'o',   .name = "ost-list",     .has_arg = required_argument },
2402         { .val = 'o',   .name = "ost_list",     .has_arg = required_argument },
2403 #endif
2404         { .val = 'p',   .name = "pool",         .has_arg = required_argument },
2405 /* find { .val = 'P',   .name = "print",        .has_arg = no_argument }, */
2406 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
2407 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
2408 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
2409         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
2410         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
2411 /* find { .val = 't',   .name = "type",         .has_arg = required_argument }*/
2412 /* dirstripe { .val = 'T', .name = "mdt-count", .has_arg = required_argument }*/
2413 /* find { .val = 'u',   .name = "uid",          .has_arg = required_argument }*/
2414 /* find { .val = 'U',   .name = "user",         .has_arg = required_argument }*/
2415         /* --verbose is only valid in migrate mode */
2416         { .val = 'v',   .name = "verbose",      .has_arg = no_argument},
2417 /* getstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
2418         { .name = NULL } };
2419
2420         setstripe_args_init(&lsa);
2421
2422         migrate_mode = (opc == SO_MIGRATE);
2423         mirror_mode = (opc == SO_MIRROR_CREATE || opc == SO_MIRROR_EXTEND);
2424
2425         snprintf(cmd, sizeof(cmd), "%s %s", progname, argv[0]);
2426         progname = cmd;
2427         while ((c = getopt_long(argc, argv, "bc:dDE:f:i:I:m:N::no:p:L:s:S:v",
2428                                 long_opts, NULL)) >= 0) {
2429                 switch (c) {
2430                 case 0:
2431                         /* Long options. */
2432                         break;
2433                 case LFS_COMP_ADD_OPT:
2434                         comp_add = 1;
2435                         break;
2436                 case LFS_COMP_DEL_OPT:
2437                         comp_del = 1;
2438                         break;
2439                 case LFS_COMP_FLAGS_OPT:
2440                         result = comp_str2flags(optarg, &lsa.lsa_comp_flags,
2441                                                 &lsa.lsa_comp_neg_flags);
2442                         if (result != 0)
2443                                 goto usage_error;
2444                         if (mirror_mode && lsa.lsa_comp_neg_flags) {
2445                                 fprintf(stderr, "%s: inverted flags are not supported\n",
2446                                         progname);
2447                                 goto usage_error;
2448                         }
2449                         if (lsa.lsa_comp_neg_flags & LCME_FL_STALE) {
2450                                 fprintf(stderr,
2451                                         "%s: cannot clear 'stale' flags from component. Please use lfs-mirror-resync(1) instead\n",
2452                                         progname);
2453                                 result = -EINVAL;
2454                                 goto error;
2455                         }
2456
2457                         break;
2458                 case LFS_COMP_SET_OPT:
2459                         comp_set = 1;
2460                         break;
2461                 case LFS_COMP_USE_PARENT_OPT:
2462                         if (!mirror_mode) {
2463                                 fprintf(stderr, "error: %s: --parent must be "
2464                                         "specified with --mirror-count|-N "
2465                                         "option\n", progname);
2466                                 goto usage_error;
2467                         }
2468                         setstripe_args_init(&lsa);
2469                         break;
2470                 case LFS_COMP_NO_VERIFY_OPT:
2471                         mirror_flags |= MF_NO_VERIFY;
2472                         break;
2473                 case LFS_MIRROR_ID_OPT:
2474                         mirror_id = strtoul(optarg, &end, 0);
2475                         if (*end != '\0' || mirror_id == 0) {
2476                                 fprintf(stderr,
2477                                         "%s %s: invalid mirror ID '%s'\n",
2478                                         progname, argv[0], optarg);
2479                                 goto usage_error;
2480                         }
2481                         break;
2482                 case LFS_MIRROR_FLAGS_OPT: {
2483                         __u32 flags;
2484
2485                         if (!mirror_mode || !last_mirror) {
2486                                 fprintf(stderr, "error: %s: --flags must be specified with --mirror-count|-N option\n",
2487                                         progname);
2488                                 goto usage_error;
2489                         }
2490
2491                         result = comp_str2flags(optarg, &last_mirror->m_flags,
2492                                                 &flags);
2493                         if (result != 0)
2494                                 goto usage_error;
2495
2496                         if (flags) {
2497                                 fprintf(stderr, "%s: inverted flags are not supported\n",
2498                                         progname);
2499                                 result = -EINVAL;
2500                                 goto usage_error;
2501                         }
2502                         if (last_mirror->m_flags & ~LCME_USER_FLAGS) {
2503                                 fprintf(stderr,
2504                                         "%s: unsupported mirror flags: %s\n",
2505                                         progname, optarg);
2506                                 result = -EINVAL;
2507                                 goto error;
2508                         }
2509                         break;
2510                 }
2511                 case 'b':
2512                         if (!migrate_mode) {
2513                                 fprintf(stderr,
2514                                         "%s %s: -b|--block valid only for migrate command\n",
2515                                         progname, argv[0]);
2516                                 goto usage_error;
2517                         }
2518                         migration_block = true;
2519                         break;
2520                 case 'c':
2521                         lsa.lsa_stripe_count = strtoul(optarg, &end, 0);
2522                         if (*end != '\0') {
2523                                 fprintf(stderr,
2524                                         "%s %s: invalid stripe count '%s'\n",
2525                                         progname, argv[0], optarg);
2526                                 goto usage_error;
2527                         }
2528
2529                         if (lsa.lsa_stripe_count == -1)
2530                                 lsa.lsa_stripe_count = LLAPI_LAYOUT_WIDE;
2531                         break;
2532                 case 'd':
2533                         /* delete the default striping pattern */
2534                         delete = 1;
2535                         if (opc == SO_MIRROR_SPLIT) {
2536                                 if (has_m_file) {
2537                                         fprintf(stderr,
2538                                               "%s %s: -d cannot used with -f\n",
2539                                                 progname, argv[0]);
2540                                         goto usage_error;
2541                                 }
2542                                 mirror_flags |= MF_DESTROY;
2543                         }
2544                         break;
2545                 case 'D':
2546                         if (!migrate_mode) {
2547                                 fprintf(stderr,
2548                                         "%s %s: -D|--non-direct is valid "
2549                                         "only for migrate command\n",
2550                                         progname, argv[0]);
2551                                 goto usage_error;
2552                         }
2553                         migration_flags |= MIGRATION_NONDIRECT;
2554                         break;
2555                 case 'E':
2556                         if (lsa.lsa_comp_end != 0) {
2557                                 result = comp_args_to_layout(lpp, &lsa);
2558                                 if (result) {
2559                                         fprintf(stderr,
2560                                                 "%s %s: invalid layout\n",
2561                                                 progname, argv[0]);
2562                                         goto usage_error;
2563                                 }
2564
2565                                 setstripe_args_init_inherit(&lsa);
2566                         }
2567
2568                         if (arg_is_eof(optarg)) {
2569                                 lsa.lsa_comp_end = LUSTRE_EOF;
2570                         } else {
2571                                 result = llapi_parse_size(optarg,
2572                                                         &lsa.lsa_comp_end,
2573                                                         &size_units, 0);
2574                                 if (result) {
2575                                         fprintf(stderr,
2576                                                 "%s %s: invalid component end '%s'\n",
2577                                                 progname, argv[0], optarg);
2578                                         goto usage_error;
2579                                 }
2580                         }
2581                         break;
2582                 case 'i':
2583                         lsa.lsa_stripe_off = strtol(optarg, &end, 0);
2584                         if (*end != '\0') {
2585                                 fprintf(stderr,
2586                                         "%s %s: invalid stripe offset '%s'\n",
2587                                         progname, argv[0], optarg);
2588                                 goto usage_error;
2589                         }
2590                         if (lsa.lsa_stripe_off == -1)
2591                                 lsa.lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2592                         break;
2593                 case 'I':
2594                         comp_id = strtoul(optarg, &end, 0);
2595                         if (*end != '\0' || comp_id == 0 ||
2596                             comp_id > LCME_ID_MAX) {
2597                                 fprintf(stderr,
2598                                         "%s %s: invalid component ID '%s'\n",
2599                                         progname, argv[0], optarg);
2600                                 goto usage_error;
2601                         }
2602                         break;
2603                 case 'f':
2604                         if (opc != SO_MIRROR_EXTEND && opc != SO_MIRROR_SPLIT) {
2605                                 fprintf(stderr,
2606                                         "error: %s: invalid option: %s\n",
2607                                         progname, argv[optopt + 1]);
2608                                 goto usage_error;
2609                         }
2610                         if (opc == SO_MIRROR_EXTEND) {
2611                                 if (last_mirror == NULL) {
2612                                         fprintf(stderr,
2613                                 "error: %s: '-N' must exist in front of '%s'\n",
2614                                                 progname, argv[optopt + 1]);
2615                                         goto usage_error;
2616                                 }
2617                                 last_mirror->m_file = optarg;
2618                                 last_mirror->m_count = 1;
2619                         } else {
2620                                 /* mirror split */
2621                                 if (mirror_list == NULL)
2622                                         mirror_list = lfs_mirror_alloc();
2623                                 mirror_list->m_file = optarg;
2624                         }
2625                         has_m_file = true;
2626                         break;
2627                 case 'L':
2628                         if (strcmp(argv[optind - 1], "mdt") == 0) {
2629                                 /* Can be only the first component */
2630                                 if (layout != NULL) {
2631                                         result = -EINVAL;
2632                                         fprintf(stderr, "error: 'mdt' layout "
2633                                                 "can be only the first one\n");
2634                                         goto error;
2635                                 }
2636                                 if (lsa.lsa_comp_end > (1ULL << 30)) { /* 1Gb */
2637                                         result = -EFBIG;
2638                                         fprintf(stderr, "error: 'mdt' layout "
2639                                                 "size is too big\n");
2640                                         goto error;
2641                                 }
2642                                 lsa.lsa_pattern = LLAPI_LAYOUT_MDT;
2643                         } else if (strcmp(argv[optind - 1], "raid0") != 0) {
2644                                 result = -EINVAL;
2645                                 fprintf(stderr, "error: layout '%s' is "
2646                                         "unknown, supported layouts are: "
2647                                         "'mdt', 'raid0'\n", argv[optind]);
2648                                 goto error;
2649                         }
2650                         break;
2651                 case 'm':
2652                         if (!migrate_mode) {
2653                                 fprintf(stderr,
2654                                         "%s %s: -m|--mdt-index valid only for migrate command\n",
2655                                         progname, argv[0]);
2656                                 goto usage_error;
2657                         }
2658                         mdt_idx_arg = optarg;
2659                         break;
2660                 case 'n':
2661                         if (!migrate_mode) {
2662                                 fprintf(stderr,
2663                                         "%s %s: -n|--non-block valid only for migrate command\n",
2664                                         progname, argv[0]);
2665                                 goto usage_error;
2666                         }
2667                         migration_flags |= MIGRATION_NONBLOCK;
2668                         break;
2669                 case 'N':
2670                         if (opc == SO_SETSTRIPE) {
2671                                 opc = SO_MIRROR_CREATE;
2672                                 mirror_mode = true;
2673                         }
2674                         mirror_count = 1;
2675                         if (optarg != NULL) {
2676                                 mirror_count = strtoul(optarg, &end, 0);
2677                                 if (*end != '\0' || mirror_count == 0) {
2678                                         fprintf(stderr,
2679                                                 "error: %s: bad mirror count: %s\n",
2680                                                 progname, optarg);
2681                                         result = -EINVAL;
2682                                         goto error;
2683                                 }
2684                         }
2685
2686                         new_mirror = lfs_mirror_alloc();
2687                         new_mirror->m_count = mirror_count;
2688
2689                         if (mirror_list == NULL)
2690                                 mirror_list = new_mirror;
2691
2692                         if (last_mirror != NULL) {
2693                                 /* wrap up last mirror */
2694                                 if (lsa.lsa_comp_end == 0)
2695                                         lsa.lsa_comp_end = LUSTRE_EOF;
2696
2697                                 result = comp_args_to_layout(lpp, &lsa);
2698                                 if (result) {
2699                                         lfs_mirror_free(new_mirror);
2700                                         goto error;
2701                                 }
2702
2703                                 setstripe_args_init_inherit(&lsa);
2704
2705                                 last_mirror->m_next = new_mirror;
2706                         }
2707
2708                         last_mirror = new_mirror;
2709                         lpp = &last_mirror->m_layout;
2710                         break;
2711                 case 'o':
2712 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
2713                         if (strcmp(argv[optind - 1], "--ost-list") == 0)
2714                                 fprintf(stderr, "warning: '--ost-list' is "
2715                                         "deprecated, use '--ost' instead\n");
2716 #endif
2717                         lsa.lsa_nr_tgts = parse_targets(osts,
2718                                                 sizeof(osts) / sizeof(__u32),
2719                                                 lsa.lsa_nr_tgts, optarg);
2720                         if (lsa.lsa_nr_tgts < 0) {
2721                                 fprintf(stderr,
2722                                         "%s %s: invalid OST target(s) '%s'\n",
2723                                         progname, argv[0], optarg);
2724                                 goto usage_error;
2725                         }
2726
2727                         lsa.lsa_tgts = osts;
2728                         if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
2729                                 lsa.lsa_stripe_off = osts[0];
2730                         break;
2731                 case 'p':
2732                         if (optarg == NULL)
2733                                 goto usage_error;
2734                         lsa.lsa_pool_name = optarg;
2735                         break;
2736                 case 'S':
2737                         result = llapi_parse_size(optarg, &lsa.lsa_stripe_size,
2738                                                   &size_units, 0);
2739                         if (result) {
2740                                 fprintf(stderr,
2741                                         "%s %s: invalid stripe size '%s'\n",
2742                                         progname, argv[0], optarg);
2743                                 goto usage_error;
2744                         }
2745                         break;
2746                 case 'v':
2747                         if (!migrate_mode) {
2748                                 fprintf(stderr,
2749                                         "%s %s: -v|--verbose valid only for migrate command\n",
2750                                         progname, argv[0]);
2751                                 goto usage_error;
2752                         }
2753                         migrate_mdt_param.fp_verbose = VERBOSE_DETAIL;
2754                         break;
2755                 default:
2756                         fprintf(stderr, "%s %s: unrecognized option '%s'\n",
2757                                 progname, argv[0], argv[optind - 1]);
2758                         goto usage_error;
2759                 }
2760         }
2761
2762         fname = argv[optind];
2763
2764         if (optind == argc) {
2765                 fprintf(stderr, "%s %s: FILE must be specified\n",
2766                         progname, argv[0]);
2767                 goto usage_error;
2768         }
2769
2770         if (mirror_mode && mirror_count == 0) {
2771                 fprintf(stderr,
2772                         "error: %s: --mirror-count|-N option is required\n",
2773                         progname);
2774                 result = -EINVAL;
2775                 goto error;
2776         }
2777
2778         if (mirror_mode) {
2779                 if (lsa.lsa_comp_end == 0)
2780                         lsa.lsa_comp_end = LUSTRE_EOF;
2781         }
2782
2783         if (lsa.lsa_comp_end != 0) {
2784                 result = comp_args_to_layout(lpp, &lsa);
2785                 if (result)
2786                         goto error;
2787         }
2788
2789         if (mirror_flags & MF_NO_VERIFY) {
2790                 if (opc != SO_MIRROR_EXTEND) {
2791                         fprintf(stderr,
2792                                 "error: %s: --no-verify is valid only for lfs mirror extend command\n",
2793                                 progname);
2794                         result = -EINVAL;
2795                         goto error;
2796                 } else if (!has_m_file) {
2797                         fprintf(stderr,
2798                                 "error: %s: --no-verify must be specified with -f <victim_file> option\n",
2799                                 progname);
2800                         result = -EINVAL;
2801                         goto error;
2802                 }
2803         }
2804
2805         /* Only LCME_FL_INIT flags is used in PFL, and it shouldn't be
2806          * altered by user space tool, so we don't need to support the
2807          * --component-set for this moment. */
2808         if (comp_set && !comp_id) {
2809                 fprintf(stderr, "%s %s: --component-set doesn't have component-id set\n",
2810                         progname, argv[0]);
2811                 goto usage_error;
2812         }
2813
2814         if ((delete + comp_set + comp_del + comp_add) > 1) {
2815                 fprintf(stderr,
2816                         "%s %s: options --component-set, --component-del, --component-add and -d are mutually exclusive\n",
2817                         progname, argv[0]);
2818                 goto usage_error;
2819         }
2820
2821         if (delete && (setstripe_args_specified(&lsa) || comp_id != 0 ||
2822                        lsa.lsa_comp_flags != 0 || layout != NULL)) {
2823                 fprintf(stderr,
2824                         "%s %s: option -d is mutually exclusive with -s, -c, -o, -p, -I, -F and -E options\n",
2825                         progname, argv[0]);
2826                 goto usage_error;
2827         }
2828
2829         if ((comp_set || comp_del) &&
2830             (setstripe_args_specified(&lsa) || layout != NULL)) {
2831                 fprintf(stderr,
2832                         "%s %s: options --component-del and --component-set are mutually exclusive when used with -c, -E, -o, -p, or -s\n",
2833                         progname, argv[0]);
2834                 goto usage_error;
2835         }
2836
2837         if (comp_del && comp_id != 0 && lsa.lsa_comp_flags != 0) {
2838                 fprintf(stderr,
2839                         "%s %s: options -I and -F are mutually exclusive when used with --component-del\n",
2840                         progname, argv[0]);
2841                 goto usage_error;
2842         }
2843
2844         if (comp_add || comp_del) {
2845                 struct stat st;
2846
2847                 result = lstat(fname, &st);
2848                 if (result == 0 && S_ISDIR(st.st_mode)) {
2849                         fprintf(stderr,
2850                                 "%s setstripe: cannot use --component-add or --component-del for directory\n",
2851                                 progname);
2852                         goto usage_error;
2853                 }
2854
2855                 if (mirror_mode) {
2856                         fprintf(stderr, "error: %s: can't use --component-add "
2857                                 "or --component-del for mirror operation\n",
2858                                 progname);
2859                         goto usage_error;
2860                 }
2861         }
2862
2863         if (comp_add) {
2864                 if (layout == NULL) {
2865                         fprintf(stderr,
2866                                 "%s %s: option -E must be specified with --component-add\n",
2867                                 progname, argv[0]);
2868                         goto usage_error;
2869                 }
2870
2871                 result = adjust_first_extent(fname, layout);
2872                 if (result == -ENODATA)
2873                         comp_add = 0;
2874                 else if (result != 0)
2875                         goto error;
2876         }
2877
2878         if (mdt_idx_arg != NULL && optind > 3) {
2879                 fprintf(stderr,
2880                         "%s %s: option -m cannot be used with other options\n",
2881                         progname, argv[0]);
2882                 goto usage_error;
2883         }
2884
2885         if ((migration_flags & MIGRATION_NONBLOCK) && migration_block) {
2886                 fprintf(stderr,
2887                         "%s %s: options --non-block and --block are mutually exclusive\n",
2888                         progname, argv[0]);
2889                 goto usage_error;
2890         }
2891
2892         if (!comp_del && !comp_set && comp_id != 0) {
2893                 fprintf(stderr,
2894                         "%s %s: option -I can only be used with --component-del\n",
2895                         progname, argv[0]);
2896                 goto usage_error;
2897         }
2898
2899         if (mdt_idx_arg != NULL) {
2900                 /* initialize migrate mdt parameters */
2901                 migrate_mdt_param.fp_mdt_index = strtoul(mdt_idx_arg, &end, 0);
2902                 if (*end != '\0') {
2903                         fprintf(stderr, "%s %s: invalid MDT index '%s'\n",
2904                                 progname, argv[0], mdt_idx_arg);
2905                         goto usage_error;
2906                 }
2907                 migrate_mdt_param.fp_migrate = 1;
2908         } else if (layout == NULL) {
2909                 /* initialize stripe parameters */
2910                 param = calloc(1, offsetof(typeof(*param),
2911                                lsp_osts[lsa.lsa_nr_tgts]));
2912                 if (param == NULL) {
2913                         fprintf(stderr,
2914                                 "%s %s: cannot allocate memory for parameters: %s\n",
2915                                 progname, argv[0], strerror(ENOMEM));
2916                         result = -ENOMEM;
2917                         goto error;
2918                 }
2919
2920                 if (lsa.lsa_stripe_size != LLAPI_LAYOUT_DEFAULT)
2921                         param->lsp_stripe_size = lsa.lsa_stripe_size;
2922                 if (lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
2923                         if (lsa.lsa_stripe_count == LLAPI_LAYOUT_WIDE)
2924                                 param->lsp_stripe_count = -1;
2925                         else
2926                                 param->lsp_stripe_count = lsa.lsa_stripe_count;
2927                 }
2928                 if (lsa.lsa_stripe_off == LLAPI_LAYOUT_DEFAULT)
2929                         param->lsp_stripe_offset = -1;
2930                 else
2931                         param->lsp_stripe_offset = lsa.lsa_stripe_off;
2932                 param->lsp_pool = lsa.lsa_pool_name;
2933                 param->lsp_is_specific = false;
2934                 if (lsa.lsa_nr_tgts > 0) {
2935                         if (lsa.lsa_stripe_count > 0 &&
2936                             lsa.lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
2937                             lsa.lsa_stripe_count != LLAPI_LAYOUT_WIDE &&
2938                             lsa.lsa_nr_tgts != lsa.lsa_stripe_count) {
2939                                 fprintf(stderr, "error: %s: stripe count %lld "
2940                                         "doesn't match the number of OSTs: %d\n"
2941                                         , argv[0], lsa.lsa_stripe_count,
2942                                         lsa.lsa_nr_tgts);
2943                                 free(param);
2944                                 goto usage_error;
2945                         }
2946
2947                         param->lsp_is_specific = true;
2948                         param->lsp_stripe_count = lsa.lsa_nr_tgts;
2949                         memcpy(param->lsp_osts, osts,
2950                                sizeof(*osts) * lsa.lsa_nr_tgts);
2951                 }
2952         }
2953
2954         for (fname = argv[optind]; fname != NULL; fname = argv[++optind]) {
2955                 if (mdt_idx_arg != NULL) {
2956                         result = llapi_migrate_mdt(fname, &migrate_mdt_param);
2957                 } else if (migrate_mode) {
2958                         result = lfs_migrate(fname, migration_flags, param,
2959                                              layout);
2960                 } else if (comp_set != 0) {
2961                         result = lfs_component_set(fname, comp_id,
2962                                                    lsa.lsa_comp_flags,
2963                                                    lsa.lsa_comp_neg_flags);
2964                 } else if (comp_del != 0) {
2965                         result = lfs_component_del(fname, comp_id,
2966                                                    lsa.lsa_comp_flags,
2967                                                    lsa.lsa_comp_neg_flags);
2968                 } else if (comp_add != 0) {
2969                         result = lfs_component_add(fname, layout);
2970                 } else if (opc == SO_MIRROR_CREATE) {
2971                         result = mirror_create(fname, mirror_list);
2972                 } else if (opc == SO_MIRROR_EXTEND) {
2973                         result = mirror_extend(fname, mirror_list,
2974                                                mirror_flags);
2975                 } else if (opc == SO_MIRROR_SPLIT) {
2976                         if (mirror_id == 0) {
2977                                 fprintf(stderr,
2978                                         "%s %s: no mirror id is specified\n",
2979                                         progname, argv[0]);
2980                                 goto usage_error;
2981                         }
2982                         result = mirror_split(fname, mirror_id, mirror_flags,
2983                                               has_m_file ? mirror_list->m_file :
2984                                               NULL);
2985                 } else if (layout != NULL) {
2986                         result = lfs_component_create(fname, O_CREAT | O_WRONLY,
2987                                                       0644, layout);
2988                         if (result >= 0) {
2989                                 close(result);
2990                                 result = 0;
2991                         }
2992                 } else {
2993                         result = llapi_file_open_param(fname,
2994                                                        O_CREAT | O_WRONLY,
2995                                                        0644, param);
2996                         if (result >= 0) {
2997                                 close(result);
2998                                 result = 0;
2999                         }
3000                 }
3001                 if (result) {
3002                         /* Save the first error encountered. */
3003                         if (result2 == 0)
3004                                 result2 = result;
3005                         continue;
3006                 }
3007         }
3008
3009         free(param);
3010         llapi_layout_free(layout);
3011         lfs_mirror_list_free(mirror_list);
3012         return result2;
3013 usage_error:
3014         result = CMD_HELP;
3015 error:
3016         llapi_layout_free(layout);
3017         lfs_mirror_list_free(mirror_list);
3018         return result;
3019 }
3020
3021 static int lfs_poollist(int argc, char **argv)
3022 {
3023         if (argc != 2)
3024                 return CMD_HELP;
3025
3026         return llapi_poollist(argv[1]);
3027 }
3028
3029 static int set_time(time_t *time, time_t *set, char *str)
3030 {
3031         time_t t;
3032         int res = 0;
3033
3034         if (str[0] == '+')
3035                 res = 1;
3036         else if (str[0] == '-')
3037                 res = -1;
3038
3039         if (res)
3040                 str++;
3041
3042         t = strtol(str, NULL, 0);
3043         if (*time < t * 24 * 60 * 60) {
3044                 if (res)
3045                         str--;
3046                 fprintf(stderr, "Wrong time '%s' is specified.\n", str);
3047                 return INT_MAX;
3048         }
3049
3050         *set = *time - t * 24 * 60 * 60;
3051         return res;
3052 }
3053 static int name2uid(unsigned int *id, const char *name)
3054 {
3055         struct passwd *passwd;
3056
3057         passwd = getpwnam(name);
3058         if (passwd == NULL)
3059                 return -ENOENT;
3060         *id = passwd->pw_uid;
3061
3062         return 0;
3063 }
3064
3065 static int name2gid(unsigned int *id, const char *name)
3066 {
3067         struct group *group;
3068
3069         group = getgrnam(name);
3070         if (group == NULL)
3071                 return -ENOENT;
3072         *id = group->gr_gid;
3073
3074         return 0;
3075 }
3076
3077 static inline int name2projid(unsigned int *id, const char *name)
3078 {
3079         return -ENOTSUP;
3080 }
3081
3082 static int uid2name(char **name, unsigned int id)
3083 {
3084         struct passwd *passwd;
3085
3086         passwd = getpwuid(id);
3087         if (passwd == NULL)
3088                 return -ENOENT;
3089         *name = passwd->pw_name;
3090
3091         return 0;
3092 }
3093
3094 static inline int gid2name(char **name, unsigned int id)
3095 {
3096         struct group *group;
3097
3098         group = getgrgid(id);
3099         if (group == NULL)
3100                 return -ENOENT;
3101         *name = group->gr_name;
3102
3103         return 0;
3104 }
3105
3106 static int name2layout(__u32 *layout, char *name)
3107 {
3108         char *ptr, *layout_name;
3109
3110         *layout = 0;
3111         for (ptr = name; ; ptr = NULL) {
3112                 layout_name = strtok(ptr, ",");
3113                 if (layout_name == NULL)
3114                         break;
3115                 if (strcmp(layout_name, "released") == 0)
3116                         *layout |= LOV_PATTERN_F_RELEASED;
3117                 else if (strcmp(layout_name, "raid0") == 0)
3118                         *layout |= LOV_PATTERN_RAID0;
3119                 else if (strcmp(layout_name, "mdt") == 0)
3120                         *layout |= LOV_PATTERN_MDT;
3121                 else
3122                         return -1;
3123         }
3124         return 0;
3125 }
3126
3127 static int lfs_find(int argc, char **argv)
3128 {
3129         int c, rc;
3130         int ret = 0;
3131         time_t t;
3132         struct find_param param = {
3133                 .fp_max_depth = -1,
3134                 .fp_quiet = 1,
3135         };
3136         struct option long_opts[] = {
3137         { .val = 'A',   .name = "atime",        .has_arg = required_argument },
3138         { .val = LFS_COMP_COUNT_OPT,
3139                         .name = "comp-count",   .has_arg = required_argument },
3140         { .val = LFS_COMP_COUNT_OPT,
3141                         .name = "component-count",
3142                                                 .has_arg = required_argument },
3143         { .val = LFS_COMP_FLAGS_OPT,
3144                         .name = "comp-flags",   .has_arg = required_argument },
3145         { .val = LFS_COMP_FLAGS_OPT,
3146                         .name = "component-flags",
3147                                                 .has_arg = required_argument },
3148         { .val = LFS_COMP_START_OPT,
3149                         .name = "comp-start",   .has_arg = required_argument },
3150         { .val = LFS_COMP_START_OPT,
3151                         .name = "component-start",
3152                                                 .has_arg = required_argument },
3153         { .val = LFS_MIRROR_STATE_OPT,
3154                         .name = "mirror-state", .has_arg = required_argument },
3155         { .val = 'c',   .name = "stripe-count", .has_arg = required_argument },
3156         { .val = 'c',   .name = "stripe_count", .has_arg = required_argument },
3157         { .val = 'C',   .name = "ctime",        .has_arg = required_argument },
3158 /* getstripe { .val = 'd', .name = "directory", .has_arg = no_argument }, */
3159         { .val = 'D',   .name = "maxdepth",     .has_arg = required_argument },
3160         { .val = 'E',   .name = "comp-end",     .has_arg = required_argument },
3161         { .val = 'E',   .name = "component-end",
3162                                                 .has_arg = required_argument },
3163 /* find { .val = 'F',   .name = "fid",          .has_arg = no_argument }, */
3164         { .val = 'g',   .name = "gid",          .has_arg = required_argument },
3165         { .val = 'G',   .name = "group",        .has_arg = required_argument },
3166         { .val = 'H',   .name = "mdt-hash",     .has_arg = required_argument },
3167         { .val = 'i',   .name = "stripe-index", .has_arg = required_argument },
3168         { .val = 'i',   .name = "stripe_index", .has_arg = required_argument },
3169 /* getstripe { .val = 'I', .name = "comp-id",   .has_arg = required_argument }*/
3170         { .val = 'L',   .name = "layout",       .has_arg = required_argument },
3171         { .val = 'm',   .name = "mdt",          .has_arg = required_argument },
3172         { .val = 'm',   .name = "mdt-index",    .has_arg = required_argument },
3173         { .val = 'm',   .name = "mdt_index",    .has_arg = required_argument },
3174         { .val = 'M',   .name = "mtime",        .has_arg = required_argument },
3175         { .val = 'n',   .name = "name",         .has_arg = required_argument },
3176         { .val = 'N',   .name = "mirror-count", .has_arg = required_argument },
3177 /* find { .val = 'o'    .name = "or", .has_arg = no_argument }, like find(1) */
3178         { .val = 'O',   .name = "obd",          .has_arg = required_argument },
3179         { .val = 'O',   .name = "ost",          .has_arg = required_argument },
3180         /* no short option for pool yet, can be 'p' after 2.18 */
3181         { .val = LFS_POOL_OPT,
3182                         .name = "pool",         .has_arg = required_argument },
3183         { .val = '0',   .name = "print0",       .has_arg = no_argument },
3184         { .val = 'P',   .name = "print",        .has_arg = no_argument },
3185         { .val = LFS_PROJID_OPT,
3186                         .name = "projid",       .has_arg = required_argument },
3187 /* getstripe { .val = 'q', .name = "quiet",     .has_arg = no_argument }, */
3188 /* getstripe { .val = 'r', .name = "recursive", .has_arg = no_argument }, */
3189 /* getstripe { .val = 'R', .name = "raw",       .has_arg = no_argument }, */
3190         { .val = 's',   .name = "size",         .has_arg = required_argument },
3191         { .val = 'S',   .name = "stripe-size",  .has_arg = required_argument },
3192         { .val = 'S',   .name = "stripe_size",  .has_arg = required_argument },
3193         { .val = 't',   .name = "type",         .has_arg = required_argument },
3194         { .val = 'T',   .name = "mdt-count",    .has_arg = required_argument },
3195         { .val = 'u',   .name = "uid",          .has_arg = required_argument },
3196         { .val = 'U',   .name = "user",         .has_arg = required_argument },
3197 /* getstripe { .val = 'v', .name = "verbose",   .has_arg = no_argument }, */
3198 /* getstripe { .val = 'y', .name = "yaml",      .has_arg = no_argument }, */
3199         { .name = NULL } };
3200         int pathstart = -1;
3201         int pathend = -1;
3202         int neg_opt = 0;
3203         time_t *xtime;
3204         int *xsign;
3205         int isoption;
3206         char *endptr;
3207
3208         time(&t);
3209
3210         /* when getopt_long_only() hits '!' it returns 1, puts "!" in optarg */
3211         while ((c = getopt_long_only(argc, argv,
3212                         "-0A:c:C:D:E:g:G:H:i:L:m:M:n:N:O:Ppqrs:S:t:T:u:U:v",
3213                         long_opts, NULL)) >= 0) {
3214                 xtime = NULL;
3215                 xsign = NULL;
3216                 if (neg_opt)
3217                         --neg_opt;
3218                 /* '!' is part of option */
3219                 /* when getopt_long_only() finds a string which is not
3220                  * an option nor a known option argument it returns 1
3221                  * in that case if we already have found pathstart and pathend
3222                  * (i.e. we have the list of pathnames),
3223                  * the only supported value is "!"
3224                  */
3225                 isoption = (c != 1) || (strcmp(optarg, "!") == 0);
3226                 if (!isoption && pathend != -1) {
3227                         fprintf(stderr, "err: %s: filename|dirname must either "
3228                                         "precede options or follow options\n",
3229                                         argv[0]);
3230                         ret = CMD_HELP;
3231                         goto err;
3232                 }
3233                 if (!isoption && pathstart == -1)
3234                         pathstart = optind - 1;
3235                 if (isoption && pathstart != -1 && pathend == -1)
3236                         pathend = optind - 2;
3237                 switch (c) {
3238                 case 0:
3239                         /* Long options. */
3240                         break;
3241                 case 1:
3242                         /* unknown; opt is "!" or path component,
3243                          * checking done above.
3244                          */
3245                         if (strcmp(optarg, "!") == 0)
3246                                 neg_opt = 2;
3247                         break;
3248                 case 'A':
3249                         xtime = &param.fp_atime;
3250                         xsign = &param.fp_asign;
3251                         param.fp_exclude_atime = !!neg_opt;
3252                         /* no break, this falls through to 'C' for ctime */
3253                 case 'C':
3254                         if (c == 'C') {
3255                                 xtime = &param.fp_ctime;
3256                                 xsign = &param.fp_csign;
3257                                 param.fp_exclude_ctime = !!neg_opt;
3258                         }
3259                         /* no break, this falls through to 'M' for mtime */
3260                 case 'M':
3261                         if (c == 'M') {
3262                                 xtime = &param.fp_mtime;
3263                                 xsign = &param.fp_msign;
3264                                 param.fp_exclude_mtime = !!neg_opt;
3265                         }
3266                         rc = set_time(&t, xtime, optarg);
3267                         if (rc == INT_MAX) {
3268                                 ret = -1;
3269                                 goto err;
3270                         }
3271                         if (rc)
3272                                 *xsign = rc;
3273                         break;
3274                 case LFS_COMP_COUNT_OPT:
3275                         if (optarg[0] == '+') {
3276                                 param.fp_comp_count_sign = -1;
3277                                 optarg++;
3278                         } else if (optarg[0] == '-') {
3279                                 param.fp_comp_count_sign =  1;
3280                                 optarg++;
3281                         }
3282
3283                         param.fp_comp_count = strtoul(optarg, &endptr, 0);
3284                         if (*endptr != '\0') {
3285                                 fprintf(stderr, "error: bad component count "
3286                                         "'%s'\n", optarg);
3287                                 goto err;
3288                         }
3289                         param.fp_check_comp_count = 1;
3290                         param.fp_exclude_comp_count = !!neg_opt;
3291                         break;
3292                 case LFS_COMP_FLAGS_OPT:
3293                         rc = comp_str2flags(optarg, &param.fp_comp_flags,
3294                                             &param.fp_comp_neg_flags);
3295                         if (rc) {
3296                                 fprintf(stderr, "error: bad component flags "
3297                                         "'%s'\n", optarg);
3298                                 goto err;
3299                         }
3300                         param.fp_check_comp_flags = 1;
3301                         if (neg_opt) {
3302                                 __u32 flags = param.fp_comp_neg_flags;
3303                                 param.fp_comp_neg_flags = param.fp_comp_flags;
3304                                 param.fp_comp_flags = flags;
3305                         }
3306                         break;
3307                 case LFS_COMP_START_OPT:
3308                         if (optarg[0] == '+') {
3309                                 param.fp_comp_start_sign = -1;
3310                                 optarg++;
3311                         } else if (optarg[0] == '-') {
3312                                 param.fp_comp_start_sign =  1;
3313                                 optarg++;
3314                         }
3315
3316                         rc = llapi_parse_size(optarg, &param.fp_comp_start,
3317                                               &param.fp_comp_start_units, 0);
3318                         if (rc) {
3319                                 fprintf(stderr, "error: bad component start "
3320                                         "'%s'\n", optarg);
3321                                 goto err;
3322                         }
3323                         param.fp_check_comp_start = 1;
3324                         param.fp_exclude_comp_start = !!neg_opt;
3325                         break;
3326                 case LFS_MIRROR_STATE_OPT:
3327                         rc = mirror_str2state(optarg, &param.fp_mirror_state,
3328                                               &param.fp_mirror_neg_state);
3329                         if (rc) {
3330                                 fprintf(stderr,
3331                                         "error: bad mirrored file state '%s'\n",
3332                                         optarg);
3333                                 goto err;
3334                         }
3335                         param.fp_check_mirror_state = 1;
3336                         if (neg_opt) {
3337                                 __u16 state = param.fp_mirror_neg_state;
3338                                 param.fp_mirror_neg_state =
3339                                         param.fp_mirror_state;
3340                                 param.fp_mirror_state = state;
3341                         }
3342                         break;
3343                 case 'c':
3344                         if (optarg[0] == '+') {
3345                                 param.fp_stripe_count_sign = -1;
3346                                 optarg++;
3347                         } else if (optarg[0] == '-') {
3348                                 param.fp_stripe_count_sign =  1;
3349                                 optarg++;
3350                         }
3351
3352                         param.fp_stripe_count = strtoul(optarg, &endptr, 0);
3353                         if (*endptr != '\0') {
3354                                 fprintf(stderr,"error: bad stripe_count '%s'\n",
3355                                         optarg);
3356                                 ret = -1;
3357                                 goto err;
3358                         }
3359                         param.fp_check_stripe_count = 1;
3360                         param.fp_exclude_stripe_count = !!neg_opt;
3361                         break;
3362                 case 'D':
3363                         param.fp_max_depth = strtol(optarg, 0, 0);
3364                         break;
3365                 case 'E':
3366                         if (optarg[0] == '+') {
3367                                 param.fp_comp_end_sign = -1;
3368                                 optarg++;
3369                         } else if (optarg[0] == '-') {
3370                                 param.fp_comp_end_sign =  1;
3371                                 optarg++;
3372                         }
3373
3374                         if (arg_is_eof(optarg)) {
3375                                 param.fp_comp_end = LUSTRE_EOF;
3376                                 param.fp_comp_end_units = 1;
3377                                 rc = 0;
3378                         } else {
3379                                 rc = llapi_parse_size(optarg,
3380                                                 &param.fp_comp_end,
3381                                                 &param.fp_comp_end_units, 0);
3382                         }
3383                         if (rc) {
3384                                 fprintf(stderr, "error: bad component end "
3385                                         "'%s'\n", optarg);
3386                                 goto err;
3387                         }
3388                         param.fp_check_comp_end = 1;
3389                         param.fp_exclude_comp_end = !!neg_opt;
3390                         break;
3391                 case 'g':
3392                 case 'G':
3393                         rc = name2gid(&param.fp_gid, optarg);
3394                         if (rc) {
3395                                 param.fp_gid = strtoul(optarg, &endptr, 10);
3396                                 if (*endptr != '\0') {
3397                                         fprintf(stderr, "Group/GID: %s cannot "
3398                                                 "be found.\n", optarg);
3399                                         ret = -1;
3400                                         goto err;
3401                                 }
3402                         }
3403                         param.fp_exclude_gid = !!neg_opt;
3404                         param.fp_check_gid = 1;
3405                         break;
3406                 case 'H':
3407                         param.fp_hash_type = check_hashtype(optarg);
3408                         if (param.fp_hash_type == 0) {
3409                                 fprintf(stderr, "error: bad hash_type '%s'\n",
3410                                         optarg);
3411                                 ret = -1;
3412                                 goto err;
3413                         }
3414                         param.fp_check_hash_type = 1;
3415                         param.fp_exclude_hash_type = !!neg_opt;
3416                         break;
3417                 case 'L':
3418                         ret = name2layout(&param.fp_layout, optarg);
3419                         if (ret)
3420                                 goto err;
3421                         param.fp_exclude_layout = !!neg_opt;
3422                         param.fp_check_layout = 1;
3423                         break;
3424                 case 'u':
3425                 case 'U':
3426                         rc = name2uid(&param.fp_uid, optarg);
3427                         if (rc) {
3428                                 param.fp_uid = strtoul(optarg, &endptr, 10);
3429                                 if (*endptr != '\0') {
3430                                         fprintf(stderr, "User/UID: %s cannot "
3431                                                 "be found.\n", optarg);
3432                                         ret = -1;
3433                                         goto err;
3434                                 }
3435                         }
3436                         param.fp_exclude_uid = !!neg_opt;
3437                         param.fp_check_uid = 1;
3438                         break;
3439                 case 'n':
3440                         param.fp_pattern = (char *)optarg;
3441                         param.fp_exclude_pattern = !!neg_opt;
3442                         break;
3443                 case 'N':
3444                         if (optarg[0] == '+') {
3445                                 param.fp_mirror_count_sign = -1;
3446                                 optarg++;
3447                         } else if (optarg[0] == '-') {
3448                                 param.fp_mirror_count_sign =  1;
3449                                 optarg++;
3450                         }
3451
3452                         param.fp_mirror_count = strtoul(optarg, &endptr, 0);
3453                         if (*endptr != '\0') {
3454                                 fprintf(stderr,
3455                                         "error: bad mirror count '%s'\n",
3456                                         optarg);
3457                                 goto err;
3458                         }
3459                         param.fp_check_mirror_count = 1;
3460                         param.fp_exclude_mirror_count = !!neg_opt;
3461                         break;
3462                 case 'm':
3463                 case 'i':
3464                 case 'O': {
3465                         char *buf, *token, *next, *p;
3466                         int len = 1;
3467                         void *tmp;
3468
3469                         buf = strdup(optarg);
3470                         if (buf == NULL) {
3471                                 ret = -ENOMEM;
3472                                 goto err;
3473                         }
3474
3475                         param.fp_exclude_obd = !!neg_opt;
3476
3477                         token = buf;
3478                         while (token && *token) {
3479                                 token = strchr(token, ',');
3480                                 if (token) {
3481                                         len++;
3482                                         token++;
3483                                 }