Whamcloud - gitweb
LU-930 doc: update lfs migrate usage and man page
[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  *
31  * lustre/utils/lfs.c
32  *
33  * Author: Peter J. Braam <braam@clusterfs.com>
34  * Author: Phil Schwan <phil@clusterfs.com>
35  * Author: Robert Read <rread@clusterfs.com>
36  */
37
38 /* for O_DIRECTORY */
39 #ifndef _GNU_SOURCE
40 #define _GNU_SOURCE
41 #endif
42
43 #include <stdlib.h>
44 #include <stdio.h>
45 #include <inttypes.h>
46 #include <getopt.h>
47 #include <string.h>
48 #include <mntent.h>
49 #include <unistd.h>
50 #include <errno.h>
51 #include <err.h>
52 #include <pwd.h>
53 #include <grp.h>
54 #include <sys/ioctl.h>
55 #include <sys/quota.h>
56 #include <sys/time.h>
57 #include <sys/types.h>
58 #include <sys/stat.h>
59 #include <sys/param.h>
60 #include <sys/xattr.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 <asm/byteorder.h>
68 #include "lfs_project.h"
69
70 #include <libcfs/util/string.h>
71 #include <libcfs/util/ioctl.h>
72 #include <libcfs/util/parser.h>
73 #include <libcfs/util/string.h>
74 #include <lustre/lustreapi.h>
75 #include <linux/lustre/lustre_ver.h>
76 #include <linux/lustre/lustre_param.h>
77 #include <linux/lnet/nidstr.h>
78 #include <lnetconfig/cyaml.h>
79 #include "lstddef.h"
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_unlink_foreign(int argc, char **argv);
88 static int lfs_osts(int argc, char **argv);
89 static int lfs_mdts(int argc, char **argv);
90 static int lfs_df(int argc, char **argv);
91 static int lfs_getname(int argc, char **argv);
92 static int lfs_check(int argc, char **argv);
93 #ifdef HAVE_SYS_QUOTA_H
94 static int lfs_setquota(int argc, char **argv);
95 static int lfs_quota(int argc, char **argv);
96 static int lfs_project(int argc, char **argv);
97 #endif
98 static int lfs_flushctx(int argc, char **argv);
99 static int lfs_poollist(int argc, char **argv);
100 static int lfs_changelog(int argc, char **argv);
101 static int lfs_changelog_clear(int argc, char **argv);
102 static int lfs_fid2path(int argc, char **argv);
103 static int lfs_path2fid(int argc, char **argv);
104 static int lfs_rmfid(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_getsom(int argc, char **argv);
119 static int lfs_heat_get(int argc, char **argv);
120 static int lfs_heat_set(int argc, char **argv);
121 static int lfs_mirror(int argc, char **argv);
122 static int lfs_mirror_list_commands(int argc, char **argv);
123 static int lfs_list_commands(int argc, char **argv);
124 static inline int lfs_mirror_resync(int argc, char **argv);
125 static inline int lfs_mirror_verify(int argc, char **argv);
126 static inline int lfs_mirror_read(int argc, char **argv);
127 static inline int lfs_mirror_write(int argc, char **argv);
128 static inline int lfs_mirror_copy(int argc, char **argv);
129 static int lfs_pcc_attach(int argc, char **argv);
130 static int lfs_pcc_attach_fid(int argc, char **argv);
131 static int lfs_pcc_detach(int argc, char **argv);
132 static int lfs_pcc_detach_fid(int argc, char **argv);
133 static int lfs_pcc_state(int argc, char **argv);
134 static int lfs_pcc(int argc, char **argv);
135 static int lfs_pcc_list_commands(int argc, char **argv);
136 static int lfs_migrate_to_dom(int fd, int fdv, char *name,
137                               __u64 migration_flags,
138                               struct llapi_stripe_param *param,
139                               struct llapi_layout *layout);
140
141 struct pool_to_id_cbdata {
142         const char *pool;
143         __u32 id;
144 };
145 static int find_comp_id_by_pool(struct llapi_layout *layout, void *cbdata);
146 static int find_mirror_id_by_pool(struct llapi_layout *layout, void *cbdata);
147
148 enum setstripe_origin {
149         SO_SETSTRIPE,
150         SO_MIGRATE,
151         SO_MIGRATE_MDT,
152         SO_MIRROR_CREATE,
153         SO_MIRROR_EXTEND,
154         SO_MIRROR_SPLIT,
155         SO_MIRROR_DELETE,
156 };
157
158 static int lfs_setstripe_internal(int argc, char **argv,
159                                   enum setstripe_origin opc);
160
161 static inline int lfs_setstripe(int argc, char **argv)
162 {
163         return lfs_setstripe_internal(argc, argv, SO_SETSTRIPE);
164 }
165
166 static inline int lfs_setstripe_migrate(int argc, char **argv)
167 {
168         return lfs_setstripe_internal(argc, argv, SO_MIGRATE);
169 }
170
171 static inline int lfs_mirror_create(int argc, char **argv)
172 {
173         return lfs_setstripe_internal(argc, argv, SO_MIRROR_CREATE);
174 }
175
176 static inline int lfs_mirror_extend(int argc, char **argv)
177 {
178         return lfs_setstripe_internal(argc, argv, SO_MIRROR_EXTEND);
179 }
180
181 static inline int lfs_mirror_split(int argc, char **argv)
182 {
183         return lfs_setstripe_internal(argc, argv, SO_MIRROR_SPLIT);
184 }
185
186 static inline int lfs_mirror_delete(int argc, char **argv)
187 {
188         return lfs_setstripe_internal(argc, argv, SO_MIRROR_DELETE);
189 }
190
191 /* Setstripe and migrate share mostly the same parameters */
192 #define SSM_CMD_COMMON(cmd) \
193         "usage: "cmd" [--component-end|-E COMP_END]\n"                  \
194         "                 [--copy=LUSTRE_SRC]\n"                        \
195         "                 [--extension-size|--ext-size|-z SIZE]\n"      \
196         "                 [--help|-h] [--layout|-L PATTERN]\n"          \
197         "                 [--layout|-L PATTERN]\n"                      \
198         "                 [--mirror-count|-N[MIRROR_COUNT]]\n"          \
199         "                 [--ost|-o OST_INDICES]\n"                     \
200         "                 [--overstripe-count|-C STRIPE_COUNT]\n"       \
201         "                 [--pool|-p POOL_NAME]\n"                      \
202         "                 [--stripe-count|-c STRIPE_COUNT]\n"           \
203         "                 [--stripe-index|-i START_OST_IDX]\n"          \
204         "                 [--stripe-size|-S STRIPE_SIZE]\n"             \
205         "                 [--yaml|-y YAML_TEMPLATE_FILE]\n"
206
207 #define MIRROR_EXTEND_USAGE                                             \
208         "                 {--mirror-count|-N[MIRROR_COUNT]}\n"          \
209         "                 [SETSTRIPE_OPTIONS|-f|--file VICTIM_FILE]\n"  \
210         "                 [--no-verify]\n"
211
212 #define SETSTRIPE_USAGE                                                 \
213         SSM_CMD_COMMON("setstripe")                                     \
214         MIRROR_EXTEND_USAGE                                             \
215         "                 DIRECTORY|FILENAME\n"
216
217 #define MIGRATE_USAGE                                                   \
218         SSM_CMD_COMMON("migrate  ")                                     \
219         "                 [--block|-b] [--non-block|-n]\n"              \
220         "                 [--non-direct|-D] [--verbose|-v]\n"           \
221         "                 FILENAME\n"
222
223 #define SETDIRSTRIPE_USAGE                                              \
224         "               [--mdt-count|-c stripe_count>\n"                \
225         "               [--help|-h] [--mdt-hash|-H mdt_hash]\n"         \
226         "               [--mdt-index|-i mdt_index[,mdt_index,...]\n"    \
227         "               [--default|-D] [--mode|-o mode]\n"              \
228         "               [--max-inherit|-X max_inherit]\n"               \
229         "               [--max-inherit-rr max_inherit_rr] <dir>\n"      \
230         "To create dir with a foreign (free format) layout :\n"         \
231         "setdirstripe|mkdir --foreign[=FOREIGN_TYPE] -x|-xattr STRING " \
232         "               [--mode|-o MODE] [--flags HEX] DIRECTORY\n"
233
234 /**
235  * command_t mirror_cmdlist - lfs mirror commands.
236  */
237 command_t mirror_cmdlist[] = {
238         { .pc_name = "create", .pc_func = lfs_mirror_create,
239           .pc_help = "Create a mirrored file.\n"
240                 "usage: lfs mirror create --mirror-count|-N[MIRROR_COUNT]\n"
241                 "           [SETSTRIPE_OPTIONS] ... FILENAME|DIRECTORY ...\n" },
242         { .pc_name = "delete", .pc_func = lfs_mirror_delete,
243           .pc_help = "Delete a mirror from a file.\n"
244         "usage: lfs mirror delete {--mirror-id <mirror_id> |\n"
245         "\t               --component-id|--comp-id|-I COMP_ID |\n"
246         "\t               -p <pool>} MIRRORED_FILE ...\n"
247         },
248         { .pc_name = "extend", .pc_func = lfs_mirror_extend,
249           .pc_help = "Extend a mirrored file.\n"
250                 "usage: lfs mirror extend "
251                 "{--mirror-count|-N[MIRROR_COUNT]} [--no-verify] "
252                 "[SETSTRIPE_OPTIONS|-f VICTIM_FILE] ... FILENAME ...\n" },
253         { .pc_name = "split", .pc_func = lfs_mirror_split,
254           .pc_help = "Split a mirrored file.\n"
255         "usage: lfs mirror split {--mirror-id MIRROR_ID |\n"
256         "\t             --component-id|-I COMP_ID|-p POOL} [--destroy|-d]\n"
257         "\t             [-f NEW_FILE] MIRRORED_FILE ...\n" },
258         { .pc_name = "read", .pc_func = lfs_mirror_read,
259           .pc_help = "Read the content of a specified mirror of a file.\n"
260                 "usage: lfs mirror read {--mirror-id|-N MIRROR_ID}\n"
261                 "\t\t[--outfile|-o <output_file>] <mirrored_file>\n" },
262         { .pc_name = "write", .pc_func = lfs_mirror_write,
263           .pc_help = "Write to a specified mirror of a file.\n"
264                 "usage: lfs mirror write {--mirror-id|-N MIRROR_ID}\n"
265                 "\t\t[--inputfile|-i <input_file>] <mirrored_file>\n" },
266         { .pc_name = "copy", .pc_func = lfs_mirror_copy,
267           .pc_help = "Copy a specified mirror to other mirror(s) of a file.\n"
268                 "usage: lfs mirror copy {--read-mirror|-i MIRROR_ID0}\n"
269                 "\t\t{--write-mirror|-o MIRROR_ID1[,...]} <mirrored_file>\n" },
270         { .pc_name = "resync", .pc_func = lfs_mirror_resync,
271           .pc_help = "Resynchronizes out-of-sync mirrored file(s).\n"
272                 "usage: lfs mirror resync [--only MIRROR_ID[,...]>]\n"
273                 "\t\t<mirrored_file> [<mirrored_file2>...]\n" },
274         { .pc_name = "verify", .pc_func = lfs_mirror_verify,
275           .pc_help = "Verify mirrored file(s).\n"
276                 "usage: lfs mirror verify [--only MIRROR_ID[,...]]\n"
277                 "\t\t[--verbose|-v] <mirrored_file> [<mirrored_file2> ...]\n" },
278         { .pc_name = "list-commands", .pc_func = lfs_mirror_list_commands,
279           .pc_help = "list commands supported by lfs mirror"},
280         { .pc_name = "help", .pc_func = Parser_help, .pc_help = "help" },
281         { .pc_name = "exit", .pc_func = Parser_quit, .pc_help = "quit" },
282         { .pc_name = "quit", .pc_func = Parser_quit, .pc_help = "quit" },
283         { .pc_help = NULL }
284 };
285
286 /**
287  * command_t pcc_cmdlist - lfs pcc commands.
288  */
289 command_t pcc_cmdlist[] = {
290         { .pc_name = "attach", .pc_func = lfs_pcc_attach,
291           .pc_help = "Attach given files to the Persistent Client Cache.\n"
292                 "usage: lfs pcc attach <--id|-i NUM> <file> ...\n"
293                 "\t-i: archive id for RW-PCC\n" },
294         { .pc_name = "attach_fid", .pc_func = lfs_pcc_attach_fid,
295           .pc_help = "Attach given files into PCC by FID(s).\n"
296                 "usage: lfs pcc attach_id {--id|-i NUM} {--mnt|-m MOUNTPOINT} FID ...\n"
297                 "\t-i: archive id for RW-PCC\n"
298                 "\t-m: Lustre mount point\n" },
299         { .pc_name = "state", .pc_func = lfs_pcc_state,
300           .pc_help = "Display the PCC state for given files.\n"
301                 "usage: lfs pcc state <file> ...\n" },
302         { .pc_name = "detach", .pc_func = lfs_pcc_detach,
303           .pc_help = "Detach given files from the Persistent Client Cache.\n"
304                 "usage: lfs pcc detach <file> ...\n" },
305         { .pc_name = "detach_fid", .pc_func = lfs_pcc_detach_fid,
306           .pc_help = "Detach given files from PCC by FID(s).\n"
307                 "usage: lfs pcc detach_fid <mntpath> <fid>...\n" },
308         { .pc_name = "list-commands", .pc_func = lfs_pcc_list_commands,
309           .pc_help = "list commands supported by lfs pcc"},
310         { .pc_name = "help", .pc_func = Parser_help, .pc_help = "help" },
311         { .pc_name = "exit", .pc_func = Parser_quit, .pc_help = "quit" },
312         { .pc_name = "quit", .pc_func = Parser_quit, .pc_help = "quit" },
313         { .pc_help = NULL }
314 };
315
316 /* all available commands */
317 command_t cmdlist[] = {
318         {"setstripe", lfs_setstripe, 0,
319          "To create a file with specified striping/composite layout, or\n"
320          "create/replace the default layout on an existing directory:\n"
321          SSM_CMD_COMMON("setstripe")
322          "                 [--mode MODE]\n"
323          "                 <directory|filename>\n"
324          " or\n"
325          "To add component(s) to an existing composite file:\n"
326          SSM_CMD_COMMON("setstripe --component-add")
327          "To totally delete the default striping from an existing directory:\n"
328          "usage: setstripe [--delete|-d] <directory>\n"
329          " or\n"
330          "To create a mirrored file or set s default mirror layout on a directory:\n"
331          "usage: setstripe {--mirror-count|-N}[MIRROR_COUNT] [SETSTRIPE_OPTIONS] <directory|filename>\n"
332          " or\n"
333          "To delete the last component(s) from an existing composite file\n"
334          "(note that this will also delete any data in those components):\n"
335          "usage: setstripe --component-del [--component-id|-I COMP_ID]\n"
336          "                               [--component-flags|-F COMP_FLAGS]\n"
337          "                               <filename>\n"
338          "\tCOMP_ID:     Unique component ID to delete\n"
339          "\tCOMP_FLAGS:  'init' indicating all instantiated components\n"
340          "\t             '^init' indicating all uninstantiated components\n"
341          "\t-I and -F cannot be specified at the same time\n"
342          " or\n"
343          "To set or clear flags on a specific component\n"
344          "(note that this command can only be applied to mirrored files:\n"
345          "usage: setstripe --comp-set {-I COMP_ID|--comp-flags=COMP_FLAGS}\n"
346          "                            <filename>\n"
347          " or\n"
348          "To create a file with a foreign (free format) layout:\n"
349          "usage: setstripe --foreign[=FOREIGN_TYPE]\n"
350          "                 --xattr|-x LAYOUT_STRING [--flags HEX]\n"
351          "                 [--mode MODE] <filename>\n"},
352         {"getstripe", lfs_getstripe, 0,
353          "To list the layout pattern for a given file or files in a\n"
354          "directory or recursively for all files in a directory tree.\n"
355          "usage: getstripe [--ost|-O UUID] [--quiet|-q] [--verbose|-v]\n"
356          "                 [--stripe-count|-c] [--stripe-index|-i] [--fid|-F]\n"
357          "                 [--pool|-p] [--stripe-size|-S] [--directory|-d]\n"
358          "                 [--mdt-index|-m] [--recursive|-r] [--raw|-R]\n"
359          "                 [--layout|-L] [--generation|-g] [--yaml|-y]\n"
360          "                 [--help|-h] [--component-id|-I[=COMP_ID]]\n"
361          "                 [--component-flags[=COMP_FLAGS]]\n"
362          "                 [--component-count]\n"
363          "                 [--extension-size|--ext-size|-z]\n"
364          "                 [--component-start[=[+-]COMP_START]]\n"
365          "                 [--component-end[=[+-]COMP_END]|-E[[+-]comp_end]]\n"
366          "                 [[!] --mirror-index=[+-]INDEX |\n"
367          "                 [!] --mirror-id=[+-]MIRROR_ID] [--mirror-count|-N]\n"
368          "                 <directory|filename> ..."},
369         {"setdirstripe", lfs_setdirstripe, 0,
370          "Create striped directory on specified MDT, same as mkdir.\n"
371          "May be restricted to root or group users, depending on settings.\n"
372          "usage: setdirstripe [OPTION] <directory>\n"
373          SETDIRSTRIPE_USAGE},
374         {"getdirstripe", lfs_getdirstripe, 0,
375          "To list the layout pattern info for a given directory\n"
376          "or recursively for all directories in a directory tree.\n"
377          "usage: getdirstripe [--mdt-count|-c] [--mdt-index|-m|-i]\n"
378          "                    [--help|-h] [--mdt-hash|-H] [--obd|-O UUID]\n"
379          "                    [--recursive|-r] [--yaml|-y]\n"
380          "                    [--verbose|-v] [--default|-D]\n"
381          "                    [--max-inherit|-X]\n"
382          "                    [--max-inherit-rr] <dir> ..."},
383         {"mkdir", lfs_setdirstripe, 0,
384          "Create striped directory on specified MDT, same as setdirstripe.\n"
385          "usage: mkdir [OPTION] <directory>\n"
386          SETDIRSTRIPE_USAGE},
387         {"rm_entry", lfs_rmentry, 0,
388          "To remove the name entry of the remote directory. Note: This\n"
389          "command will only delete the name entry, i.e. the remote directory\n"
390          "will become inaccessable after this command. This can only be done\n"
391          "by the administrator\n"
392          "usage: rm_entry <dir>\n"},
393         {"unlink_foreign", lfs_unlink_foreign, 0,
394          "To remove the foreign file/dir.\n"
395          "Note: This is for files/dirs prevented to be removed using\n"
396          "unlink/rmdir, but works also for regular ones\n"
397          "usage: unlink_foreign <foreign_dir/file> [<foreign_dir/file> ...]\n"},
398         {"pool_list", lfs_poollist, 0,
399          "List pools or pool OSTs\n"
400          "usage: pool_list <fsname>[.<pool>] | <pathname>\n"},
401         {"find", lfs_find, 0,
402          "find files matching given attributes recursively in directory tree.\n"
403          "usage: find <directory|filename> ...\n"
404          "     [[!] --atime|-A [+-]N[smhdwy]] [[!] --ctime|-C [+-]N[smhdwy]]\n"
405          "     [[!] --mtime|-M [+-]N[smhdwy]]\n"
406          "     [[!] --btime|--Btime|-B [+-]N[smhdwy]] [--help|-h]\n"
407          "     [[!] --newer[XY] <reference>] [[!] --blocks|-b N]\n"
408          "     [--maxdepth|-D N] [[!] --mdt-index|--mdt|-m <uuid|index,...>]\n"
409          "     [[!] --name|-n <pattern>] [[!] --ost|-O <uuid|index,...>]\n"
410          "     [[!] --perm [/-]mode] [[!] --pool <pool>] [--print|-P]\n"
411          "     [--print0|-0] [[!] --projid <projid>]\n"
412          "     [[!] --size|-s [+-]N[bkMGTPE]]\n"
413          "     [[!] --stripe-count|-c [+-]<stripes>]\n"
414          "     [[!] --stripe-index|-i <index,...>]\n"
415          "     [[!] --stripe-size|-S [+-]N[kMGT]] [[!] --type|-t <filetype>]\n"
416          "     [[!] --extension-size|--ext-size|-z [+-]N[kMGT]]\n"
417          "     [[!] --gid|-g|--group|-G <gid>|<gname>]\n"
418          "     [[!] --uid|-u|--user|-U <uid>|<uname>]\n"
419          "     [[!] --layout|-L released,raid0,mdt]\n"
420          "     [[!] --foreign[=<foreign_type>]]\n"
421          "     [[!] --component-count [+-]<comp_cnt>]\n"
422          "     [[!] --component-start [+-]N[kMGTPE]]\n"
423          "     [[!] --component-end|-E [+-]N[kMGTPE]]\n"
424          "     [[!] --component-flags {init,stale,prefer,offline,nosync,extension}]\n"
425          "     [[!] --mirror-count|-N [+-]<n>]\n"
426          "     [[!] --mirror-state <[^]state>]\n"
427          "     [[!] --mdt-count|-T [+-]<stripes>]\n"
428          "     [[!] --mdt-hash|-H <[^][blm],[^]fnv_1a_64,all_char,crush,...>\n"
429          "     [[!] --mdt-index|-m <uuid|index,...>]\n"
430          "\t !: used before an option indicates 'NOT' requested attribute\n"
431          "\t -: used before a value indicates less than requested value\n"
432          "\t +: used before a value indicates more than requested value\n"
433          "\t ^: used before a flag indicates to exclude it\n"},
434         {"check", lfs_check, 0,
435          "Display the status of MGTs, MDTs or OSTs (as specified in the command)\n"
436          "or all the servers (MGTs, MDTs and OSTs).\n"
437          "usage: check {mgts|osts|mdts|all}"},
438         {"osts", lfs_osts, 0, "list OSTs connected to client "
439          "[for specified path only]\n" "usage: osts [path]"},
440         {"mdts", lfs_mdts, 0, "list MDTs connected to client "
441          "[for specified path only]\n" "usage: mdts [path]"},
442         {"df", lfs_df, 0,
443          "report filesystem disk space usage or inodes usage "
444          "of each MDS and all OSDs or a batch belonging to a specific pool.\n"
445          "Usage: df [--inodes|-i] [--human-readable|-h] [--lazy|-l]\n"
446          "          [--pool|-p <fsname>[.<pool>]] [path]"},
447         {"getname", lfs_getname, 0,
448          "list instances and specified mount points [for specified path only]\n"
449          "Usage: getname [--help|-h] [--instance|-i] [--fsname|-n] [path ...]"},
450 #ifdef HAVE_SYS_QUOTA_H
451         {"setquota", lfs_setquota, 0, "Set filesystem quotas.\n"
452          "usage: setquota {-u|-g|-p} UNAME|UID|GNAME|GID|PROJID\n"
453          "                -b BLOCK_SOFTLIMIT -B BLOCK_HARDLIMIT\n"
454          "                -i INODE_SOFTLIMIT -I INODE_HARDLIMIT <filesystem>\n"
455          "       setquota {-u|--user USER|UID|-g|--group GROUP|GID|-p|--projid PROJID}\n"
456          "                [--block-softlimit BLOCK_SOFTLIMIT]\n"
457          "                [--block-hardlimit BLOCK_HARDLIMIT]\n"
458          "                [--inode-softlimit INODE_SOFTLIMIT]\n"
459          "                [--inode-hardlimit INODE_HARDLIMIT] <filesystem>\n"
460          "       setquota [-t] {-h|--help|-u|--user|-g|--group|-p|--projid}\n"
461          "                [--block-grace 'notify'|BLOCK_GRACE]\n"
462          "                [--inode-grace 'notify'|INODE_GRACE] <filesystem>\n"
463          "       setquota {-U|-G|-P}\n"
464          "                -b BLOCK_SOFTLIMIT -B BLOCK_HARDLIMIT\n"
465          "                -i INODE_SOFTLIMIT -I INODE_HARDLIMIT <filesystem>\n"
466          "       setquota {-U|--default-usr|-G|--default-grp|-P|--default-prj}\n"
467          "                [--block-softlimit BLOCK_SOFTLIMIT]\n"
468          "                [--block-hardlimit BLOCK_HARDLIMIT]\n"
469          "                [--inode-softlimit INODE_SOFTLIMIT]\n"
470          "                [--inode-hardlimit INODE_HARDLIMIT] <filesystem>\n"
471          "       setquota {-u|-g|-p} UNAME|UID|GNAME|GID|PROJID\n"
472          "                {-d|--default}\n"
473          "       -b can be used instead of --block-softlimit/--block-grace\n"
474          "       -B can be used instead of --block-hardlimit\n"
475          "       -i can be used instead of --inode-softlimit/--inode-grace\n"
476          "       -I can be used instead of --inode-hardlimit\n"
477          "       -d can be used instead of --default\n\n"
478          "Note: The total quota space will be split into many qunits and\n"
479          "      balanced over all server targets, the minimal qunit size is\n"
480          "      1M bytes for block space and 1K inodes for inode space.\n\n"
481          "      The maximum quota grace time is 2^48 - 1 seconds.\n\n"
482          "      Quota space rebalancing process will stop when this mininum\n"
483          "      value is reached. As a result, quota exceeded can be returned\n"
484          "      while many targets still have 1MB or 1K inodes of spare\n"
485          "      quota space.\n\n"
486          "      When setting the grace time, 'notify' can be used as grace to\n"
487          "      be notified after the quota is over soft limit but prevents\n"
488          "      the soft limit from becoming the hard limit."},
489         {"quota", lfs_quota, 0, "Display disk usage and limits.\n"
490          "usage: quota [-q] [-v] [-h] [-o OBD_UUID|-i MDT_IDX|-I OST_IDX]\n"
491          "             [{-u|-g|-p} UNAME|UID|GNAME|GID|PROJID] <filesystem>\n"
492          "       quota [-o OBD_UUID|-i MDT_IDX|-I OST_IDX] -t {-u|-g|-p} <filesystem>\n"
493         "        quota [-q] [-v] [h] {-U|-G|-P} <filesystem>"},
494         {"project", lfs_project, 0,
495          "Change or list project attribute for specified file or directory.\n"
496          "usage: project [-d|-r] <file|directory...>\n"
497          "         list project ID and flags on file(s) or directories\n"
498          "       project [-p id] [-s] [-r] <file|directory...>\n"
499          "         set project ID and/or inherit flag for specified file(s) or directories\n"
500          "       project -c [-d|-r [-p id] [-0]] <file|directory...>\n"
501          "         check project ID and flags on file(s) or directories, print outliers\n"
502          "       project -C [-r] [-k] <file|directory...>\n"
503          "         clear the project inherit flag and ID on the file or directory\n"
504         },
505 #endif
506         {"flushctx", lfs_flushctx, 0,
507          "Flush security context for current user.\n"
508          "usage: flushctx [-k] [-r] [mountpoint...]"},
509         {"changelog", lfs_changelog, 0,
510          "Show the metadata changes on an MDT."
511          "\nusage: changelog <mdtname> [startrec [endrec]]"},
512         {"changelog_clear", lfs_changelog_clear, 0,
513          "Indicate that old changelog records up to <endrec> are no longer of "
514          "interest to consumer <id>, allowing the system to free up space.\n"
515          "An <endrec> of 0 means all records.\n"
516          "usage: changelog_clear <mdtname> <id> <endrec>"},
517         {"fid2path", lfs_fid2path, 0,
518          "Resolve the full path(s) for given FID(s). For a specific hardlink "
519          "specify link number <linkno>.\n"
520          "usage: fid2path [--print-fid|-f] [--print-link|-c] [--link|-l <linkno>] "
521          "<fsname|root> <fid>..."},
522         {"path2fid", lfs_path2fid, 0, "Display the fid(s) for a given path(s).\n"
523          "usage: path2fid [--parents] <path> ..."},
524         {"rmfid", lfs_rmfid, 0, "Remove file(s) by FID(s)\n"
525          "usage: rmfid <fsname|rootpath> <fid> ..."},
526         {"data_version", lfs_data_version, 0, "Display file data version for "
527          "a given path.\n" "usage: data_version [-n|-r|-w] <path>"},
528         {"hsm_state", lfs_hsm_state, 0, "Display the HSM information (states, "
529          "undergoing actions) for given files.\n usage: hsm_state <file> ..."},
530         {"hsm_set", lfs_hsm_set, 0, "Set HSM user flag on specified files.\n"
531          "usage: hsm_set [--norelease] [--noarchive] [--dirty] [--exists] "
532          "[--archived] [--lost] [--archive-id NUM] <file> ..."},
533         {"hsm_clear", lfs_hsm_clear, 0, "Clear HSM user flag on specified "
534          "files.\n"
535          "usage: hsm_clear [--norelease] [--noarchive] [--dirty] [--exists] "
536          "[--archived] [--lost] <file> ..."},
537         {"hsm_action", lfs_hsm_action, 0, "Display current HSM request for "
538          "given files.\n" "usage: hsm_action <file> ..."},
539         {"hsm_archive", lfs_hsm_archive, 0,
540          "Archive file to external storage.\n"
541          "usage: hsm_archive [--filelist FILELIST] [--data DATA] [--archive NUM] "
542          "<file> ..."},
543         {"hsm_restore", lfs_hsm_restore, 0,
544          "Restore file from external storage.\n"
545          "usage: hsm_restore [--filelist FILELIST] [--data DATA] <file> ..."},
546         {"hsm_release", lfs_hsm_release, 0,
547          "Release files from Lustre.\n"
548          "usage: hsm_release [--filelist FILELIST] [--data DATA] <file> ..."},
549         {"hsm_remove", lfs_hsm_remove, 0,
550          "Remove file copy from external storage.\n"
551          "usage: hsm_remove [--filelist FILELIST] [--data DATA] "
552          "[--archive NUM]\n"
553          "                  (FILE [FILE ...] | "
554          "--mntpath MOUNTPATH FID [FID ...])\n"
555          "\n"
556          "Note: To remove an archived copy of a file already deleted from a "
557          "Lustre FS, the\n"
558          "--mntpath option and a list of FIDs must be specified"
559         },
560         {"hsm_cancel", lfs_hsm_cancel, 0,
561          "Cancel requests related to specified files.\n"
562          "usage: hsm_cancel [--filelist FILELIST] [--data DATA] <file> ..."},
563         {"swap_layouts", lfs_swap_layouts, 0, "Swap layouts between 2 files.\n"
564          "usage: swap_layouts <path1> <path2>"},
565         {"migrate", lfs_setstripe_migrate, 0,
566          "migrate directories and their inodes between MDTs.\n"
567          "usage: migrate [--mdt-count|-c STRIPE_COUNT]\n"
568          "               [--mdt-hash|-H HASH_TYPE]\n"
569          "               [--mdt-index|-m START_MDT_INDEX] [--verbose|-v]\n"
570          "               DIRECTORY\n"
571          "\n"
572          "migrate file objects from one OST layout to another\n"
573          "(may be not safe with concurent writes).\n"
574          MIGRATE_USAGE },
575         {"mv", lfs_mv, 0,
576          "To move directories between MDTs. This command is deprecated, "
577          "use \"migrate\" instead.\n"
578          "usage: mv <directory|filename> [--mdt-index|-m MDT_INDEX] "
579          "[--verbose|-v]\n"},
580         {"ladvise", lfs_ladvise, 0,
581          "Provide servers with advice about access patterns for a file.\n"
582          "usage: ladvise [--advice|-a ADVICE] [--start|-s START[kMGT]]\n"
583          "               [--background|-b] [--unset|-u]\n\n"
584          "               {--end|-e END[kMGT]|--length|-l LENGTH[kMGT]}\n"
585          "               {[--mode|-m [READ,WRITE]}\n"
586          "               <file> ...\n"},
587         {"mirror", lfs_mirror, mirror_cmdlist,
588          "lfs commands used to manage files with mirrored components:\n"
589          "lfs mirror create - create a mirrored file or directory\n"
590          "lfs mirror extend - add mirror(s) to an existing file\n"
591          "lfs mirror split  - split a mirror from an existing mirrored file\n"
592          "lfs mirror resync - resynchronize out-of-sync mirrored file(s)\n"
593          "lfs mirror read   - read a mirror content of a mirrored file\n"
594          "lfs mirror write  - write to a mirror of a mirrored file\n"
595          "lfs mirror copy   - copy a mirror to other mirror(s) of a file\n"
596          "lfs mirror verify - verify mirrored file(s)\n"},
597         {"getsom", lfs_getsom, 0, "To list the SOM info for a given file.\n"
598          "usage: getsom [-s] [-b] [-f] <path>\n"
599          "\t-s: Only show the size value of the SOM data for a given file\n"
600          "\t-b: Only show the blocks value of the SOM data for a given file\n"
601          "\t-f: Only show the flags value of the SOM data for a given file\n"},
602         {"heat_get", lfs_heat_get, 0,
603          "To get heat of files.\n"
604          "usage: heat_get <file> ...\n"},
605         {"heat_set", lfs_heat_set, 0,
606          "To set heat flags of files.\n"
607          "usage: heat_set [--clear|-c] [--off|-o] [--on|-O] <file> ...\n"
608          "\t--clear|-c: Clear file heat for given files\n"
609          "\t--off|-o:   Turn off file heat for given files\n"
610          "\t--on|-O:    Turn on file heat for given files\n"},
611         {"pcc", lfs_pcc, pcc_cmdlist,
612          "lfs commands used to interact with PCC features:\n"
613          "lfs pcc attach - attach given files to Persistent Client Cache\n"
614          "lfs pcc attach_fid - attach given files into PCC by FID(s)\n"
615          "lfs pcc state  - display the PCC state for given files\n"
616          "lfs pcc detach - detach given files from Persistent Client Cache\n"
617          "lfs pcc detach_fid - detach given files from PCC by FID(s)\n"},
618         {"help", Parser_help, 0, "help"},
619         {"exit", Parser_quit, 0, "quit"},
620         {"quit", Parser_quit, 0, "quit"},
621         {"--version", Parser_version, 0,
622          "output build version of the utility and exit"},
623         {"--list-commands", lfs_list_commands, 0,
624          "list commands supported by the utility and exit"},
625         { 0, 0, 0, NULL }
626 };
627
628 static int check_hashtype(const char *hashtype)
629 {
630         int type_num = atoi(hashtype);
631         int i;
632
633         /* numeric hash type */
634         if (hashtype && strlen(hashtype) == 1 &&
635             (type_num > 0 && type_num < LMV_HASH_TYPE_MAX))
636                 return type_num;
637         /* string hash type */
638         for (i = LMV_HASH_TYPE_ALL_CHARS; i < LMV_HASH_TYPE_MAX; i++)
639                 if (strcmp(hashtype, mdt_hash_name[i]) == 0)
640                         return i;
641
642         return 0;
643 }
644
645 static uint32_t check_foreign_type_name(const char *foreign_type_name)
646 {
647         uint32_t i;
648
649         for (i = 0; i < LU_FOREIGN_TYPE_UNKNOWN; i++) {
650                 if (!lu_foreign_types[i].lft_name)
651                         break;
652                 if (strcmp(foreign_type_name,
653                            lu_foreign_types[i].lft_name) == 0)
654                         return lu_foreign_types[i].lft_type;
655         }
656
657         return LU_FOREIGN_TYPE_UNKNOWN;
658 }
659
660 static const char *error_loc = "syserror";
661
662 enum {
663         MIGRATION_NONBLOCK      = 0x0001,
664         MIGRATION_MIRROR        = 0x0002,
665         MIGRATION_NONDIRECT     = 0x0004,
666         MIGRATION_VERBOSE       = 0x0008,
667 };
668
669 static int
670 migrate_open_files(const char *name, __u64 migration_flags,
671                    const struct llapi_stripe_param *param,
672                    struct llapi_layout *layout, int *fd_src, int *fd_tgt)
673 {
674         int                      fd = -1;
675         int                      fdv = -1;
676         int                      rflags;
677         int                      mdt_index;
678         int                      random_value;
679         char                     parent[PATH_MAX];
680         char                     volatile_file[PATH_MAX];
681         char                    *ptr;
682         int                      rc;
683         struct stat              st;
684         struct stat              stv;
685
686         if (!param && !layout) {
687                 error_loc = "layout information";
688                 return -EINVAL;
689         }
690
691         /* search for file directory pathname */
692         if (strlen(name) > sizeof(parent) - 1) {
693                 error_loc = "source file name";
694                 return -ERANGE;
695         }
696
697         strncpy(parent, name, sizeof(parent));
698         ptr = strrchr(parent, '/');
699         if (!ptr) {
700                 if (!getcwd(parent, sizeof(parent))) {
701                         error_loc = "getcwd";
702                         return -errno;
703                 }
704         } else {
705                 if (ptr == parent) /* leading '/' */
706                         ptr = parent + 1;
707                 *ptr = '\0';
708         }
709
710         /* open file, direct io */
711         /* even if the file is only read, WR mode is nedeed to allow
712          * layout swap on fd
713          */
714         rflags = O_RDWR | O_NOATIME;
715         if (!(migration_flags & MIGRATION_NONDIRECT))
716                 rflags |= O_DIRECT;
717         fd = open(name, rflags);
718         if (fd < 0) {
719                 rc = -errno;
720                 error_loc = "cannot open source file";
721                 return rc;
722         }
723
724         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
725         if (rc < 0) {
726                 error_loc = "cannot get MDT index";
727                 goto out;
728         }
729
730         do {
731                 int open_flags = O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW;
732                 mode_t open_mode = S_IRUSR | S_IWUSR;
733
734                 random_value = random();
735                 rc = snprintf(volatile_file, sizeof(volatile_file),
736                               "%s/%s:%.4X:%.4X:fd=%.2d", parent,
737                               LUSTRE_VOLATILE_HDR, mdt_index,
738                               random_value, fd);
739                 if (rc >= sizeof(volatile_file)) {
740                         rc = -ENAMETOOLONG;
741                         break;
742                 }
743
744                 /* create, open a volatile file, use caching (ie no directio) */
745                 if (layout) {
746                         /* Returns -1 and sets errno on error: */
747                         fdv = llapi_layout_file_open(volatile_file, open_flags,
748                                                      open_mode, layout);
749                         if (fdv < 0)
750                                 fdv = -errno;
751                 } else {
752                         /* Does the right thing on error: */
753                         fdv = llapi_file_open_param(volatile_file, open_flags,
754                                                     open_mode, param);
755                 }
756         } while (fdv < 0 && (rc = fdv) == -EEXIST);
757
758         if (rc < 0) {
759                 error_loc = "cannot create volatile file";
760                 goto out;
761         }
762
763         /*
764          * In case the MDT does not support creation of volatile files
765          * we should try to unlink it.
766          */
767         (void)unlink(volatile_file);
768
769         /*
770          * Not-owner (root?) special case.
771          * Need to set owner/group of volatile file like original.
772          * This will allow to pass related check during layout_swap.
773          */
774         rc = fstat(fd, &st);
775         if (rc != 0) {
776                 rc = -errno;
777                 error_loc = "cannot stat source file";
778                 goto out;
779         }
780
781         rc = fstat(fdv, &stv);
782         if (rc != 0) {
783                 rc = -errno;
784                 error_loc = "cannot stat volatile";
785                 goto out;
786         }
787
788         if (st.st_uid != stv.st_uid || st.st_gid != stv.st_gid) {
789                 rc = fchown(fdv, st.st_uid, st.st_gid);
790                 if (rc != 0) {
791                         rc = -errno;
792                         error_loc = "cannot change ownwership of volatile";
793                         goto out;
794                 }
795         }
796
797 out:
798         if (rc < 0) {
799                 if (fd > 0)
800                         close(fd);
801                 if (fdv > 0)
802                         close(fdv);
803         } else {
804                 *fd_src = fd;
805                 *fd_tgt = fdv;
806                 error_loc = NULL;
807         }
808         return rc;
809 }
810
811 static int migrate_copy_data(int fd_src, int fd_dst, int (*check_file)(int))
812 {
813         struct llapi_layout *layout;
814         size_t buf_size = 4 * 1024 * 1024;
815         void *buf = NULL;
816         off_t pos = 0;
817         off_t data_end = 0;
818         size_t page_size = sysconf(_SC_PAGESIZE);
819         bool sparse;
820         int rc;
821
822         layout = llapi_layout_get_by_fd(fd_src, 0);
823         if (layout) {
824                 uint64_t stripe_size;
825
826                 rc = llapi_layout_stripe_size_get(layout, &stripe_size);
827                 if (rc == 0)
828                         buf_size = stripe_size;
829
830                 llapi_layout_free(layout);
831         }
832
833         /* Use a page-aligned buffer for direct I/O */
834         rc = posix_memalign(&buf, page_size, buf_size);
835         if (rc != 0)
836                 return -rc;
837
838         sparse = llapi_file_is_sparse(fd_src);
839         if (sparse) {
840                 rc = ftruncate(fd_dst, pos);
841                 if (rc < 0) {
842                         rc = -errno;
843                         return rc;
844                 }
845         }
846
847         while (1) {
848                 off_t data_off;
849                 size_t to_read, to_write;
850                 ssize_t rsize;
851
852                 if (sparse && pos >= data_end) {
853                         size_t data_size;
854
855                         data_off = llapi_data_seek(fd_src, pos, &data_size);
856                         if (data_off < 0) {
857                                 /* Non-fatal, switch to full copy */
858                                 sparse = false;
859                                 continue;
860                         }
861                         /* hole at the end of file, truncate up to it */
862                         if (!data_size) {
863                                 rc = ftruncate(fd_dst, data_off);
864                                 if (rc < 0)
865                                         goto out;
866                         }
867                         pos = data_off & ~(page_size - 1);
868                         data_end = data_off + data_size;
869                         to_read = ((data_end - pos - 1) | (page_size - 1)) + 1;
870                         to_read = MIN(to_read, buf_size);
871                 } else {
872                         to_read = buf_size;
873                 }
874
875                 if (check_file) {
876                         rc = check_file(fd_src);
877                         if (rc < 0)
878                                 goto out;
879                 }
880
881                 rsize = pread(fd_src, buf, to_read, pos);
882                 if (rsize < 0) {
883                         rc = -errno;
884                         goto out;
885                 }
886                 /* EOF */
887                 if (rsize == 0)
888                         break;
889
890                 to_write = rsize;
891                 while (to_write > 0) {
892                         ssize_t written;
893
894                         written = pwrite(fd_dst, buf, to_write, pos);
895                         if (written < 0) {
896                                 rc = -errno;
897                                 goto out;
898                         }
899                         pos += written;
900                         to_write -= written;
901                 }
902                 if (rc || rsize < to_read)
903                         break;
904         }
905
906         rc = fsync(fd_dst);
907         if (rc < 0)
908                 rc = -errno;
909 out:
910         /* Try to avoid page cache pollution after migration. */
911         (void)posix_fadvise(fd_src, 0, 0, POSIX_FADV_DONTNEED);
912         (void)posix_fadvise(fd_dst, 0, 0, POSIX_FADV_DONTNEED);
913
914         free(buf);
915         return rc;
916 }
917
918 static int migrate_set_timestamps(int fd, const struct stat *st)
919 {
920         struct timeval tv[2] = {
921                 {.tv_sec = st->st_atime},
922                 {.tv_sec = st->st_mtime}
923         };
924
925         return futimes(fd, tv);
926 }
927
928 static int migrate_block(int fd, int fdv)
929 {
930         struct stat st;
931         __u64   dv1;
932         int     gid;
933         int     rc;
934         int     rc2;
935
936         rc = fstat(fd, &st);
937         if (rc < 0) {
938                 error_loc = "cannot stat source file";
939                 return -errno;
940         }
941
942         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
943         if (rc < 0) {
944                 error_loc = "cannot get dataversion";
945                 return rc;
946         }
947
948         do
949                 gid = random();
950         while (gid == 0);
951
952         /*
953          * The grouplock blocks all concurrent accesses to the file.
954          * It has to be taken after llapi_get_data_version as it would
955          * block it too.
956          */
957         rc = llapi_group_lock(fd, gid);
958         if (rc < 0) {
959                 error_loc = "cannot get group lock";
960                 return rc;
961         }
962
963         rc = migrate_copy_data(fd, fdv, NULL);
964         if (rc < 0) {
965                 error_loc = "data copy failed";
966                 goto out_unlock;
967         }
968
969         /* Make sure we keep original atime/mtime values */
970         rc = migrate_set_timestamps(fdv, &st);
971         if (rc < 0) {
972                 error_loc = "set target file timestamp failed";
973                 goto out_unlock;
974         }
975
976         /*
977          * swap layouts
978          * for a migration we need to check data version on file did
979          * not change.
980          *
981          * Pass in gid=0 since we already own grouplock.
982          */
983         rc = llapi_fswap_layouts_grouplock(fd, fdv, dv1, 0, 0,
984                                            SWAP_LAYOUTS_CHECK_DV1);
985         if (rc == -EAGAIN) {
986                 error_loc = "file changed";
987                 goto out_unlock;
988         } else if (rc < 0) {
989                 error_loc = "cannot swap layout";
990                 goto out_unlock;
991         }
992
993 out_unlock:
994         rc2 = llapi_group_unlock(fd, gid);
995         if (rc2 < 0 && rc == 0) {
996                 error_loc = "unlock group lock";
997                 rc = rc2;
998         }
999
1000         return rc;
1001 }
1002
1003 /**
1004  * Internal helper for migrate_copy_data(). Check lease and report error if
1005  * need be.
1006  *
1007  * \param[in]  fd           File descriptor on which to check the lease.
1008  *
1009  * \retval 0       Migration can keep on going.
1010  * \retval -errno  Error occurred, abort migration.
1011  */
1012 static int check_lease(int fd)
1013 {
1014         int rc;
1015
1016         rc = llapi_lease_check(fd);
1017         if (rc > 0)
1018                 return 0; /* llapi_check_lease returns > 0 on success. */
1019
1020         return -EBUSY;
1021 }
1022
1023 static int migrate_nonblock(int fd, int fdv)
1024 {
1025         struct stat st;
1026         __u64   dv1;
1027         __u64   dv2;
1028         int     rc;
1029
1030         rc = fstat(fd, &st);
1031         if (rc < 0) {
1032                 error_loc = "cannot stat source file";
1033                 return -errno;
1034         }
1035
1036         rc = llapi_get_data_version(fd, &dv1, LL_DV_RD_FLUSH);
1037         if (rc < 0) {
1038                 error_loc = "cannot get data version";
1039                 return rc;
1040         }
1041
1042         rc = migrate_copy_data(fd, fdv, check_lease);
1043         if (rc < 0) {
1044                 error_loc = "data copy failed";
1045                 return rc;
1046         }
1047
1048         rc = llapi_get_data_version(fd, &dv2, LL_DV_RD_FLUSH);
1049         if (rc != 0) {
1050                 error_loc = "cannot get data version";
1051                 return rc;
1052         }
1053
1054         if (dv1 != dv2) {
1055                 rc = -EAGAIN;
1056                 error_loc = "source file changed";
1057                 return rc;
1058         }
1059
1060         /* Make sure we keep original atime/mtime values */
1061         rc = migrate_set_timestamps(fdv, &st);
1062         if (rc < 0) {
1063                 error_loc = "set target file timestamp failed";
1064                 return -errno;
1065         }
1066         return 0;
1067 }
1068
1069 static
1070 int lfs_layout_compid_by_pool(char *fname, const char *pool, int *comp_id)
1071 {
1072         struct pool_to_id_cbdata data = { .pool = pool };
1073         struct llapi_layout *layout = NULL;
1074         int rc;
1075
1076         layout = llapi_layout_get_by_path(fname, 0);
1077         if (!layout) {
1078                 fprintf(stderr,
1079                         "error %s: file '%s' couldn't get layout: rc=%d\n",
1080                         progname, fname, errno);
1081                 rc = -errno;
1082                 goto free_layout;
1083         }
1084         rc = llapi_layout_sanity(layout, fname, false, true);
1085         if (rc < 0) {
1086                 llapi_layout_sanity_perror(errno);
1087                 goto free_layout;
1088         }
1089         rc = llapi_layout_comp_iterate(layout, find_comp_id_by_pool, &data);
1090         if (rc < 0)
1091                 goto free_layout;
1092
1093         *comp_id = data.id;
1094         rc = 0;
1095
1096 free_layout:
1097         if (layout)
1098                 llapi_layout_free(layout);
1099         return rc;
1100 }
1101
1102 static int lfs_component_set(char *fname, int comp_id, const char *pool,
1103                              __u32 flags, __u32 neg_flags)
1104 {
1105         __u32 ids[2];
1106         __u32 flags_array[2];
1107         size_t count = 0;
1108         int rc;
1109
1110         if (!comp_id) {
1111                 if (pool == NULL) {
1112                         fprintf(stderr,
1113                                 "error %s: neither component id nor pool is specified\n",
1114                                 progname);
1115                         return -EINVAL;
1116                 }
1117                 rc = lfs_layout_compid_by_pool(fname, pool, &comp_id);
1118                 if (rc)
1119                         return rc;
1120         }
1121
1122         if (flags) {
1123                 ids[count] = comp_id;
1124                 flags_array[count] = flags;
1125                 ++count;
1126         }
1127
1128         if (neg_flags) {
1129                 if (neg_flags & LCME_FL_STALE) {
1130                         fprintf(stderr,
1131                                 "%s: cannot clear 'stale' flags from component. Please use lfs-mirror-resync(1) instead\n",
1132                                 progname);
1133                         return -EINVAL;
1134                 }
1135
1136                 ids[count] = comp_id;
1137                 flags_array[count] = neg_flags | LCME_FL_NEG;
1138                 ++count;
1139         }
1140
1141         rc = llapi_layout_file_comp_set(fname, ids, flags_array, count);
1142         if (rc) {
1143                 if (errno == EUCLEAN) {
1144                         rc = -errno;
1145                         fprintf(stderr,
1146                                 "%s: cannot set 'stale' flag on component '%#x' of the last non-stale mirror of '%s'\n",
1147                                 progname, comp_id, fname);
1148                 } else {
1149                         fprintf(stderr,
1150                                 "%s: cannot change the flags of component '%#x' of file '%s': %x / ^(%x)\n",
1151                                 progname, comp_id, fname, flags, neg_flags);
1152                 }
1153         }
1154
1155         return rc;
1156 }
1157
1158 static int lfs_component_del(char *fname, __u32 comp_id,
1159                              __u32 flags, __u32 neg_flags)
1160 {
1161         int     rc = 0;
1162
1163         if (flags && neg_flags)
1164                 return -EINVAL;
1165
1166         if (!flags && neg_flags)
1167                 flags = neg_flags | LCME_FL_NEG;
1168
1169         if ((flags && comp_id) || (!flags && !comp_id))
1170                 return -EINVAL;
1171
1172         if (flags) {
1173                 if (flags & ~LCME_KNOWN_FLAGS) {
1174                         fprintf(stderr,
1175                                 "%s setstripe: unknown flags %#x\n",
1176                                 progname, flags);
1177                         return -EINVAL;
1178                 }
1179         } else if (comp_id > LCME_ID_MAX) {
1180                 fprintf(stderr, "%s setstripe: invalid component id %u\n",
1181                         progname, comp_id);
1182                 return -EINVAL;
1183         }
1184
1185         rc = llapi_layout_file_comp_del(fname, comp_id, flags);
1186         if (rc)
1187                 fprintf(stderr,
1188                         "%s setstripe: cannot delete component %#x from '%s': %s\n",
1189                         progname, comp_id, fname, strerror(errno));
1190         return rc;
1191 }
1192
1193 static int lfs_component_add(char *fname, struct llapi_layout *layout)
1194 {
1195         int     rc;
1196
1197         if (!layout)
1198                 return -EINVAL;
1199
1200         rc = llapi_layout_file_comp_add(fname, layout);
1201         if (rc)
1202                 fprintf(stderr, "Add layout component(s) to %s failed. %s\n",
1203                         fname, strerror(errno));
1204         return rc;
1205 }
1206
1207 static int lfs_component_create(char *fname, int open_flags, mode_t open_mode,
1208                                 struct llapi_layout *layout)
1209 {
1210         struct stat     st;
1211         int     fd;
1212
1213         if (!layout)
1214                 return -EINVAL;
1215
1216         fd = lstat(fname, &st);
1217         if (fd == 0 && S_ISDIR(st.st_mode))
1218                 open_flags = O_DIRECTORY | O_RDONLY;
1219
1220         fd = llapi_layout_file_open(fname, open_flags, open_mode, layout);
1221         if (fd < 0)
1222                 fprintf(stderr, "%s: cannot %s '%s': %s\n", progname,
1223                         S_ISDIR(st.st_mode) ?
1224                                 "set default composite layout for" :
1225                                 "create composite file",
1226                         fname, strerror(errno));
1227         return fd;
1228 }
1229
1230 static int lfs_migrate(char *name, __u64 migration_flags,
1231                        struct llapi_stripe_param *param,
1232                        struct llapi_layout *layout)
1233 {
1234         struct llapi_layout *existing;
1235         uint64_t dom_new, dom_cur;
1236         int fd = -1;
1237         int fdv = -1;
1238         int rc;
1239
1240         rc = migrate_open_files(name, migration_flags, param, layout,
1241                                 &fd, &fdv);
1242         if (rc < 0)
1243                 goto out;
1244
1245         rc = llapi_layout_dom_size(layout, &dom_new);
1246         if (rc) {
1247                 error_loc = "cannot get new layout DoM size";
1248                 goto out;
1249         }
1250         /* special case for migration to DOM layout*/
1251         existing = llapi_layout_get_by_fd(fd, 0);
1252         if (!existing) {
1253                 error_loc = "cannot get existing layout";
1254                 goto out;
1255         }
1256
1257         rc = llapi_layout_dom_size(existing, &dom_cur);
1258         if (rc) {
1259                 error_loc = "cannot get current layout DoM size";
1260                 goto out;
1261         }
1262
1263         /*
1264          * if file has DoM layout already then migration is possible to
1265          * the new layout with the same DoM component via swap layout,
1266          * if new layout used bigger DOM size, then mirroring is used
1267          */
1268         if (dom_new > dom_cur) {
1269                 rc = lfs_migrate_to_dom(fd, fdv, name, migration_flags, param,
1270                                         layout);
1271                 if (rc)
1272                         error_loc = "cannot migrate to DOM layout";
1273                 goto out_closed;
1274         }
1275
1276         if (!(migration_flags & MIGRATION_NONBLOCK)) {
1277                 /*
1278                  * Blocking mode (forced if servers do not support file lease).
1279                  * It is also the default mode, since we cannot distinguish
1280                  * between a broken lease and a server that does not support
1281                  * atomic swap/close (LU-6785)
1282                  */
1283                 rc = migrate_block(fd, fdv);
1284                 goto out;
1285         }
1286
1287         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1288         if (rc < 0) {
1289                 error_loc = "cannot get lease";
1290                 goto out;
1291         }
1292
1293         rc = migrate_nonblock(fd, fdv);
1294         if (rc < 0) {
1295                 llapi_lease_release(fd);
1296                 goto out;
1297         }
1298
1299         /*
1300          * Atomically put lease, swap layouts and close.
1301          * for a migration we need to check data version on file did
1302          * not change.
1303          */
1304         rc = llapi_fswap_layouts(fd, fdv, 0, 0, SWAP_LAYOUTS_CLOSE);
1305         if (rc < 0) {
1306                 error_loc = "cannot swap layout";
1307                 goto out;
1308         }
1309
1310 out:
1311         if (fd >= 0)
1312                 close(fd);
1313
1314         if (fdv >= 0)
1315                 close(fdv);
1316 out_closed:
1317         if (rc < 0)
1318                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1319                         progname, name, error_loc, strerror(-rc));
1320         else if (migration_flags & MIGRATION_VERBOSE)
1321                 printf("%s\n", name);
1322
1323         return rc;
1324 }
1325
1326 static int comp_str2flags(char *string, __u32 *flags, __u32 *neg_flags)
1327 {
1328         char *name;
1329         char *dup_string = NULL;
1330         int rc = 0;
1331
1332         *flags = 0;
1333         *neg_flags = 0;
1334
1335         if (!string || !string[0])
1336                 return -EINVAL;
1337
1338         dup_string = strdup(string);
1339         if (!dup_string) {
1340                 llapi_printf(LLAPI_MSG_ERROR,
1341                              "%s: insufficient memory\n",
1342                              progname);
1343                 return -ENOMEM;
1344         }
1345
1346         for (name = strtok(dup_string, ","); name; name = strtok(NULL, ",")) {
1347                 bool found = false;
1348                 int i;
1349
1350                 for (i = 0; i < ARRAY_SIZE(comp_flags_table); i++) {
1351                         __u32 comp_flag = comp_flags_table[i].cfn_flag;
1352                         const char *comp_name = comp_flags_table[i].cfn_name;
1353
1354                         if (strcmp(name, comp_name) == 0) {
1355                                 *flags |= comp_flag;
1356                                 found = true;
1357                         } else if (strncmp(name, "^", 1) == 0 &&
1358                                    strcmp(name + 1, comp_name) == 0) {
1359                                 *neg_flags |= comp_flag;
1360                                 found = true;
1361                         }
1362                 }
1363                 if (!found) {
1364                         llapi_printf(LLAPI_MSG_ERROR,
1365                                      "%s: component flag '%s' not supported\n",
1366                                      progname, name);
1367                         rc = -EINVAL;
1368                         goto out_free;
1369                 }
1370         }
1371
1372         if (!*flags && !*neg_flags)
1373                 rc = -EINVAL;
1374
1375         /* don't allow to set and exclude the same flag */
1376         if (*flags & *neg_flags)
1377                 rc = -EINVAL;
1378
1379 out_free:
1380         free(dup_string);
1381         return rc;
1382 }
1383
1384 static int mdthash_input(char *string, __u32 *inflags,
1385                          __u32 *exflags, __u32 *type)
1386 {
1387         char *name;
1388         struct mhf_list {
1389                 char *name;
1390                 __u32 flag;
1391         } mhflist[] = {
1392                 {"migrating", LMV_HASH_FLAG_MIGRATION},
1393                 {"badtype", LMV_HASH_FLAG_BAD_TYPE},
1394                 {"lostlmv", LMV_HASH_FLAG_LOST_LMV},
1395         };
1396
1397         if (string == NULL)
1398                 return -EINVAL;
1399
1400         *inflags = 0;
1401         *exflags = 0;
1402         *type = 0;
1403         for (name = strtok(string, ","); name; name = strtok(NULL, ",")) {
1404                 bool found = false;
1405                 int i;
1406
1407                 for (i = 0; i < ARRAY_SIZE(mhflist); i++) {
1408                         if (strcmp(name, mhflist[i].name) == 0 ||
1409                             name[0] == mhflist[i].name[0]) {
1410                                 *inflags |= mhflist[i].flag;
1411                                 found = true;
1412                         } else if (name[0] == '^' &&
1413                                    (strcmp(name + 1, mhflist[i].name) == 0 ||
1414                                     name[1] == mhflist[i].name[0])) {
1415                                 *exflags |= mhflist[i].flag;
1416                                 found = true;
1417                         }
1418                 }
1419                 if (!found) {
1420                         i = check_hashtype(name);
1421                         if (i > 0) {
1422                                 *type |= 1 << i;
1423                                 continue;
1424                         }
1425                         llapi_printf(LLAPI_MSG_ERROR,
1426                                      "%s: invalid mdt_hash value '%s'\n",
1427                                      progname, name);
1428                         return -EINVAL;
1429                 }
1430         }
1431
1432         /* don't allow to include and exclude the same flag */
1433         if (*inflags & *exflags) {
1434                 llapi_printf(LLAPI_MSG_ERROR,
1435                              "%s: include and exclude same flag '%s'\n",
1436                              progname, string);
1437                 return -EINVAL;
1438         }
1439
1440         return 0;
1441 }
1442
1443 static int mirror_str2state(char *string, __u16 *state, __u16 *neg_state)
1444 {
1445         if (!string)
1446                 return -EINVAL;
1447
1448         *state = 0;
1449         *neg_state = 0;
1450
1451         if (strncmp(string, "^", 1) == 0) {
1452                 *neg_state = llapi_layout_string_flags(string + 1);
1453                 if (*neg_state != 0)
1454                         return 0;
1455         } else {
1456                 *state = llapi_layout_string_flags(string);
1457                 if (*state != 0)
1458                         return 0;
1459         }
1460
1461         llapi_printf(LLAPI_MSG_ERROR,
1462                      "%s: mirrored file state '%s' not supported\n",
1463                      progname, string);
1464         return -EINVAL;
1465 }
1466
1467 /**
1468  * struct mirror_args - Command-line arguments for mirror(s).
1469  * @m_count:  Number of mirrors to be created with this layout.
1470  * @m_flags:  Mirror level flags, only 'prefer' is supported.
1471  * @m_layout: Mirror layout.
1472  * @m_file:   A victim file. Its layout will be split and used as a mirror.
1473  * @m_next:   Point to the next node of the list.
1474  *
1475  * Command-line arguments for mirror(s) will be parsed and stored in
1476  * a linked list that consists of this structure.
1477  */
1478 struct mirror_args {
1479         __u32                   m_count;
1480         __u32                   m_flags;
1481         struct llapi_layout     *m_layout;
1482         const char              *m_file;
1483         struct mirror_args      *m_next;
1484         bool                    m_inherit;
1485 };
1486
1487 /**
1488  * enum mirror_flags - Flags for extending a mirrored file.
1489  * @MF_NO_VERIFY: Indicates not to verify the mirror(s) from victim file(s)
1490  *             in case the victim file(s) contains the same data as the
1491  *             original mirrored file.
1492  * @MF_DESTROY: Indicates to delete the mirror from the mirrored file.
1493  * @MF_COMP_ID: specified component id instead of mirror id
1494  *
1495  * Flags for extending a mirrored file.
1496  */
1497 enum mirror_flags {
1498         MF_NO_VERIFY    = 0x1,
1499         MF_DESTROY      = 0x2,
1500         MF_COMP_ID      = 0x4,
1501         MF_COMP_POOL    = 0x8,
1502 };
1503
1504 /**
1505  * mirror_create_sanity_check() - Check mirror list.
1506  * @list:  A linked list that stores the mirror arguments.
1507  *
1508  * This function does a sanity check on @list for creating
1509  * a mirrored file.
1510  *
1511  * Return: 0 on success or a negative error code on failure.
1512  */
1513 static int mirror_create_sanity_check(const char *fname,
1514                                       struct mirror_args *list,
1515                                       bool check_fname)
1516 {
1517         int rc = 0;
1518         bool has_m_file = false;
1519         bool has_m_layout = false;
1520
1521         if (!list)
1522                 return -EINVAL;
1523
1524         if (fname && check_fname) {
1525                 struct llapi_layout *layout;
1526
1527                 layout = llapi_layout_get_by_path(fname, 0);
1528                 if (!layout) {
1529                         fprintf(stderr,
1530                                 "error: %s: file '%s' couldn't get layout\n",
1531                                 progname, fname);
1532                         return -ENODATA;
1533                 }
1534
1535                 rc = llapi_layout_sanity(layout, fname, false, true);
1536
1537                 llapi_layout_free(layout);
1538
1539                 if (rc) {
1540                         llapi_layout_sanity_perror(rc);
1541                         return rc;
1542                 }
1543         }
1544
1545         while (list) {
1546                 if (list->m_file) {
1547                         has_m_file = true;
1548                         llapi_layout_free(list->m_layout);
1549
1550                         list->m_layout =
1551                                 llapi_layout_get_by_path(list->m_file, 0);
1552                         if (!list->m_layout) {
1553                                 fprintf(stderr,
1554                                         "error: %s: file '%s' has no layout\n",
1555                                         progname, list->m_file);
1556                                 return -ENODATA;
1557                         }
1558                 } else {
1559                         has_m_layout = true;
1560                         if (!list->m_layout) {
1561                                 fprintf(stderr, "error: %s: no mirror layout\n",
1562                                         progname);
1563                                 return -EINVAL;
1564                         }
1565                 }
1566
1567                 rc = llapi_layout_sanity(list->m_layout, fname, false, true);
1568                 if (rc) {
1569                         llapi_layout_sanity_perror(rc);
1570                         return rc;
1571                 }
1572
1573                 list = list->m_next;
1574         }
1575
1576         if (has_m_file && has_m_layout) {
1577                 fprintf(stderr,
1578                         "error: %s: -f <victim_file> option should not be specified with setstripe options\n",
1579                         progname);
1580                 return -EINVAL;
1581         }
1582
1583         return 0;
1584 }
1585
1586 static int mirror_set_flags(struct llapi_layout *layout, void *cbdata)
1587 {
1588         __u32 mirror_flags = *(__u32 *)cbdata;
1589         uint32_t flags;
1590         int rc;
1591
1592         rc = llapi_layout_comp_flags_get(layout, &flags);
1593         if (rc < 0)
1594                 return rc;
1595
1596         if (!flags) {
1597                 rc = llapi_layout_comp_flags_set(layout, mirror_flags);
1598                 if (rc)
1599                         return rc;
1600         }
1601
1602         return LLAPI_LAYOUT_ITER_CONT;
1603 }
1604
1605 /**
1606  * mirror_create() - Create a mirrored file.
1607  * @fname:        The file to be created.
1608  * @mirror_list:  A linked list that stores the mirror arguments.
1609  *
1610  * This function creates a mirrored file @fname with the mirror(s)
1611  * from @mirror_list.
1612  *
1613  * Return: 0 on success or a negative error code on failure.
1614  */
1615 static int mirror_create(char *fname, struct mirror_args *mirror_list)
1616 {
1617         struct llapi_layout *layout = NULL;
1618         struct mirror_args *cur_mirror = NULL;
1619         uint16_t mirror_count = 0;
1620         int i = 0;
1621         int rc = 0;
1622
1623         rc = mirror_create_sanity_check(fname, mirror_list, false);
1624         if (rc)
1625                 return rc;
1626
1627         cur_mirror = mirror_list;
1628         while (cur_mirror) {
1629                 rc = llapi_layout_comp_iterate(cur_mirror->m_layout,
1630                                                mirror_set_flags,
1631                                                &cur_mirror->m_flags);
1632                 if (rc) {
1633                         rc = -errno;
1634                         fprintf(stderr, "%s: failed to set mirror flags\n",
1635                                 progname);
1636                         goto error;
1637                 }
1638
1639                 for (i = 0; i < cur_mirror->m_count; i++) {
1640                         rc = llapi_layout_merge(&layout, cur_mirror->m_layout);
1641                         if (rc) {
1642                                 rc = -errno;
1643                                 fprintf(stderr,
1644                                         "error: %s: merge layout failed: %s\n",
1645                                         progname, strerror(errno));
1646                                 goto error;
1647                         }
1648                 }
1649                 mirror_count += cur_mirror->m_count;
1650                 cur_mirror = cur_mirror->m_next;
1651         }
1652
1653         if (!layout) {
1654                 fprintf(stderr, "error: %s: layout is NULL\n", progname);
1655                 return -EINVAL;
1656         }
1657
1658         rc = llapi_layout_mirror_count_set(layout, mirror_count);
1659         if (rc) {
1660                 rc = -errno;
1661                 fprintf(stderr, "error: %s: set mirror count failed: %s\n",
1662                         progname, strerror(errno));
1663                 goto error;
1664         }
1665
1666         rc = lfs_component_create(fname, O_CREAT | O_WRONLY, 0666,
1667                                   layout);
1668         if (rc >= 0) {
1669                 close(rc);
1670                 rc = 0;
1671         }
1672
1673 error:
1674         llapi_layout_free(layout);
1675         return rc;
1676 }
1677
1678 /**
1679  * Compare files and check lease on @fd.
1680  *
1681  * \retval bytes number of bytes are the same
1682  */
1683 static ssize_t mirror_file_compare(int fd, int fdv)
1684 {
1685         const size_t buflen = 4 * 1024 * 1024; /* 4M */
1686         void *buf;
1687         ssize_t bytes_done = 0;
1688         ssize_t bytes_read = 0;
1689
1690         buf = malloc(buflen * 2);
1691         if (!buf)
1692                 return -ENOMEM;
1693
1694         while (1) {
1695                 if (!llapi_lease_check(fd)) {
1696                         bytes_done = -EBUSY;
1697                         break;
1698                 }
1699
1700                 bytes_read = read(fd, buf, buflen);
1701                 if (bytes_read <= 0)
1702                         break;
1703
1704                 if (bytes_read != read(fdv, buf + buflen, buflen))
1705                         break;
1706
1707                 /*
1708                  * XXX: should compute the checksum on each buffer and then
1709                  * compare checksum to avoid cache collision
1710                  */
1711                 if (memcmp(buf, buf + buflen, bytes_read))
1712                         break;
1713
1714                 bytes_done += bytes_read;
1715         }
1716
1717         free(buf);
1718
1719         return bytes_done;
1720 }
1721
1722 static int mirror_extend_file(const char *fname, const char *victim_file,
1723                               enum mirror_flags mirror_flags)
1724 {
1725         int fd = -1;
1726         int fdv = -1;
1727         struct stat stbuf;
1728         struct stat stbuf_v;
1729         struct ll_ioc_lease *data = NULL;
1730         int rc;
1731
1732         fd = open(fname, O_RDWR);
1733         if (fd < 0) {
1734                 error_loc = "open source file";
1735                 rc = -errno;
1736                 goto out;
1737         }
1738
1739         fdv = open(victim_file, O_RDWR);
1740         if (fdv < 0) {
1741                 error_loc = "open target file";
1742                 rc = -errno;
1743                 goto out;
1744         }
1745
1746         if (fstat(fd, &stbuf) || fstat(fdv, &stbuf_v)) {
1747                 error_loc = "stat source or target file";
1748                 rc = -errno;
1749                 goto out;
1750         }
1751
1752         if (stbuf.st_dev != stbuf_v.st_dev) {
1753                 error_loc = "stat source and target file";
1754                 rc = -EXDEV;
1755                 goto out;
1756         }
1757
1758         /* mirrors should be of the same size */
1759         if (stbuf.st_size != stbuf_v.st_size) {
1760                 error_loc = "file sizes don't match";
1761                 rc = -EINVAL;
1762                 goto out;
1763         }
1764
1765         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1766         if (rc < 0) {
1767                 error_loc = "cannot get lease";
1768                 goto out;
1769         }
1770
1771         if (!(mirror_flags & MF_NO_VERIFY)) {
1772                 ssize_t ret;
1773                 /* mirrors should have the same contents */
1774                 ret = mirror_file_compare(fd, fdv);
1775                 if (ret != stbuf.st_size) {
1776                         error_loc = "file busy or contents don't match";
1777                         rc = ret < 0 ? ret : -EINVAL;
1778                         goto out;
1779                 }
1780         }
1781
1782         /* Get rid of caching pages from clients */
1783         rc = llapi_file_flush(fd);
1784         if (rc < 0) {
1785                 error_loc = "cannot get data version";
1786                 goto out;
1787         }
1788
1789         rc = llapi_file_flush(fdv);
1790         if (rc < 0) {
1791                 error_loc = "cannot get data version";
1792                 goto out;
1793         }
1794
1795         rc = migrate_set_timestamps(fd, &stbuf);
1796         if (rc < 0) {
1797                 error_loc = "cannot set source file timestamp";
1798                 goto out;
1799         }
1800
1801         /* Atomically put lease, merge layouts and close. */
1802         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1803         if (!data) {
1804                 error_loc = "memory allocation";
1805                 goto out;
1806         }
1807         data->lil_mode = LL_LEASE_UNLCK;
1808         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1809         data->lil_count = 1;
1810         data->lil_ids[0] = fdv;
1811         rc = llapi_lease_set(fd, data);
1812         if (rc < 0) {
1813                 error_loc = "cannot merge layout";
1814                 goto out;
1815         } else if (rc == 0) {
1816                 rc = -EBUSY;
1817                 error_loc = "lost lease lock";
1818                 goto out;
1819         }
1820         rc = 0;
1821
1822 out:
1823         if (data)
1824                 free(data);
1825         if (fd >= 0)
1826                 close(fd);
1827         if (fdv >= 0)
1828                 close(fdv);
1829         if (!rc)
1830                 (void) unlink(victim_file);
1831         if (rc < 0)
1832                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1833                         progname, fname, error_loc, strerror(-rc));
1834         return rc;
1835 }
1836
1837 static int mirror_extend_layout(char *name, struct llapi_layout *m_layout,
1838                                 bool inherit, uint32_t flags)
1839 {
1840         struct llapi_layout *f_layout = NULL;
1841         struct ll_ioc_lease *data = NULL;
1842         struct stat st;
1843         int fd = -1;
1844         int fdv = -1;
1845         int rc = 0;
1846
1847         if (inherit) {
1848                 f_layout = llapi_layout_get_by_path(name, 0);
1849                 if (!f_layout) {
1850                         rc = -EINVAL;
1851                         fprintf(stderr, "%s: cannot get layout\n", progname);
1852                         goto out;
1853                 }
1854                 rc = llapi_layout_get_last_init_comp(f_layout);
1855                 if (rc) {
1856                         fprintf(stderr, "%s: cannot get the last init comp\n",
1857                                 progname);
1858                         goto out;
1859                 }
1860                 rc = llapi_layout_mirror_inherit(f_layout, m_layout);
1861                 if (rc) {
1862                         fprintf(stderr,
1863                                 "%s: cannot inherit from the last init comp\n",
1864                                 progname);
1865                         goto out;
1866                 }
1867         }
1868         llapi_layout_comp_flags_set(m_layout, flags);
1869         rc = migrate_open_files(name, MIGRATION_NONDIRECT, NULL, m_layout, &fd,
1870                                 &fdv);
1871         if (rc < 0)
1872                 goto out;
1873
1874         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
1875         if (rc < 0) {
1876                 error_loc = "cannot get lease";
1877                 goto out;
1878         }
1879
1880         rc = fstat(fd, &st);
1881         if (rc < 0) {
1882                 error_loc = "cannot stat source file";
1883                 goto out;
1884         }
1885
1886         rc = migrate_nonblock(fd, fdv);
1887         if (rc < 0) {
1888                 llapi_lease_release(fd);
1889                 goto out;
1890         }
1891
1892         rc = migrate_set_timestamps(fd, &st);
1893         if (rc < 0) {
1894                 error_loc = "cannot set source file timestamp";
1895                 goto out;
1896         }
1897
1898         /* Atomically put lease, merge layouts and close. */
1899         data = calloc(1, offsetof(typeof(*data), lil_ids[1]));
1900         if (!data) {
1901                 error_loc = "memory allocation";
1902                 goto out;
1903         }
1904         data->lil_mode = LL_LEASE_UNLCK;
1905         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
1906         data->lil_count = 1;
1907         data->lil_ids[0] = fdv;
1908         rc = llapi_lease_set(fd, data);
1909         if (rc < 0) {
1910                 error_loc = "cannot merge layout";
1911                 goto out;
1912         } else if (rc == 0) {
1913                 rc = -EBUSY;
1914                 error_loc = "lost lease lock";
1915                 goto out;
1916         }
1917         rc = 0;
1918
1919 out:
1920         if (data)
1921                 free(data);
1922         if (fd >= 0)
1923                 close(fd);
1924         if (fdv >= 0)
1925                 close(fdv);
1926         if (rc < 0)
1927                 fprintf(stderr, "error: %s: %s: %s: %s\n",
1928                         progname, name, error_loc, strerror(-rc));
1929         return rc;
1930 }
1931
1932 static int mirror_extend(char *fname, struct mirror_args *mirror_list,
1933                          enum mirror_flags mirror_flags)
1934 {
1935         int rc = 0;
1936
1937         while (mirror_list) {
1938                 if (mirror_list->m_file) {
1939                         rc = mirror_extend_file(fname, mirror_list->m_file,
1940                                                 mirror_flags);
1941                 } else {
1942                         __u32 mirror_count = mirror_list->m_count;
1943
1944                         while (mirror_count > 0) {
1945                                 rc = mirror_extend_layout(fname,
1946                                                         mirror_list->m_layout,
1947                                                         mirror_list->m_inherit,
1948                                                         mirror_list->m_flags);
1949                                 if (rc)
1950                                         break;
1951
1952                                 --mirror_count;
1953                         }
1954                 }
1955                 if (rc)
1956                         break;
1957
1958                 mirror_list = mirror_list->m_next;
1959         }
1960
1961         return rc;
1962 }
1963
1964 static int find_mirror_id(struct llapi_layout *layout, void *cbdata)
1965 {
1966         uint32_t id;
1967         int rc;
1968
1969         rc = llapi_layout_mirror_id_get(layout, &id);
1970         if (rc < 0)
1971                 return rc;
1972
1973         if ((__u16)id == *(__u16 *)cbdata)
1974                 return LLAPI_LAYOUT_ITER_STOP;
1975
1976         return LLAPI_LAYOUT_ITER_CONT;
1977 }
1978
1979 static int find_comp_id(struct llapi_layout *layout, void *cbdata)
1980 {
1981         uint32_t id;
1982         int rc;
1983
1984         rc = llapi_layout_comp_id_get(layout, &id);
1985         if (rc < 0)
1986                 return rc;
1987
1988         if (id == *(__u32 *)cbdata)
1989                 return LLAPI_LAYOUT_ITER_STOP;
1990
1991         return LLAPI_LAYOUT_ITER_CONT;
1992 }
1993
1994 static int find_mirror_id_by_pool(struct llapi_layout *layout, void *cbdata)
1995 {
1996         char buf[LOV_MAXPOOLNAME + 1];
1997         struct pool_to_id_cbdata *d = (void *)cbdata;
1998         uint32_t id;
1999         int rc;
2000
2001         rc = llapi_layout_pool_name_get(layout, buf, sizeof(buf));
2002         if (rc < 0)
2003                 return rc;
2004         if (strcmp(d->pool, buf))
2005                 return LLAPI_LAYOUT_ITER_CONT;
2006
2007         rc = llapi_layout_mirror_id_get(layout, &id);
2008         if (rc < 0)
2009                 return rc;
2010         d->id = id;
2011
2012         return LLAPI_LAYOUT_ITER_STOP;
2013 }
2014
2015 static int find_comp_id_by_pool(struct llapi_layout *layout, void *cbdata)
2016 {
2017         char buf[LOV_MAXPOOLNAME + 1];
2018         struct pool_to_id_cbdata *d = (void *)cbdata;
2019         uint32_t id;
2020         int rc;
2021
2022         rc = llapi_layout_pool_name_get(layout, buf, sizeof(buf));
2023         if (rc < 0)
2024                 return rc;
2025         if (strcmp(d->pool, buf))
2026                 return LLAPI_LAYOUT_ITER_CONT;
2027
2028         rc = llapi_layout_comp_id_get(layout, &id);
2029         if (rc < 0)
2030                 return rc;
2031         d->id = id;
2032
2033         return LLAPI_LAYOUT_ITER_STOP;
2034 }
2035
2036 struct collect_ids_data {
2037         __u16   *cid_ids;
2038         int     cid_count;
2039         __u16   cid_exclude;
2040 };
2041
2042 static int collect_mirror_id(struct llapi_layout *layout, void *cbdata)
2043 {
2044         struct collect_ids_data *cid = cbdata;
2045         uint32_t id;
2046         int rc;
2047
2048         rc = llapi_layout_mirror_id_get(layout, &id);
2049         if (rc < 0)
2050                 return rc;
2051
2052         if ((__u16)id != cid->cid_exclude) {
2053                 int i;
2054
2055                 for (i = 0; i < cid->cid_count; i++) {
2056                         /* already collected the mirror id */
2057                         if (id == cid->cid_ids[i])
2058                                 return LLAPI_LAYOUT_ITER_CONT;
2059                 }
2060                 cid->cid_ids[cid->cid_count] = id;
2061                 cid->cid_count++;
2062         }
2063
2064         return LLAPI_LAYOUT_ITER_CONT;
2065 }
2066
2067 /**
2068  * last_non_stale_mirror() - Check if a mirror is the last non-stale mirror.
2069  * @mirror_id: Mirror id to be checked.
2070  * @layout:    Mirror component list.
2071  *
2072  * This function checks if a mirror with specified @mirror_id is the last
2073  * non-stale mirror of a layout @layout.
2074  *
2075  * Return: true or false.
2076  */
2077 static inline
2078 bool last_non_stale_mirror(__u16 mirror_id, struct llapi_layout *layout)
2079 {
2080         __u16 mirror_ids[128] = { 0 };
2081         struct collect_ids_data cid = { .cid_ids = mirror_ids,
2082                                         .cid_count = 0,
2083                                         .cid_exclude = mirror_id, };
2084         int i;
2085
2086         llapi_layout_comp_iterate(layout, collect_mirror_id, &cid);
2087
2088         for (i = 0; i < cid.cid_count; i++) {
2089                 struct llapi_resync_comp comp_array[1024] = { { 0 } };
2090                 int comp_size = 0;
2091
2092                 comp_size = llapi_mirror_find_stale(layout, comp_array,
2093                                                     ARRAY_SIZE(comp_array),
2094                                                     &mirror_ids[i], 1);
2095                 if (comp_size == 0)
2096                         return false;
2097         }
2098
2099         return true;
2100 }
2101
2102 static int mirror_split(const char *fname, __u32 id, const char *pool,
2103                         enum mirror_flags mflags, const char *victim_file)
2104 {
2105         struct llapi_layout *layout;
2106         char parent[PATH_MAX];
2107         char victim[PATH_MAX];
2108         int flags = O_CREAT | O_EXCL | O_LOV_DELAY_CREATE | O_NOFOLLOW;
2109         char *ptr;
2110         struct ll_ioc_lease *data;
2111         uint16_t mirror_count;
2112         __u32 mirror_id;
2113         int mdt_index;
2114         int fd, fdv;
2115         bool purge = true; /* delete mirror by setting fdv=fd */
2116         bool is_encrypted;
2117         int rc;
2118
2119         if (victim_file && (strcmp(fname, victim_file) == 0)) {
2120                 fprintf(stderr,
2121                         "error %s: the source file '%s' and -f file are the same\n",
2122                         progname, fname);
2123                 return -EINVAL;
2124         }
2125
2126         /* check fname contains mirror with mirror_id/comp_id */
2127         layout = llapi_layout_get_by_path(fname, 0);
2128         if (!layout) {
2129                 fprintf(stderr,
2130                         "error %s: file '%s' couldn't get layout\n",
2131                         progname, fname);
2132                 return -EINVAL;
2133         }
2134
2135         rc = llapi_layout_sanity(layout, fname, false, true);
2136         if (rc) {
2137                 llapi_layout_sanity_perror(rc);
2138                 goto free_layout;
2139         }
2140
2141         rc = llapi_layout_mirror_count_get(layout, &mirror_count);
2142         if (rc) {
2143                 fprintf(stderr,
2144                         "error %s: file '%s' couldn't get mirror count\n",
2145                         progname, fname);
2146                 goto free_layout;
2147         }
2148         if (mirror_count < 2) {
2149                 fprintf(stderr,
2150                         "error %s: file '%s' has %d component, cannot split\n",
2151                         progname, fname, mirror_count);
2152                 goto free_layout;
2153         }
2154
2155         if (mflags & MF_COMP_POOL) {
2156                 struct pool_to_id_cbdata data = { .pool = pool };
2157
2158                 rc = llapi_layout_comp_iterate(layout, find_mirror_id_by_pool,
2159                                                &data);
2160                 mirror_id = data.id;
2161         } else if (mflags & MF_COMP_ID) {
2162                 rc = llapi_layout_comp_iterate(layout, find_comp_id, &id);
2163                 mirror_id = mirror_id_of(id);
2164         } else {
2165                 rc = llapi_layout_comp_iterate(layout, find_mirror_id, &id);
2166                 mirror_id = id;
2167         }
2168         if (rc < 0) {
2169                 fprintf(stderr, "error %s: failed to iterate layout of '%s'\n",
2170                         progname, fname);
2171                 goto free_layout;
2172         } else if (rc == LLAPI_LAYOUT_ITER_CONT) {
2173                 if (mflags & MF_COMP_POOL) {
2174                         fprintf(stderr,
2175                                 "error %s: file '%s' does not contain mirror with pool '%s'\n",
2176                                 progname, fname, pool);
2177                         goto free_layout;
2178                 } else if (mflags & MF_COMP_ID) {
2179                         fprintf(stderr,
2180                                 "error %s: file '%s' does not contain mirror with comp-id %u\n",
2181                                 progname, fname, id);
2182                         goto free_layout;
2183                 } else {
2184                         fprintf(stderr,
2185                                 "error %s: file '%s' does not contain mirror with id %u\n",
2186                                 progname, fname, id);
2187                         goto free_layout;
2188                 }
2189         }
2190
2191         fd = open(fname, O_RDWR);
2192         if (fd < 0) {
2193                 fprintf(stderr,
2194                         "error %s: open file '%s' failed: %s\n",
2195                         progname, fname, strerror(errno));
2196                 goto free_layout;
2197         }
2198
2199         /* get victim file directory pathname */
2200         if (strlen(fname) > sizeof(parent) - 1) {
2201                 fprintf(stderr, "error %s: file name of '%s' too long\n",
2202                         progname, fname);
2203                 rc = -ERANGE;
2204                 goto close_fd;
2205         }
2206         strncpy(parent, fname, sizeof(parent));
2207         ptr = strrchr(parent, '/');
2208         if (!ptr) {
2209                 if (!getcwd(parent, sizeof(parent))) {
2210                         fprintf(stderr, "error %s: getcwd failed: %s\n",
2211                                 progname, strerror(errno));
2212                         rc = -errno;
2213                         goto close_fd;
2214                 }
2215         } else {
2216                 if (ptr == parent)
2217                         ptr = parent + 1;
2218                 *ptr = '\0';
2219         }
2220
2221         rc = llapi_file_fget_mdtidx(fd, &mdt_index);
2222         if (rc < 0) {
2223                 fprintf(stderr, "%s: cannot get MDT index of '%s'\n",
2224                         progname, fname);
2225                 goto close_fd;
2226         }
2227
2228         rc = llapi_file_is_encrypted(fd);
2229         if (rc < 0) {
2230                 fprintf(stderr, "%s: cannot get flags of '%s': %d\n",
2231                         progname, fname, rc);
2232                 goto close_fd;
2233         }
2234         is_encrypted = rc;
2235
2236 again:
2237         if (!victim_file) {
2238                 /* use a temp file to store the splitted layout */
2239                 if (mflags & MF_DESTROY) {
2240                         char file_path[PATH_MAX];
2241                         unsigned int rnumber;
2242                         int open_flags;
2243
2244                         if (last_non_stale_mirror(mirror_id, layout)) {
2245                                 rc = -EUCLEAN;
2246                                 fprintf(stderr,
2247                                         "%s: cannot destroy the last non-stale mirror of file '%s'\n",
2248                                         progname, fname);
2249                                 goto close_fd;
2250                         }
2251
2252                         if (purge) {
2253                                 /* don't use volatile file for mirror destroy */
2254                                 fdv = fd;
2255                         } else {
2256                                 /**
2257                                  * try the old way to delete mirror using
2258                                  * volatile file.
2259                                  */
2260                                 do {
2261                                         rnumber = random();
2262                                         rc = snprintf(file_path,
2263                                                       sizeof(file_path),
2264                                                       "%s/" LUSTRE_VOLATILE_HDR ":%.4X:%.4X:fd=%.2d",
2265                                                       parent, mdt_index,
2266                                                       rnumber, fd);
2267                                         if (rc < 0 ||
2268                                             rc >= sizeof(file_path)) {
2269                                                 fdv = -ENAMETOOLONG;
2270                                                 break;
2271                                         }
2272
2273                                         open_flags = O_RDWR |
2274                                              (O_LOV_DELAY_CREATE & ~O_ACCMODE) |
2275                                              O_CREAT | O_EXCL | O_NOFOLLOW;
2276                                         fdv = open(file_path, open_flags,
2277                                                    S_IRUSR | S_IWUSR);
2278                                         if (fdv < 0)
2279                                                 rc = -errno;
2280                                 } while (fdv < 0 && rc == -EEXIST);
2281                         }
2282                 } else {
2283                         if (is_encrypted) {
2284                                 rc = -1;
2285                                 fprintf(stderr,
2286                                         "error %s: not permitted on encrypted file '%s': %d\n",
2287                                         progname, fname, rc);
2288                                 goto close_fd;
2289                         }
2290
2291                         snprintf(victim, sizeof(victim), "%s.mirror~%u",
2292                                  fname, mirror_id);
2293                         fdv = open(victim, flags, S_IRUSR | S_IWUSR);
2294                 }
2295         } else {
2296                 /* user specified victim file */
2297                 if (is_encrypted) {
2298                         rc = -1;
2299                         fprintf(stderr,
2300                                 "error %s: not permitted on encrypted file '%s': %d\n",
2301                                 progname, fname, rc);
2302                         goto close_fd;
2303                 }
2304                 fdv = open(victim_file, flags, S_IRUSR | S_IWUSR);
2305         }
2306
2307         if (fdv < 0) {
2308                 fprintf(stderr,
2309                         "error %s: create victim file failed: %s\n",
2310                         progname, strerror(errno));
2311                 goto close_fd;
2312         }
2313
2314         /* get lease lock of fname */
2315         rc = llapi_lease_acquire(fd, LL_LEASE_WRLCK);
2316         if (rc < 0) {
2317                 fprintf(stderr,
2318                         "error %s: cannot get lease of file '%s': %d\n",
2319                         progname, fname, rc);
2320                 goto close_victim;
2321         }
2322
2323         /* Atomatically put lease, split layouts and close. */
2324         data = malloc(offsetof(typeof(*data), lil_ids[2]));
2325         if (!data) {
2326                 rc = -ENOMEM;
2327                 goto close_victim;
2328         }
2329
2330         data->lil_mode = LL_LEASE_UNLCK;
2331         data->lil_flags = LL_LEASE_LAYOUT_SPLIT;
2332         data->lil_count = 2;
2333         data->lil_ids[0] = fdv;
2334         data->lil_ids[1] = mirror_id;
2335         rc = llapi_lease_set(fd, data);
2336         if (rc <= 0) {
2337                 if (rc == -EINVAL && purge) {
2338                         /* could be old MDS which prohibit fd==fdv */
2339                         purge = false;
2340                         goto again;
2341
2342                 }
2343                 if (rc == 0) /* lost lease lock */
2344                         rc = -EBUSY;
2345                 fprintf(stderr,
2346                         "error %s: cannot split '%s': %s\n",
2347                         progname, fname, strerror(-rc));
2348         } else {
2349                 rc = 0;
2350         }
2351         free(data);
2352
2353 close_victim:
2354         if (!purge)
2355                 close(fdv);
2356 close_fd:
2357         close(fd);
2358 free_layout:
2359         llapi_layout_free(layout);
2360         return rc;
2361 }
2362
2363 static inline
2364 int lfs_mirror_resync_file(const char *fname, struct ll_ioc_lease *ioc,
2365                            __u16 *mirror_ids, int ids_nr);
2366
2367 static int lfs_migrate_to_dom(int fd, int fdv, char *name,
2368                               __u64 migration_flags,
2369                               struct llapi_stripe_param *param,
2370                               struct llapi_layout *layout)
2371 {
2372         struct ll_ioc_lease *data = NULL;
2373         int rc;
2374
2375         rc = llapi_lease_acquire(fd, LL_LEASE_RDLCK);
2376         if (rc < 0) {
2377                 error_loc = "cannot get lease";
2378                 goto out_close;
2379         }
2380
2381         /* Atomically put lease, merge layouts, resync and close. */
2382         data = calloc(1, offsetof(typeof(*data), lil_ids[1024]));
2383         if (!data) {
2384                 error_loc = "memory allocation";
2385                 goto out_close;
2386         }
2387         data->lil_mode = LL_LEASE_UNLCK;
2388         data->lil_flags = LL_LEASE_LAYOUT_MERGE;
2389         data->lil_count = 1;
2390         data->lil_ids[0] = fdv;
2391         rc = llapi_lease_set(fd, data);
2392         if (rc < 0) {
2393                 error_loc = "cannot merge layout";
2394                 goto out_close;
2395         } else if (rc == 0) {
2396                 rc = -EBUSY;
2397                 error_loc = "lost lease lock";
2398                 goto out_close;
2399         }
2400         close(fd);
2401         close(fdv);
2402
2403         rc = lfs_mirror_resync_file(name, data, NULL, 0);
2404         if (rc) {
2405                 error_loc = "cannot resync file";
2406                 goto out;
2407         }
2408
2409         /* delete first mirror now */
2410         rc = mirror_split(name, 1, NULL, MF_DESTROY, NULL);
2411         if (rc < 0)
2412                 error_loc = "cannot delete old layout";
2413         goto out;
2414
2415 out_close:
2416         close(fd);
2417         close(fdv);
2418 out:
2419         if (rc < 0)
2420                 fprintf(stderr, "error: %s: %s: %s: %s\n",
2421                         progname, name, error_loc, strerror(-rc));
2422         else if (migration_flags & MIGRATION_VERBOSE)
2423                 printf("%s\n", name);
2424         if (data)
2425                 free(data);
2426         return rc;
2427 }
2428
2429 /**
2430  * Parse a string containing an target index list into an array of integers.
2431  *
2432  * The input string contains a comma delimited list of individual
2433  * indices and ranges, for example "1,2-4,7". Add the indices into the
2434  * \a tgts array and remove duplicates.
2435  *
2436  * \param[out] tgts             array to store indices in
2437  * \param[in] size              size of \a tgts array
2438  * \param[in] offset            starting index in \a tgts
2439  * \param[in] arg               string containing OST index list
2440  * \param[in/out] overstriping  index list may contain duplicates
2441  *
2442  * \retval positive    number of indices in \a tgts
2443  * \retval -EINVAL     unable to parse \a arg
2444  */
2445 static int parse_targets(__u32 *tgts, int size, int offset, char *arg,
2446                          unsigned long long *pattern)
2447 {
2448         int rc;
2449         int nr = offset;
2450         int slots = size - offset;
2451         char *ptr = NULL;
2452         bool overstriped = false;
2453         bool end_of_loop;
2454
2455         if (!arg)
2456                 return -EINVAL;
2457
2458         end_of_loop = false;
2459         while (!end_of_loop) {
2460                 int start_index = 0;
2461                 int end_index = 0;
2462                 int i;
2463                 char *endptr = NULL;
2464
2465                 rc = -EINVAL;
2466
2467                 ptr = strchrnul(arg, ',');
2468
2469                 end_of_loop = *ptr == '\0';
2470                 *ptr = '\0';
2471
2472                 errno = 0;
2473                 start_index = strtol(arg, &endptr, 0);
2474                 if (endptr == arg) /* no data at all */
2475                         break;
2476                 if (errno != 0 || start_index < -1 ||
2477                     (*endptr != '-' && *endptr != '\0'))
2478                         break;
2479
2480                 end_index = start_index;
2481                 if (*endptr == '-') {
2482                         errno = 0;
2483                         end_index = strtol(endptr + 1, &endptr, 0);
2484                         if (errno != 0 || *endptr != '\0' || end_index < -1)
2485                                 break;
2486                         if (end_index < start_index)
2487                                 break;
2488                 }
2489
2490                 for (i = start_index; i <= end_index && slots > 0; i++) {
2491                         int j;
2492
2493                         /* remove duplicate */
2494                         for (j = 0; j < offset; j++) {
2495                                 if (tgts[j] == i && pattern &&
2496                                     *pattern == LLAPI_LAYOUT_OVERSTRIPING)
2497                                         overstriped = true;
2498                                 else if (tgts[j] == i)
2499                                         return -EINVAL;
2500                         }
2501
2502                         j = offset;
2503
2504                         if (j == offset) { /* check complete */
2505                                 tgts[nr++] = i;
2506                                 --slots;
2507                         }
2508                 }
2509
2510                 if (slots == 0 && i < end_index)
2511                         break;
2512
2513                 *ptr = ',';
2514                 arg = ++ptr;
2515                 offset = nr;
2516                 rc = 0;
2517         }
2518         if (!end_of_loop && ptr)
2519                 *ptr = ',';
2520
2521         if (!overstriped && pattern)
2522                 *pattern = LLAPI_LAYOUT_DEFAULT;
2523
2524         return rc < 0 ? rc : nr;
2525 }
2526
2527 struct lfs_setstripe_args {
2528         unsigned long long       lsa_comp_end;
2529         unsigned long long       lsa_stripe_size;
2530         unsigned long long       lsa_extension_size;
2531         long long                lsa_stripe_count;
2532         long long                lsa_stripe_off;
2533         __u32                    lsa_comp_flags;
2534         __u32                    lsa_comp_neg_flags;
2535         unsigned long long       lsa_pattern;
2536         unsigned int             lsa_mirror_count;
2537         int                      lsa_nr_tgts;
2538         bool                     lsa_first_comp;
2539         bool                     lsa_extension_comp;
2540         __u32                   *lsa_tgts;
2541         char                    *lsa_pool_name;
2542 };
2543
2544 static inline void setstripe_args_init(struct lfs_setstripe_args *lsa)
2545 {
2546         unsigned int mirror_count = lsa->lsa_mirror_count;
2547         bool first_comp = lsa->lsa_first_comp;
2548
2549         memset(lsa, 0, sizeof(*lsa));
2550
2551         lsa->lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
2552         lsa->lsa_stripe_count = LLAPI_LAYOUT_DEFAULT;
2553         lsa->lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2554         lsa->lsa_pattern = LLAPI_LAYOUT_RAID0;
2555         lsa->lsa_pool_name = NULL;
2556
2557         lsa->lsa_mirror_count = mirror_count;
2558         lsa->lsa_first_comp = first_comp;
2559 }
2560
2561 /**
2562  * setstripe_args_init_inherit() - Initialize and inherit stripe options.
2563  * @lsa: Stripe options to be initialized and inherited.
2564  *
2565  * This function initializes stripe options in @lsa and inherit
2566  * stripe_size, stripe_count and OST pool_name options.
2567  *
2568  * Return: void.
2569  */
2570 static inline void setstripe_args_init_inherit(struct lfs_setstripe_args *lsa)
2571 {
2572         unsigned long long stripe_size;
2573         long long stripe_count;
2574         char *pool_name = NULL;
2575
2576         stripe_size = lsa->lsa_stripe_size;
2577         stripe_count = lsa->lsa_stripe_count;
2578         pool_name = lsa->lsa_pool_name;
2579
2580         setstripe_args_init(lsa);
2581
2582         lsa->lsa_stripe_size = stripe_size;
2583         lsa->lsa_stripe_count = stripe_count;
2584         lsa->lsa_pool_name = pool_name;
2585 }
2586
2587 static inline bool setstripe_args_specified(struct lfs_setstripe_args *lsa)
2588 {
2589         return (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT ||
2590                 lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT ||
2591                 lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT ||
2592                 lsa->lsa_pattern != LLAPI_LAYOUT_RAID0 ||
2593                 lsa->lsa_comp_end != 0);
2594 }
2595
2596 static int lsa_args_stripe_count_check(struct lfs_setstripe_args *lsa)
2597 {
2598         if (lsa->lsa_nr_tgts) {
2599                 if (lsa->lsa_nr_tgts < 0 ||
2600                     lsa->lsa_nr_tgts >= LOV_MAX_STRIPE_COUNT) {
2601                         fprintf(stderr, "Invalid nr_tgts(%d)\n",
2602                                 lsa->lsa_nr_tgts);
2603                         errno = EINVAL;
2604                         return -1;
2605                 }
2606
2607                 if (lsa->lsa_stripe_count > 0 &&
2608                     lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT &&
2609                     lsa->lsa_stripe_count != LLAPI_LAYOUT_WIDE &&
2610                     lsa->lsa_nr_tgts != lsa->lsa_stripe_count) {
2611                         fprintf(stderr, "stripe_count(%lld) != nr_tgts(%d)\n",
2612                                 lsa->lsa_stripe_count,
2613                                 lsa->lsa_nr_tgts);
2614                         errno = EINVAL;
2615                         return -1;
2616                 }
2617         }
2618
2619         return 0;
2620
2621 }
2622
2623 /**
2624  * comp_args_to_layout() - Create or extend a composite layout.
2625  * @composite:       Pointer to the composite layout.
2626  * @lsa:             Stripe options for the new component.
2627  *
2628  * This function creates or extends a composite layout by adding a new
2629  * component with stripe options from @lsa.
2630  *
2631  * When modified, adjust llapi_stripe_param_verify() if needed as well.
2632  *
2633  * Return: 0 on success or an error code on failure.
2634  */
2635 static int comp_args_to_layout(struct llapi_layout **composite,
2636                                struct lfs_setstripe_args *lsa,
2637                                bool set_extent)
2638 {
2639         struct llapi_layout *layout = *composite;
2640         uint64_t prev_end = 0;
2641         uint64_t size;
2642         int i = 0, rc;
2643
2644 new_comp:
2645         if (!layout) {
2646                 layout = llapi_layout_alloc();
2647                 if (!layout) {
2648                         fprintf(stderr, "Alloc llapi_layout failed. %s\n",
2649                                 strerror(errno));
2650                         errno = ENOMEM;
2651                         return -1;
2652                 }
2653                 *composite = layout;
2654                 lsa->lsa_first_comp = true;
2655         } else {
2656                 uint64_t start;
2657
2658                 /*
2659                  * Get current component extent, current component
2660                  * must be the tail component.
2661                  */
2662                 rc = llapi_layout_comp_extent_get(layout, &start, &prev_end);
2663                 if (rc) {
2664                         fprintf(stderr, "Get comp extent failed. %s\n",
2665                                 strerror(errno));
2666                         return rc;
2667                 }
2668
2669                 if (lsa->lsa_first_comp) {
2670                         prev_end = 0;
2671                         rc = llapi_layout_add_first_comp(layout);
2672                 } else {
2673                         rc = llapi_layout_comp_add(layout);
2674                 }
2675                 if (rc) {
2676                         fprintf(stderr, "Add component failed. %s\n",
2677                                 strerror(errno));
2678                         return rc;
2679                 }
2680         }
2681
2682         rc = llapi_layout_comp_flags_set(layout, lsa->lsa_comp_flags);
2683         if (rc) {
2684                 fprintf(stderr, "Set flags 0x%x failed: %s\n",
2685                         lsa->lsa_comp_flags, strerror(errno));
2686                 return rc;
2687         }
2688
2689         if (set_extent) {
2690                 uint64_t comp_end = lsa->lsa_comp_end;
2691
2692                 /*
2693                  * The extendable component is 0-length, so it can be removed
2694                  * if there is insufficient space to extend it.
2695                  */
2696                 if (lsa->lsa_extension_comp)
2697                         comp_end = prev_end;
2698
2699                 rc = llapi_layout_comp_extent_set(layout, prev_end,
2700                                                   comp_end);
2701                 if (rc) {
2702                         fprintf(stderr, "Set extent [%lu, %lu) failed. %s\n",
2703                                 prev_end, comp_end, strerror(errno));
2704                         return rc;
2705                 }
2706         }
2707         /* reset lsa_first_comp */
2708         lsa->lsa_first_comp = false;
2709
2710         /* Data-on-MDT component setting */
2711         if (lsa->lsa_pattern == LLAPI_LAYOUT_MDT) {
2712                 /* Yaml support */
2713                 if (lsa->lsa_stripe_count == 0)
2714                         lsa->lsa_stripe_count = LLAPI_LAYOUT_DEFAULT;
2715                 if (lsa->lsa_stripe_size == lsa->lsa_comp_end)
2716                         lsa->lsa_stripe_size = LLAPI_LAYOUT_DEFAULT;
2717                 if (lsa->lsa_stripe_off == -1 ||
2718                     lsa->lsa_stripe_off == 0)
2719                         lsa->lsa_stripe_off = LLAPI_LAYOUT_DEFAULT;
2720                 /*
2721                  * In case of Data-on-MDT patterns the only extra option
2722                  * applicable is stripe size option.
2723                  */
2724                 if (lsa->lsa_stripe_count != LLAPI_LAYOUT_DEFAULT) {
2725                         fprintf(stderr,
2726                                 "Option 'stripe-count' can't be specified with Data-on-MDT component: %lld\n",
2727                                 lsa->lsa_stripe_count);
2728                         errno = EINVAL;
2729                         return -1;
2730                 }
2731                 if (lsa->lsa_stripe_size != LLAPI_LAYOUT_DEFAULT &&
2732                     lsa->lsa_stripe_size != lsa->lsa_comp_end - prev_end) {
2733                         fprintf(stderr,
2734                                 "Option 'stripe-size' can't be specified with Data-on-MDT component: %llu\n",
2735                                 lsa->lsa_stripe_size);
2736                         errno = EINVAL;
2737                         return -1;
2738                 }
2739                 if (lsa->lsa_nr_tgts != 0) {
2740                         fprintf(stderr,
2741                                 "Option 'ost-list' can't be specified with Data-on-MDT component: '%i'\n",
2742                                 lsa->lsa_nr_tgts);
2743                         errno = EINVAL;
2744                         return -1;
2745                 }
2746                 if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT) {
2747                         fprintf(stderr,
2748                                 "Option 'stripe-offset' can't be specified with Data-on-MDT component: %lld\n",
2749                                 lsa->lsa_stripe_off);
2750                         errno = EINVAL;
2751                         return -1;
2752                 }
2753                 if (lsa->lsa_pool_name != 0) {
2754                         fprintf(stderr,
2755                                 "Option 'pool' can't be specified with Data-on-MDT component: '%s'\n",
2756                                 lsa->lsa_pool_name);
2757                         errno = EINVAL;
2758                         return -1;
2759                 }
2760
2761                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2762                 if (rc) {
2763                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2764                                 lsa->lsa_pattern,
2765                                 strerror(errno));
2766                         return rc;
2767                 }
2768                 /* Data-on-MDT component has always single stripe up to end */
2769                 lsa->lsa_stripe_size = lsa->lsa_comp_end;
2770         } else if (lsa->lsa_pattern == LLAPI_LAYOUT_OVERSTRIPING) {
2771                 rc = llapi_layout_pattern_set(layout, lsa->lsa_pattern);
2772                 if (rc) {
2773                         fprintf(stderr, "Set stripe pattern %#llx failed. %s\n",
2774                                 lsa->lsa_pattern,
2775                                 strerror(errno));
2776                         return rc;
2777                 }
2778         }
2779
2780         size = lsa->lsa_comp_flags & LCME_FL_EXTENSION ?
2781                 lsa->lsa_extension_size : lsa->lsa_stripe_size;
2782
2783         if (lsa->lsa_comp_flags & LCME_FL_EXTENSION)
2784                 rc = llapi_layout_extension_size_set(layout, size);
2785         else
2786                 rc = llapi_layout_stripe_size_set(layout, size);
2787
2788         if (rc) {
2789                 fprintf(stderr, "Set stripe size %lu failed: %s\n",
2790                         size, strerror(errno));
2791                 return rc;
2792         }
2793
2794         rc = llapi_layout_stripe_count_set(layout, lsa->lsa_stripe_count);
2795         if (rc) {
2796                 fprintf(stderr, "Set stripe count %lld failed: %s\n",
2797                         lsa->lsa_stripe_count, strerror(errno));
2798                 return rc;
2799         }
2800
2801         if (lsa->lsa_pool_name) {
2802                 rc = llapi_layout_pool_name_set(layout, lsa->lsa_pool_name);
2803                 if (rc) {
2804                         fprintf(stderr, "Set pool name: %s failed. %s\n",
2805                                 lsa->lsa_pool_name, strerror(errno));
2806                         return rc;
2807                 }
2808         } else {
2809                 rc = llapi_layout_pool_name_set(layout, "");
2810                 if (rc) {
2811                         fprintf(stderr, "Clear pool name failed: %s\n",
2812                                 strerror(errno));
2813                         return rc;
2814                 }
2815         }
2816
2817         rc = lsa_args_stripe_count_check(lsa);
2818         if (rc)
2819                 return rc;
2820
2821         if (lsa->lsa_nr_tgts > 0) {
2822                 bool found = false;
2823
2824                 for (i = 0; i < lsa->lsa_nr_tgts; i++) {
2825                         rc = llapi_layout_ost_index_set(layout, i,
2826                                                         lsa->lsa_tgts[i]);
2827                         if (rc)
2828                                 break;
2829
2830                         /* Make sure stripe offset is in OST list. */
2831                         if (lsa->lsa_tgts[i] == lsa->lsa_stripe_off)
2832                                 found = true;
2833                 }
2834                 if (!found) {
2835                         fprintf(stderr, "Invalid stripe offset '%lld', not in the target list",
2836                                 lsa->lsa_stripe_off);
2837                         errno = EINVAL;
2838                         return -1;
2839                 }
2840         } else if (lsa->lsa_stripe_off != LLAPI_LAYOUT_DEFAULT &&
2841                    lsa->lsa_stripe_off != -1) {
2842                 rc = llapi_layout_ost_index_set(layout, 0, lsa->lsa_stripe_off);
2843         }
2844         if (rc) {
2845                 fprintf(stderr, "Set ost index %d failed. %s\n",
2846                         i, strerror(errno));
2847                 return rc;
2848         }
2849
2850         /* Create the second, virtual component of extension space */
2851         if (lsa->lsa_extension_comp) {
2852                 lsa->lsa_comp_flags |= LCME_FL_EXTENSION;
2853                 lsa->lsa_extension_comp = false;
2854                 goto new_comp;
2855         }
2856
2857         return rc;
2858 }
2859
2860 static int build_component(struct llapi_layout **layout,
2861                            struct lfs_setstripe_args *lsa, bool set_extent)
2862 {
2863         int rc;
2864
2865         rc = comp_args_to_layout(layout, lsa, set_extent);
2866         if (rc)
2867                 return rc;
2868
2869         if (lsa->lsa_mirror_count > 0) {
2870                 rc = llapi_layout_mirror_count_set(*layout,
2871                                                    lsa->lsa_mirror_count);
2872                 if (rc)
2873                         return rc;
2874
2875                 rc = llapi_layout_flags_set(*layout, LCM_FL_RDONLY);
2876                 if (rc)
2877                         return rc;
2878                 lsa->lsa_mirror_count = 0;
2879         }
2880
2881         return rc;
2882 }
2883
2884 static int build_prev_component(struct llapi_layout **layout,
2885                                 struct lfs_setstripe_args *prev,
2886                                 struct lfs_setstripe_args *lsa,
2887                                 bool set_extent)
2888 {
2889         int extension = lsa->lsa_comp_flags & LCME_FL_EXTENSION;
2890         int rc;
2891
2892         if (prev->lsa_stripe_size) {
2893                 if (extension) {
2894                         prev->lsa_comp_end = lsa->lsa_comp_end;
2895                         prev->lsa_extension_size = lsa->lsa_extension_size;
2896                         prev->lsa_extension_comp = true;
2897                 }
2898
2899                 rc = build_component(layout, prev, true);
2900                 if (rc)
2901                         return rc;
2902         }
2903
2904         /*
2905          * Copy lsa to previous lsa;
2906          * if this is an extension component, make the previous invalid;
2907          */
2908         if (extension)
2909                 prev->lsa_stripe_size = 0;
2910         else
2911                 *prev = *lsa;
2912
2913         return 0;
2914 }
2915
2916 #ifndef LCME_TEMPLATE_FLAGS
2917 #define LCME_TEMPLATE_FLAGS     (LCME_FL_PREF_RW | LCME_FL_NOSYNC | \
2918                                  LCME_FL_EXTENSION)
2919 #endif
2920
2921 static int build_layout_from_yaml_node(struct cYAML *node,
2922                                        struct llapi_layout **layout,
2923                                        struct lfs_setstripe_args *lsa,
2924                                        struct lfs_setstripe_args *prevp)
2925 {
2926         struct lfs_setstripe_args prev = { 0 };
2927         __u32 *osts = lsa->lsa_tgts;
2928         char *string;
2929         int rc = 0;
2930
2931         if (!prevp)
2932                 prevp = &prev;
2933
2934         while (node) {
2935                 string = node->cy_string;
2936
2937                 if (node->cy_type == CYAML_TYPE_OBJECT) {
2938                         /* go deep to sub blocks */
2939                         if (string && !strncmp(string, "component", 9) &&
2940                             strncmp(string, "component0", 10) &&
2941                             strncmp(string, "components", 10)) {
2942                                 rc = build_prev_component(layout, prevp, lsa,
2943                                                           true);
2944                                 if (rc)
2945                                         return rc;
2946
2947                                 /* initialize lsa. */
2948                                 setstripe_args_init(lsa);
2949                                 lsa->lsa_first_comp = false;
2950                                 lsa->lsa_tgts = osts;
2951                         }
2952
2953                         rc = build_layout_from_yaml_node(node->cy_child, layout,
2954                                                          lsa, prevp);
2955                         if (rc)
2956                                 return rc;
2957                 } else {
2958                         if (!node->cy_string)
2959                                 return -EINVAL;
2960
2961                         /* skip leading lmm_ if present, to simplify parsing */
2962                         if (strncmp(string, "lmm_", 4) == 0)
2963                                 string += 4;
2964
2965                         if (node->cy_type == CYAML_TYPE_STRING) {
2966                                 if (!strcmp(string, "lcme_extent.e_end")) {
2967                                         if (!strcmp(node->cy_valuestring, "EOF") ||
2968                                             !strcmp(node->cy_valuestring, "eof"))
2969                                                 lsa->lsa_comp_end = LUSTRE_EOF;
2970                                 } else if (!strcmp(string, "pool")) {
2971                                         lsa->lsa_pool_name = node->cy_valuestring;
2972                                 } else if (!strcmp(string, "pattern")) {
2973                                         if (!strcmp(node->cy_valuestring, "mdt"))
2974                                                 lsa->lsa_pattern = LLAPI_LAYOUT_MDT;
2975                                         if (!strcmp(node->cy_valuestring,
2976                                                     "raid0,overstriped"))
2977                                                 lsa->lsa_pattern =
2978                                                         LLAPI_LAYOUT_OVERSTRIPING;
2979                                 } else if (!strcmp(string, "lcme_flags")) {
2980                                         rc = comp_str2flags(node->cy_valuestring,
2981                                                             &lsa->lsa_comp_flags,
2982                                                             &lsa->lsa_comp_neg_flags);
2983                                         if (rc)
2984                                                 return rc;
2985                                         /*
2986                                          * Only template flags have meaning in
2987                                          * the layout for a new file
2988                                          */
2989                                         lsa->lsa_comp_flags &= LCME_TEMPLATE_FLAGS;
2990                                 }
2991                         } else if (node->cy_type == CYAML_TYPE_NUMBER) {
2992                                 if (!strcmp(string, "lcm_mirror_count")) {
2993                                         lsa->lsa_mirror_count = node->cy_valueint;
2994                                 } else if (!strcmp(string, "lcme_extent.e_start")) {
2995                                         if (node->cy_valueint == 0)
2996                                                 lsa->lsa_first_comp = true;
2997                                 } else if (!strcmp(string, "lcme_extent.e_end")) {
2998                                         if (node->cy_valueint == -1)
2999                                                 lsa->lsa_comp_end = LUSTRE_EOF;
3000                                         else
3001                                                 lsa->lsa_comp_end = node->cy_valueint;
3002                                 } else if (!strcmp(string, "stripe_count")) {
3003                                         lsa->lsa_stripe_count = node->cy_valueint;
3004                                 } else if (!strcmp(string, "stripe_size")) {
3005                                         lsa->lsa_stripe_size = node->cy_valueint;
3006                                 } else if (!strcmp(string, "extension_size")) {
3007                                         lsa->lsa_extension_size = node->cy_valueint;
3008                                         lsa->lsa_extension_comp = true;
3009                                 } else if (!strcmp(string, "stripe_offset")) {
3010                                         lsa->lsa_stripe_off = node->cy_valueint;
3011                                 } else if (!strcmp(string, "l_ost_idx")) {
3012                                         osts[lsa->lsa_nr_tgts] = node->cy_valueint;
3013                                         lsa->lsa_nr_tgts++;
3014                                 }
3015                         }
3016                 }
3017                 node = node->cy_next;
3018         }
3019
3020         if (prevp == &prev) {
3021                 rc = build_prev_component(layout, prevp, lsa, true);
3022                 if (rc)
3023                         return rc;
3024
3025                 if (!(lsa->lsa_comp_flags & LCME_FL_EXTENSION))
3026                         rc = build_component(layout, lsa, *layout != NULL);
3027         }
3028
3029         return rc;
3030 }
3031
3032 static int lfs_comp_create_from_yaml(char *template,
3033                                      struct llapi_layout **layout,
3034                                      struct lfs_setstripe_args *lsa,
3035                                      __u32 *osts)
3036 {
3037         struct cYAML *tree = NULL, *err_rc = NULL;
3038         int rc = 0;
3039
3040         tree = cYAML_build_tree(template, NULL, 0, &err_rc, false);
3041         if (!tree) {
3042                 fprintf(stderr, "%s: cannot parse YAML file %s\n",
3043                         progname, template);
3044                 cYAML_build_error(-EINVAL, -1, "yaml", "from comp yaml",
3045                                   "can't parse", &err_rc);
3046                 cYAML_print_tree2file(stderr, err_rc);
3047                 cYAML_free_tree(err_rc);
3048                 rc = -EINVAL;
3049                 goto err;
3050         }
3051
3052         /* initialize lsa for plain file */
3053         setstripe_args_init(lsa);
3054         lsa->lsa_tgts = osts;
3055
3056         rc = build_layout_from_yaml_node(tree, layout, lsa, NULL);
3057         if (rc) {
3058                 fprintf(stderr, "%s: cannot build layout from YAML file %s.\n",
3059                         progname, template);
3060                 goto err;
3061         }
3062         /* clean clean lsa */
3063         setstripe_args_init(lsa);
3064
3065 err:
3066         if (tree)
3067                 cYAML_free_tree(tree);
3068         return rc;
3069 }
3070
3071 /**
3072  * Get the extension size from the next (SEL) component and extend the
3073  * current component on it. The start of the next component is to be
3074  * adjusted as well.
3075  *
3076  * \param[in] layout    the current layout
3077  * \param[in] start     the start of the current component
3078  * \param[in,out] end   the end of the current component
3079  * \param[in] offset    the offset to adjust the end position to instead of
3080  *                      extension size
3081  *
3082  * \retval 0            - extended successfully
3083  * \retval < 0          - error
3084  */
3085 static int layout_extend_comp(struct llapi_layout *layout,
3086                               uint64_t start, uint64_t *end,
3087                               uint64_t offset)
3088 {
3089         uint64_t size, next_start, next_end;
3090         int rc;
3091
3092         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_NEXT);
3093         if (rc < 0) {
3094                 fprintf(stderr,
3095                         "%s setstripe: cannot move component cursor: %s\n",
3096                         progname, strerror(errno));
3097                 return rc;
3098         }
3099
3100         /*
3101          * Even if the @size will not be used below, this will fail if
3102          * this is not a SEL component - a good confirmation we are
3103          * working on right components.
3104          */
3105         rc = llapi_layout_extension_size_get(layout, &size);
3106         if (rc < 0) {
3107                 fprintf(stderr,
3108                         "%s setstripe: cannot get component ext size: %s\n",
3109                         progname, strerror(errno));
3110                 return rc;
3111         }
3112
3113         rc = llapi_layout_comp_extent_get(layout, &next_start, &next_end);
3114         if (rc) {
3115                 fprintf(stderr, "%s setstripe: cannot get extent: %s\n",
3116                         progname, strerror(errno));
3117                 return rc;
3118         }
3119
3120         next_start += offset ?: size;
3121         rc = llapi_layout_comp_extent_set(layout, next_start, next_end);
3122         if (rc) {
3123                 fprintf(stderr, "%s setstripe: cannot set extent: %s\n",
3124                         progname, strerror(errno));
3125                 return rc;
3126         }
3127
3128         rc = llapi_layout_comp_use(layout, LLAPI_LAYOUT_COMP_USE_PREV);
3129         if (rc < 0) {
3130                 fprintf(stderr,
3131                         "%s setstripe: cannot move component cursor: %s\n",
3132                         progname, strerror(errno));
3133                 return rc;
3134         }
3135
3136         *end += offset ?: size;
3137         rc = llapi_layout_comp_extent_set(layout, start, *end);
3138         if (rc) {
3139                 fprintf(stderr, "%s setstripe: cannot set extent: %s\n",
3140                         progname, strerror(errno));
3141                 return rc;
3142         }
3143
3144         return 0;
3145 }
3146
3147 /**
3148  * In 'lfs setstripe --component-add' mode, we need to fetch the extent
3149  * end of the last component in the existing file, and adjust the
3150  * first extent start of the components to be added accordingly.
3151  *
3152  * In the create mode, we need to check if the first component is an extendable
3153  * SEL component and extend its length to the extension size (first component
3154  * of the PFL file is initialised at the create time, cannot be 0-lenght.
3155  */
3156 static int layout_adjust_first_extent(char *fname, struct llapi_layout *layout,
3157                                       bool comp_add)
3158 {
3159         struct llapi_layout *head;
3160         uint64_t start = 0, prev_end = 0;
3161         uint64_t end;
3162         int rc, ret = 0;
3163
3164         if (!layout || !(comp_add || llapi_layout_is_composite(layout)))
3165                 return 0;
3166
3167         errno = 0;