1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2012 Alexander Block. All rights reserved.
6 #include <linux/bsearch.h>
8 #include <linux/file.h>
9 #include <linux/sort.h>
10 #include <linux/mount.h>
11 #include <linux/xattr.h>
12 #include <linux/posix_acl_xattr.h>
13 #include <linux/radix-tree.h>
14 #include <linux/vmalloc.h>
15 #include <linux/string.h>
16 #include <linux/compat.h>
17 #include <linux/crc32c.h>
23 #include "btrfs_inode.h"
24 #include "transaction.h"
25 #include "compression.h"
27 #include "print-tree.h"
30 * Maximum number of references an extent can have in order for us to attempt to
31 * issue clone operations instead of write operations. This currently exists to
32 * avoid hitting limitations of the backreference walking code (taking a lot of
33 * time and using too much memory for extents with large number of references).
35 #define SEND_MAX_EXTENT_REFS 64
38 * A fs_path is a helper to dynamically build path names with unknown size.
39 * It reallocates the internal buffer on demand.
40 * It allows fast adding of path elements on the right side (normal path) and
41 * fast adding to the left side (reversed path). A reversed path can also be
42 * unreversed if needed.
51 unsigned short buf_len:15;
52 unsigned short reversed:1;
56 * Average path length does not exceed 200 bytes, we'll have
57 * better packing in the slab and higher chance to satisfy
58 * a allocation later during send.
63 #define FS_PATH_INLINE_SIZE \
64 (sizeof(struct fs_path) - offsetof(struct fs_path, inline_buf))
67 /* reused for each extent */
69 struct btrfs_root *root;
76 #define SEND_CTX_MAX_NAME_CACHE_SIZE 128
77 #define SEND_CTX_NAME_CACHE_CLEAN_SIZE (SEND_CTX_MAX_NAME_CACHE_SIZE * 2)
80 struct file *send_filp;
86 u64 cmd_send_size[BTRFS_SEND_C_MAX + 1];
87 u64 flags; /* 'flags' member of btrfs_ioctl_send_args is u64 */
88 /* Protocol version compatibility requested */
91 struct btrfs_root *send_root;
92 struct btrfs_root *parent_root;
93 struct clone_root *clone_roots;
96 /* current state of the compare_tree call */
97 struct btrfs_path *left_path;
98 struct btrfs_path *right_path;
99 struct btrfs_key *cmp_key;
102 * Keep track of the generation of the last transaction that was used
103 * for relocating a block group. This is periodically checked in order
104 * to detect if a relocation happened since the last check, so that we
105 * don't operate on stale extent buffers for nodes (level >= 1) or on
106 * stale disk_bytenr values of file extent items.
108 u64 last_reloc_trans;
111 * infos of the currently processed inode. In case of deleted inodes,
112 * these are the values from the deleted inode.
117 int cur_inode_new_gen;
118 int cur_inode_deleted;
122 u64 cur_inode_last_extent;
123 u64 cur_inode_next_write_offset;
124 bool ignore_cur_inode;
128 struct list_head new_refs;
129 struct list_head deleted_refs;
131 struct radix_tree_root name_cache;
132 struct list_head name_cache_list;
135 struct file_ra_state ra;
138 * We process inodes by their increasing order, so if before an
139 * incremental send we reverse the parent/child relationship of
140 * directories such that a directory with a lower inode number was
141 * the parent of a directory with a higher inode number, and the one
142 * becoming the new parent got renamed too, we can't rename/move the
143 * directory with lower inode number when we finish processing it - we
144 * must process the directory with higher inode number first, then
145 * rename/move it and then rename/move the directory with lower inode
146 * number. Example follows.
148 * Tree state when the first send was performed:
160 * Tree state when the second (incremental) send is performed:
169 * The sequence of steps that lead to the second state was:
171 * mv /a/b/c/d /a/b/c2/d2
172 * mv /a/b/c /a/b/c2/d2/cc
174 * "c" has lower inode number, but we can't move it (2nd mv operation)
175 * before we move "d", which has higher inode number.
177 * So we just memorize which move/rename operations must be performed
178 * later when their respective parent is processed and moved/renamed.
181 /* Indexed by parent directory inode number. */
182 struct rb_root pending_dir_moves;
185 * Reverse index, indexed by the inode number of a directory that
186 * is waiting for the move/rename of its immediate parent before its
187 * own move/rename can be performed.
189 struct rb_root waiting_dir_moves;
192 * A directory that is going to be rm'ed might have a child directory
193 * which is in the pending directory moves index above. In this case,
194 * the directory can only be removed after the move/rename of its child
195 * is performed. Example:
215 * Sequence of steps that lead to the send snapshot:
216 * rm -f /a/b/c/foo.txt
218 * mv /a/b/c/x /a/b/YY
221 * When the child is processed, its move/rename is delayed until its
222 * parent is processed (as explained above), but all other operations
223 * like update utimes, chown, chgrp, etc, are performed and the paths
224 * that it uses for those operations must use the orphanized name of
225 * its parent (the directory we're going to rm later), so we need to
226 * memorize that name.
228 * Indexed by the inode number of the directory to be deleted.
230 struct rb_root orphan_dirs;
233 struct pending_dir_move {
235 struct list_head list;
239 struct list_head update_refs;
242 struct waiting_dir_move {
246 * There might be some directory that could not be removed because it
247 * was waiting for this directory inode to be moved first. Therefore
248 * after this directory is moved, we can try to rmdir the ino rmdir_ino.
255 struct orphan_dir_info {
259 u64 last_dir_index_offset;
262 struct name_cache_entry {
263 struct list_head list;
265 * radix_tree has only 32bit entries but we need to handle 64bit inums.
266 * We use the lower 32bit of the 64bit inum to store it in the tree. If
267 * more then one inum would fall into the same entry, we use radix_list
268 * to store the additional entries. radix_list is also used to store
269 * entries where two entries have the same inum but different
272 struct list_head radix_list;
278 int need_later_update;
284 #define ADVANCE_ONLY_NEXT -1
286 enum btrfs_compare_tree_result {
287 BTRFS_COMPARE_TREE_NEW,
288 BTRFS_COMPARE_TREE_DELETED,
289 BTRFS_COMPARE_TREE_CHANGED,
290 BTRFS_COMPARE_TREE_SAME,
294 static void inconsistent_snapshot_error(struct send_ctx *sctx,
295 enum btrfs_compare_tree_result result,
298 const char *result_string;
301 case BTRFS_COMPARE_TREE_NEW:
302 result_string = "new";
304 case BTRFS_COMPARE_TREE_DELETED:
305 result_string = "deleted";
307 case BTRFS_COMPARE_TREE_CHANGED:
308 result_string = "updated";
310 case BTRFS_COMPARE_TREE_SAME:
312 result_string = "unchanged";
316 result_string = "unexpected";
319 btrfs_err(sctx->send_root->fs_info,
320 "Send: inconsistent snapshot, found %s %s for inode %llu without updated inode item, send root is %llu, parent root is %llu",
321 result_string, what, sctx->cmp_key->objectid,
322 sctx->send_root->root_key.objectid,
324 sctx->parent_root->root_key.objectid : 0));
328 static bool proto_cmd_ok(const struct send_ctx *sctx, int cmd)
330 switch (sctx->proto) {
331 case 1: return cmd < __BTRFS_SEND_C_MAX_V1;
332 case 2: return cmd < __BTRFS_SEND_C_MAX_V2;
333 default: return false;
337 static int is_waiting_for_move(struct send_ctx *sctx, u64 ino);
339 static struct waiting_dir_move *
340 get_waiting_dir_move(struct send_ctx *sctx, u64 ino);
342 static int is_waiting_for_rm(struct send_ctx *sctx, u64 dir_ino, u64 gen);
344 static int need_send_hole(struct send_ctx *sctx)
346 return (sctx->parent_root && !sctx->cur_inode_new &&
347 !sctx->cur_inode_new_gen && !sctx->cur_inode_deleted &&
348 S_ISREG(sctx->cur_inode_mode));
351 static void fs_path_reset(struct fs_path *p)
354 p->start = p->buf + p->buf_len - 1;
364 static struct fs_path *fs_path_alloc(void)
368 p = kmalloc(sizeof(*p), GFP_KERNEL);
372 p->buf = p->inline_buf;
373 p->buf_len = FS_PATH_INLINE_SIZE;
378 static struct fs_path *fs_path_alloc_reversed(void)
390 static void fs_path_free(struct fs_path *p)
394 if (p->buf != p->inline_buf)
399 static int fs_path_len(struct fs_path *p)
401 return p->end - p->start;
404 static int fs_path_ensure_buf(struct fs_path *p, int len)
412 if (p->buf_len >= len)
415 if (len > PATH_MAX) {
420 path_len = p->end - p->start;
421 old_buf_len = p->buf_len;
424 * First time the inline_buf does not suffice
426 if (p->buf == p->inline_buf) {
427 tmp_buf = kmalloc(len, GFP_KERNEL);
429 memcpy(tmp_buf, p->buf, old_buf_len);
431 tmp_buf = krealloc(p->buf, len, GFP_KERNEL);
437 * The real size of the buffer is bigger, this will let the fast path
438 * happen most of the time
440 p->buf_len = ksize(p->buf);
443 tmp_buf = p->buf + old_buf_len - path_len - 1;
444 p->end = p->buf + p->buf_len - 1;
445 p->start = p->end - path_len;
446 memmove(p->start, tmp_buf, path_len + 1);
449 p->end = p->start + path_len;
454 static int fs_path_prepare_for_add(struct fs_path *p, int name_len,
460 new_len = p->end - p->start + name_len;
461 if (p->start != p->end)
463 ret = fs_path_ensure_buf(p, new_len);
468 if (p->start != p->end)
470 p->start -= name_len;
471 *prepared = p->start;
473 if (p->start != p->end)
484 static int fs_path_add(struct fs_path *p, const char *name, int name_len)
489 ret = fs_path_prepare_for_add(p, name_len, &prepared);
492 memcpy(prepared, name, name_len);
498 static int fs_path_add_path(struct fs_path *p, struct fs_path *p2)
503 ret = fs_path_prepare_for_add(p, p2->end - p2->start, &prepared);
506 memcpy(prepared, p2->start, p2->end - p2->start);
512 static int fs_path_add_from_extent_buffer(struct fs_path *p,
513 struct extent_buffer *eb,
514 unsigned long off, int len)
519 ret = fs_path_prepare_for_add(p, len, &prepared);
523 read_extent_buffer(eb, prepared, off, len);
529 static int fs_path_copy(struct fs_path *p, struct fs_path *from)
533 p->reversed = from->reversed;
536 ret = fs_path_add_path(p, from);
542 static void fs_path_unreverse(struct fs_path *p)
551 len = p->end - p->start;
553 p->end = p->start + len;
554 memmove(p->start, tmp, len + 1);
558 static struct btrfs_path *alloc_path_for_send(void)
560 struct btrfs_path *path;
562 path = btrfs_alloc_path();
565 path->search_commit_root = 1;
566 path->skip_locking = 1;
567 path->need_commit_sem = 1;
571 static int write_buf(struct file *filp, const void *buf, u32 len, loff_t *off)
577 ret = kernel_write(filp, buf + pos, len - pos, off);
578 /* TODO handle that correctly */
579 /*if (ret == -ERESTARTSYS) {
593 static int tlv_put(struct send_ctx *sctx, u16 attr, const void *data, int len)
595 struct btrfs_tlv_header *hdr;
596 int total_len = sizeof(*hdr) + len;
597 int left = sctx->send_max_size - sctx->send_size;
599 if (unlikely(left < total_len))
602 hdr = (struct btrfs_tlv_header *) (sctx->send_buf + sctx->send_size);
603 put_unaligned_le16(attr, &hdr->tlv_type);
604 put_unaligned_le16(len, &hdr->tlv_len);
605 memcpy(hdr + 1, data, len);
606 sctx->send_size += total_len;
611 #define TLV_PUT_DEFINE_INT(bits) \
612 static int tlv_put_u##bits(struct send_ctx *sctx, \
613 u##bits attr, u##bits value) \
615 __le##bits __tmp = cpu_to_le##bits(value); \
616 return tlv_put(sctx, attr, &__tmp, sizeof(__tmp)); \
619 TLV_PUT_DEFINE_INT(64)
621 static int tlv_put_string(struct send_ctx *sctx, u16 attr,
622 const char *str, int len)
626 return tlv_put(sctx, attr, str, len);
629 static int tlv_put_uuid(struct send_ctx *sctx, u16 attr,
632 return tlv_put(sctx, attr, uuid, BTRFS_UUID_SIZE);
635 static int tlv_put_btrfs_timespec(struct send_ctx *sctx, u16 attr,
636 struct extent_buffer *eb,
637 struct btrfs_timespec *ts)
639 struct btrfs_timespec bts;
640 read_extent_buffer(eb, &bts, (unsigned long)ts, sizeof(bts));
641 return tlv_put(sctx, attr, &bts, sizeof(bts));
645 #define TLV_PUT(sctx, attrtype, data, attrlen) \
647 ret = tlv_put(sctx, attrtype, data, attrlen); \
649 goto tlv_put_failure; \
652 #define TLV_PUT_INT(sctx, attrtype, bits, value) \
654 ret = tlv_put_u##bits(sctx, attrtype, value); \
656 goto tlv_put_failure; \
659 #define TLV_PUT_U8(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 8, data)
660 #define TLV_PUT_U16(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 16, data)
661 #define TLV_PUT_U32(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 32, data)
662 #define TLV_PUT_U64(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 64, data)
663 #define TLV_PUT_STRING(sctx, attrtype, str, len) \
665 ret = tlv_put_string(sctx, attrtype, str, len); \
667 goto tlv_put_failure; \
669 #define TLV_PUT_PATH(sctx, attrtype, p) \
671 ret = tlv_put_string(sctx, attrtype, p->start, \
672 p->end - p->start); \
674 goto tlv_put_failure; \
676 #define TLV_PUT_UUID(sctx, attrtype, uuid) \
678 ret = tlv_put_uuid(sctx, attrtype, uuid); \
680 goto tlv_put_failure; \
682 #define TLV_PUT_BTRFS_TIMESPEC(sctx, attrtype, eb, ts) \
684 ret = tlv_put_btrfs_timespec(sctx, attrtype, eb, ts); \
686 goto tlv_put_failure; \
689 static int send_header(struct send_ctx *sctx)
691 struct btrfs_stream_header hdr;
693 strcpy(hdr.magic, BTRFS_SEND_STREAM_MAGIC);
694 hdr.version = cpu_to_le32(BTRFS_SEND_STREAM_VERSION);
696 return write_buf(sctx->send_filp, &hdr, sizeof(hdr),
701 * For each command/item we want to send to userspace, we call this function.
703 static int begin_cmd(struct send_ctx *sctx, int cmd)
705 struct btrfs_cmd_header *hdr;
707 if (WARN_ON(!sctx->send_buf))
710 BUG_ON(sctx->send_size);
712 sctx->send_size += sizeof(*hdr);
713 hdr = (struct btrfs_cmd_header *)sctx->send_buf;
714 put_unaligned_le16(cmd, &hdr->cmd);
719 static int send_cmd(struct send_ctx *sctx)
722 struct btrfs_cmd_header *hdr;
725 hdr = (struct btrfs_cmd_header *)sctx->send_buf;
726 put_unaligned_le32(sctx->send_size - sizeof(*hdr), &hdr->len);
727 put_unaligned_le32(0, &hdr->crc);
729 crc = btrfs_crc32c(0, (unsigned char *)sctx->send_buf, sctx->send_size);
730 put_unaligned_le32(crc, &hdr->crc);
732 ret = write_buf(sctx->send_filp, sctx->send_buf, sctx->send_size,
735 sctx->total_send_size += sctx->send_size;
736 sctx->cmd_send_size[get_unaligned_le16(&hdr->cmd)] += sctx->send_size;
743 * Sends a move instruction to user space
745 static int send_rename(struct send_ctx *sctx,
746 struct fs_path *from, struct fs_path *to)
748 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
751 btrfs_debug(fs_info, "send_rename %s -> %s", from->start, to->start);
753 ret = begin_cmd(sctx, BTRFS_SEND_C_RENAME);
757 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, from);
758 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH_TO, to);
760 ret = send_cmd(sctx);
768 * Sends a link instruction to user space
770 static int send_link(struct send_ctx *sctx,
771 struct fs_path *path, struct fs_path *lnk)
773 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
776 btrfs_debug(fs_info, "send_link %s -> %s", path->start, lnk->start);
778 ret = begin_cmd(sctx, BTRFS_SEND_C_LINK);
782 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
783 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH_LINK, lnk);
785 ret = send_cmd(sctx);
793 * Sends an unlink instruction to user space
795 static int send_unlink(struct send_ctx *sctx, struct fs_path *path)
797 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
800 btrfs_debug(fs_info, "send_unlink %s", path->start);
802 ret = begin_cmd(sctx, BTRFS_SEND_C_UNLINK);
806 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
808 ret = send_cmd(sctx);
816 * Sends a rmdir instruction to user space
818 static int send_rmdir(struct send_ctx *sctx, struct fs_path *path)
820 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
823 btrfs_debug(fs_info, "send_rmdir %s", path->start);
825 ret = begin_cmd(sctx, BTRFS_SEND_C_RMDIR);
829 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
831 ret = send_cmd(sctx);
839 * Helper function to retrieve some fields from an inode item.
841 static int __get_inode_info(struct btrfs_root *root, struct btrfs_path *path,
842 u64 ino, u64 *size, u64 *gen, u64 *mode, u64 *uid,
846 struct btrfs_inode_item *ii;
847 struct btrfs_key key;
850 key.type = BTRFS_INODE_ITEM_KEY;
852 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
859 ii = btrfs_item_ptr(path->nodes[0], path->slots[0],
860 struct btrfs_inode_item);
862 *size = btrfs_inode_size(path->nodes[0], ii);
864 *gen = btrfs_inode_generation(path->nodes[0], ii);
866 *mode = btrfs_inode_mode(path->nodes[0], ii);
868 *uid = btrfs_inode_uid(path->nodes[0], ii);
870 *gid = btrfs_inode_gid(path->nodes[0], ii);
872 *rdev = btrfs_inode_rdev(path->nodes[0], ii);
877 static int get_inode_info(struct btrfs_root *root,
878 u64 ino, u64 *size, u64 *gen,
879 u64 *mode, u64 *uid, u64 *gid,
882 struct btrfs_path *path;
885 path = alloc_path_for_send();
888 ret = __get_inode_info(root, path, ino, size, gen, mode, uid, gid,
890 btrfs_free_path(path);
894 typedef int (*iterate_inode_ref_t)(int num, u64 dir, int index,
899 * Helper function to iterate the entries in ONE btrfs_inode_ref or
900 * btrfs_inode_extref.
901 * The iterate callback may return a non zero value to stop iteration. This can
902 * be a negative value for error codes or 1 to simply stop it.
904 * path must point to the INODE_REF or INODE_EXTREF when called.
906 static int iterate_inode_ref(struct btrfs_root *root, struct btrfs_path *path,
907 struct btrfs_key *found_key, int resolve,
908 iterate_inode_ref_t iterate, void *ctx)
910 struct extent_buffer *eb = path->nodes[0];
911 struct btrfs_inode_ref *iref;
912 struct btrfs_inode_extref *extref;
913 struct btrfs_path *tmp_path;
917 int slot = path->slots[0];
924 unsigned long name_off;
925 unsigned long elem_size;
928 p = fs_path_alloc_reversed();
932 tmp_path = alloc_path_for_send();
939 if (found_key->type == BTRFS_INODE_REF_KEY) {
940 ptr = (unsigned long)btrfs_item_ptr(eb, slot,
941 struct btrfs_inode_ref);
942 total = btrfs_item_size(eb, slot);
943 elem_size = sizeof(*iref);
945 ptr = btrfs_item_ptr_offset(eb, slot);
946 total = btrfs_item_size(eb, slot);
947 elem_size = sizeof(*extref);
950 while (cur < total) {
953 if (found_key->type == BTRFS_INODE_REF_KEY) {
954 iref = (struct btrfs_inode_ref *)(ptr + cur);
955 name_len = btrfs_inode_ref_name_len(eb, iref);
956 name_off = (unsigned long)(iref + 1);
957 index = btrfs_inode_ref_index(eb, iref);
958 dir = found_key->offset;
960 extref = (struct btrfs_inode_extref *)(ptr + cur);
961 name_len = btrfs_inode_extref_name_len(eb, extref);
962 name_off = (unsigned long)&extref->name;
963 index = btrfs_inode_extref_index(eb, extref);
964 dir = btrfs_inode_extref_parent(eb, extref);
968 start = btrfs_ref_to_path(root, tmp_path, name_len,
972 ret = PTR_ERR(start);
975 if (start < p->buf) {
976 /* overflow , try again with larger buffer */
977 ret = fs_path_ensure_buf(p,
978 p->buf_len + p->buf - start);
981 start = btrfs_ref_to_path(root, tmp_path,
986 ret = PTR_ERR(start);
989 BUG_ON(start < p->buf);
993 ret = fs_path_add_from_extent_buffer(p, eb, name_off,
999 cur += elem_size + name_len;
1000 ret = iterate(num, dir, index, p, ctx);
1007 btrfs_free_path(tmp_path);
1012 typedef int (*iterate_dir_item_t)(int num, struct btrfs_key *di_key,
1013 const char *name, int name_len,
1014 const char *data, int data_len,
1018 * Helper function to iterate the entries in ONE btrfs_dir_item.
1019 * The iterate callback may return a non zero value to stop iteration. This can
1020 * be a negative value for error codes or 1 to simply stop it.
1022 * path must point to the dir item when called.
1024 static int iterate_dir_item(struct btrfs_root *root, struct btrfs_path *path,
1025 iterate_dir_item_t iterate, void *ctx)
1028 struct extent_buffer *eb;
1029 struct btrfs_dir_item *di;
1030 struct btrfs_key di_key;
1042 * Start with a small buffer (1 page). If later we end up needing more
1043 * space, which can happen for xattrs on a fs with a leaf size greater
1044 * then the page size, attempt to increase the buffer. Typically xattr
1048 buf = kmalloc(buf_len, GFP_KERNEL);
1054 eb = path->nodes[0];
1055 slot = path->slots[0];
1056 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
1059 total = btrfs_item_size(eb, slot);
1062 while (cur < total) {
1063 name_len = btrfs_dir_name_len(eb, di);
1064 data_len = btrfs_dir_data_len(eb, di);
1065 btrfs_dir_item_key_to_cpu(eb, di, &di_key);
1067 if (btrfs_dir_type(eb, di) == BTRFS_FT_XATTR) {
1068 if (name_len > XATTR_NAME_MAX) {
1069 ret = -ENAMETOOLONG;
1072 if (name_len + data_len >
1073 BTRFS_MAX_XATTR_SIZE(root->fs_info)) {
1081 if (name_len + data_len > PATH_MAX) {
1082 ret = -ENAMETOOLONG;
1087 if (name_len + data_len > buf_len) {
1088 buf_len = name_len + data_len;
1089 if (is_vmalloc_addr(buf)) {
1093 char *tmp = krealloc(buf, buf_len,
1094 GFP_KERNEL | __GFP_NOWARN);
1101 buf = kvmalloc(buf_len, GFP_KERNEL);
1109 read_extent_buffer(eb, buf, (unsigned long)(di + 1),
1110 name_len + data_len);
1112 len = sizeof(*di) + name_len + data_len;
1113 di = (struct btrfs_dir_item *)((char *)di + len);
1116 ret = iterate(num, &di_key, buf, name_len, buf + name_len,
1133 static int __copy_first_ref(int num, u64 dir, int index,
1134 struct fs_path *p, void *ctx)
1137 struct fs_path *pt = ctx;
1139 ret = fs_path_copy(pt, p);
1143 /* we want the first only */
1148 * Retrieve the first path of an inode. If an inode has more then one
1149 * ref/hardlink, this is ignored.
1151 static int get_inode_path(struct btrfs_root *root,
1152 u64 ino, struct fs_path *path)
1155 struct btrfs_key key, found_key;
1156 struct btrfs_path *p;
1158 p = alloc_path_for_send();
1162 fs_path_reset(path);
1165 key.type = BTRFS_INODE_REF_KEY;
1168 ret = btrfs_search_slot_for_read(root, &key, p, 1, 0);
1175 btrfs_item_key_to_cpu(p->nodes[0], &found_key, p->slots[0]);
1176 if (found_key.objectid != ino ||
1177 (found_key.type != BTRFS_INODE_REF_KEY &&
1178 found_key.type != BTRFS_INODE_EXTREF_KEY)) {
1183 ret = iterate_inode_ref(root, p, &found_key, 1,
1184 __copy_first_ref, path);
1194 struct backref_ctx {
1195 struct send_ctx *sctx;
1197 /* number of total found references */
1201 * used for clones found in send_root. clones found behind cur_objectid
1202 * and cur_offset are not considered as allowed clones.
1207 /* may be truncated in case it's the last extent in a file */
1210 /* Just to check for bugs in backref resolving */
1214 static int __clone_root_cmp_bsearch(const void *key, const void *elt)
1216 u64 root = (u64)(uintptr_t)key;
1217 const struct clone_root *cr = elt;
1219 if (root < cr->root->root_key.objectid)
1221 if (root > cr->root->root_key.objectid)
1226 static int __clone_root_cmp_sort(const void *e1, const void *e2)
1228 const struct clone_root *cr1 = e1;
1229 const struct clone_root *cr2 = e2;
1231 if (cr1->root->root_key.objectid < cr2->root->root_key.objectid)
1233 if (cr1->root->root_key.objectid > cr2->root->root_key.objectid)
1239 * Called for every backref that is found for the current extent.
1240 * Results are collected in sctx->clone_roots->ino/offset/found_refs
1242 static int __iterate_backrefs(u64 ino, u64 offset, u64 root, void *ctx_)
1244 struct backref_ctx *bctx = ctx_;
1245 struct clone_root *found;
1247 /* First check if the root is in the list of accepted clone sources */
1248 found = bsearch((void *)(uintptr_t)root, bctx->sctx->clone_roots,
1249 bctx->sctx->clone_roots_cnt,
1250 sizeof(struct clone_root),
1251 __clone_root_cmp_bsearch);
1255 if (found->root == bctx->sctx->send_root &&
1256 ino == bctx->cur_objectid &&
1257 offset == bctx->cur_offset) {
1258 bctx->found_itself = 1;
1262 * Make sure we don't consider clones from send_root that are
1263 * behind the current inode/offset.
1265 if (found->root == bctx->sctx->send_root) {
1267 * If the source inode was not yet processed we can't issue a
1268 * clone operation, as the source extent does not exist yet at
1269 * the destination of the stream.
1271 if (ino > bctx->cur_objectid)
1274 * We clone from the inode currently being sent as long as the
1275 * source extent is already processed, otherwise we could try
1276 * to clone from an extent that does not exist yet at the
1277 * destination of the stream.
1279 if (ino == bctx->cur_objectid &&
1280 offset + bctx->extent_len >
1281 bctx->sctx->cur_inode_next_write_offset)
1286 found->found_refs++;
1287 if (ino < found->ino) {
1289 found->offset = offset;
1290 } else if (found->ino == ino) {
1292 * same extent found more then once in the same file.
1294 if (found->offset > offset + bctx->extent_len)
1295 found->offset = offset;
1302 * Given an inode, offset and extent item, it finds a good clone for a clone
1303 * instruction. Returns -ENOENT when none could be found. The function makes
1304 * sure that the returned clone is usable at the point where sending is at the
1305 * moment. This means, that no clones are accepted which lie behind the current
1308 * path must point to the extent item when called.
1310 static int find_extent_clone(struct send_ctx *sctx,
1311 struct btrfs_path *path,
1312 u64 ino, u64 data_offset,
1314 struct clone_root **found)
1316 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
1322 u64 extent_item_pos;
1324 struct btrfs_file_extent_item *fi;
1325 struct extent_buffer *eb = path->nodes[0];
1326 struct backref_ctx backref_ctx = {0};
1327 struct clone_root *cur_clone_root;
1328 struct btrfs_key found_key;
1329 struct btrfs_path *tmp_path;
1330 struct btrfs_extent_item *ei;
1334 tmp_path = alloc_path_for_send();
1338 /* We only use this path under the commit sem */
1339 tmp_path->need_commit_sem = 0;
1341 if (data_offset >= ino_size) {
1343 * There may be extents that lie behind the file's size.
1344 * I at least had this in combination with snapshotting while
1345 * writing large files.
1351 fi = btrfs_item_ptr(eb, path->slots[0],
1352 struct btrfs_file_extent_item);
1353 extent_type = btrfs_file_extent_type(eb, fi);
1354 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1358 compressed = btrfs_file_extent_compression(eb, fi);
1360 num_bytes = btrfs_file_extent_num_bytes(eb, fi);
1361 disk_byte = btrfs_file_extent_disk_bytenr(eb, fi);
1362 if (disk_byte == 0) {
1366 logical = disk_byte + btrfs_file_extent_offset(eb, fi);
1368 down_read(&fs_info->commit_root_sem);
1369 ret = extent_from_logical(fs_info, disk_byte, tmp_path,
1370 &found_key, &flags);
1371 up_read(&fs_info->commit_root_sem);
1375 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
1380 ei = btrfs_item_ptr(tmp_path->nodes[0], tmp_path->slots[0],
1381 struct btrfs_extent_item);
1383 * Backreference walking (iterate_extent_inodes() below) is currently
1384 * too expensive when an extent has a large number of references, both
1385 * in time spent and used memory. So for now just fallback to write
1386 * operations instead of clone operations when an extent has more than
1387 * a certain amount of references.
1389 if (btrfs_extent_refs(tmp_path->nodes[0], ei) > SEND_MAX_EXTENT_REFS) {
1393 btrfs_release_path(tmp_path);
1396 * Setup the clone roots.
1398 for (i = 0; i < sctx->clone_roots_cnt; i++) {
1399 cur_clone_root = sctx->clone_roots + i;
1400 cur_clone_root->ino = (u64)-1;
1401 cur_clone_root->offset = 0;
1402 cur_clone_root->found_refs = 0;
1405 backref_ctx.sctx = sctx;
1406 backref_ctx.found = 0;
1407 backref_ctx.cur_objectid = ino;
1408 backref_ctx.cur_offset = data_offset;
1409 backref_ctx.found_itself = 0;
1410 backref_ctx.extent_len = num_bytes;
1413 * The last extent of a file may be too large due to page alignment.
1414 * We need to adjust extent_len in this case so that the checks in
1415 * __iterate_backrefs work.
1417 if (data_offset + num_bytes >= ino_size)
1418 backref_ctx.extent_len = ino_size - data_offset;
1421 * Now collect all backrefs.
1423 if (compressed == BTRFS_COMPRESS_NONE)
1424 extent_item_pos = logical - found_key.objectid;
1426 extent_item_pos = 0;
1427 ret = iterate_extent_inodes(fs_info, found_key.objectid,
1428 extent_item_pos, 1, __iterate_backrefs,
1429 &backref_ctx, false);
1434 down_read(&fs_info->commit_root_sem);
1435 if (fs_info->last_reloc_trans > sctx->last_reloc_trans) {
1437 * A transaction commit for a transaction in which block group
1438 * relocation was done just happened.
1439 * The disk_bytenr of the file extent item we processed is
1440 * possibly stale, referring to the extent's location before
1441 * relocation. So act as if we haven't found any clone sources
1442 * and fallback to write commands, which will read the correct
1443 * data from the new extent location. Otherwise we will fail
1444 * below because we haven't found our own back reference or we
1445 * could be getting incorrect sources in case the old extent
1446 * was already reallocated after the relocation.
1448 up_read(&fs_info->commit_root_sem);
1452 up_read(&fs_info->commit_root_sem);
1454 if (!backref_ctx.found_itself) {
1455 /* found a bug in backref code? */
1458 "did not find backref in send_root. inode=%llu, offset=%llu, disk_byte=%llu found extent=%llu",
1459 ino, data_offset, disk_byte, found_key.objectid);
1463 btrfs_debug(fs_info,
1464 "find_extent_clone: data_offset=%llu, ino=%llu, num_bytes=%llu, logical=%llu",
1465 data_offset, ino, num_bytes, logical);
1467 if (!backref_ctx.found)
1468 btrfs_debug(fs_info, "no clones found");
1470 cur_clone_root = NULL;
1471 for (i = 0; i < sctx->clone_roots_cnt; i++) {
1472 if (sctx->clone_roots[i].found_refs) {
1473 if (!cur_clone_root)
1474 cur_clone_root = sctx->clone_roots + i;
1475 else if (sctx->clone_roots[i].root == sctx->send_root)
1476 /* prefer clones from send_root over others */
1477 cur_clone_root = sctx->clone_roots + i;
1482 if (cur_clone_root) {
1483 *found = cur_clone_root;
1490 btrfs_free_path(tmp_path);
1494 static int read_symlink(struct btrfs_root *root,
1496 struct fs_path *dest)
1499 struct btrfs_path *path;
1500 struct btrfs_key key;
1501 struct btrfs_file_extent_item *ei;
1507 path = alloc_path_for_send();
1512 key.type = BTRFS_EXTENT_DATA_KEY;
1514 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1519 * An empty symlink inode. Can happen in rare error paths when
1520 * creating a symlink (transaction committed before the inode
1521 * eviction handler removed the symlink inode items and a crash
1522 * happened in between or the subvol was snapshoted in between).
1523 * Print an informative message to dmesg/syslog so that the user
1524 * can delete the symlink.
1526 btrfs_err(root->fs_info,
1527 "Found empty symlink inode %llu at root %llu",
1528 ino, root->root_key.objectid);
1533 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
1534 struct btrfs_file_extent_item);
1535 type = btrfs_file_extent_type(path->nodes[0], ei);
1536 compression = btrfs_file_extent_compression(path->nodes[0], ei);
1537 BUG_ON(type != BTRFS_FILE_EXTENT_INLINE);
1538 BUG_ON(compression);
1540 off = btrfs_file_extent_inline_start(ei);
1541 len = btrfs_file_extent_ram_bytes(path->nodes[0], ei);
1543 ret = fs_path_add_from_extent_buffer(dest, path->nodes[0], off, len);
1546 btrfs_free_path(path);
1551 * Helper function to generate a file name that is unique in the root of
1552 * send_root and parent_root. This is used to generate names for orphan inodes.
1554 static int gen_unique_name(struct send_ctx *sctx,
1556 struct fs_path *dest)
1559 struct btrfs_path *path;
1560 struct btrfs_dir_item *di;
1565 path = alloc_path_for_send();
1570 len = snprintf(tmp, sizeof(tmp), "o%llu-%llu-%llu",
1572 ASSERT(len < sizeof(tmp));
1574 di = btrfs_lookup_dir_item(NULL, sctx->send_root,
1575 path, BTRFS_FIRST_FREE_OBJECTID,
1576 tmp, strlen(tmp), 0);
1577 btrfs_release_path(path);
1583 /* not unique, try again */
1588 if (!sctx->parent_root) {
1594 di = btrfs_lookup_dir_item(NULL, sctx->parent_root,
1595 path, BTRFS_FIRST_FREE_OBJECTID,
1596 tmp, strlen(tmp), 0);
1597 btrfs_release_path(path);
1603 /* not unique, try again */
1611 ret = fs_path_add(dest, tmp, strlen(tmp));
1614 btrfs_free_path(path);
1619 inode_state_no_change,
1620 inode_state_will_create,
1621 inode_state_did_create,
1622 inode_state_will_delete,
1623 inode_state_did_delete,
1626 static int get_cur_inode_state(struct send_ctx *sctx, u64 ino, u64 gen)
1634 ret = get_inode_info(sctx->send_root, ino, NULL, &left_gen, NULL, NULL,
1636 if (ret < 0 && ret != -ENOENT)
1640 if (!sctx->parent_root) {
1641 right_ret = -ENOENT;
1643 ret = get_inode_info(sctx->parent_root, ino, NULL, &right_gen,
1644 NULL, NULL, NULL, NULL);
1645 if (ret < 0 && ret != -ENOENT)
1650 if (!left_ret && !right_ret) {
1651 if (left_gen == gen && right_gen == gen) {
1652 ret = inode_state_no_change;
1653 } else if (left_gen == gen) {
1654 if (ino < sctx->send_progress)
1655 ret = inode_state_did_create;
1657 ret = inode_state_will_create;
1658 } else if (right_gen == gen) {
1659 if (ino < sctx->send_progress)
1660 ret = inode_state_did_delete;
1662 ret = inode_state_will_delete;
1666 } else if (!left_ret) {
1667 if (left_gen == gen) {
1668 if (ino < sctx->send_progress)
1669 ret = inode_state_did_create;
1671 ret = inode_state_will_create;
1675 } else if (!right_ret) {
1676 if (right_gen == gen) {
1677 if (ino < sctx->send_progress)
1678 ret = inode_state_did_delete;
1680 ret = inode_state_will_delete;
1692 static int is_inode_existent(struct send_ctx *sctx, u64 ino, u64 gen)
1696 if (ino == BTRFS_FIRST_FREE_OBJECTID)
1699 ret = get_cur_inode_state(sctx, ino, gen);
1703 if (ret == inode_state_no_change ||
1704 ret == inode_state_did_create ||
1705 ret == inode_state_will_delete)
1715 * Helper function to lookup a dir item in a dir.
1717 static int lookup_dir_item_inode(struct btrfs_root *root,
1718 u64 dir, const char *name, int name_len,
1722 struct btrfs_dir_item *di;
1723 struct btrfs_key key;
1724 struct btrfs_path *path;
1726 path = alloc_path_for_send();
1730 di = btrfs_lookup_dir_item(NULL, root, path,
1731 dir, name, name_len, 0);
1732 if (IS_ERR_OR_NULL(di)) {
1733 ret = di ? PTR_ERR(di) : -ENOENT;
1736 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
1737 if (key.type == BTRFS_ROOT_ITEM_KEY) {
1741 *found_inode = key.objectid;
1744 btrfs_free_path(path);
1749 * Looks up the first btrfs_inode_ref of a given ino. It returns the parent dir,
1750 * generation of the parent dir and the name of the dir entry.
1752 static int get_first_ref(struct btrfs_root *root, u64 ino,
1753 u64 *dir, u64 *dir_gen, struct fs_path *name)
1756 struct btrfs_key key;
1757 struct btrfs_key found_key;
1758 struct btrfs_path *path;
1762 path = alloc_path_for_send();
1767 key.type = BTRFS_INODE_REF_KEY;
1770 ret = btrfs_search_slot_for_read(root, &key, path, 1, 0);
1774 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1776 if (ret || found_key.objectid != ino ||
1777 (found_key.type != BTRFS_INODE_REF_KEY &&
1778 found_key.type != BTRFS_INODE_EXTREF_KEY)) {
1783 if (found_key.type == BTRFS_INODE_REF_KEY) {
1784 struct btrfs_inode_ref *iref;
1785 iref = btrfs_item_ptr(path->nodes[0], path->slots[0],
1786 struct btrfs_inode_ref);
1787 len = btrfs_inode_ref_name_len(path->nodes[0], iref);
1788 ret = fs_path_add_from_extent_buffer(name, path->nodes[0],
1789 (unsigned long)(iref + 1),
1791 parent_dir = found_key.offset;
1793 struct btrfs_inode_extref *extref;
1794 extref = btrfs_item_ptr(path->nodes[0], path->slots[0],
1795 struct btrfs_inode_extref);
1796 len = btrfs_inode_extref_name_len(path->nodes[0], extref);
1797 ret = fs_path_add_from_extent_buffer(name, path->nodes[0],
1798 (unsigned long)&extref->name, len);
1799 parent_dir = btrfs_inode_extref_parent(path->nodes[0], extref);
1803 btrfs_release_path(path);
1806 ret = get_inode_info(root, parent_dir, NULL, dir_gen, NULL,
1815 btrfs_free_path(path);
1819 static int is_first_ref(struct btrfs_root *root,
1821 const char *name, int name_len)
1824 struct fs_path *tmp_name;
1827 tmp_name = fs_path_alloc();
1831 ret = get_first_ref(root, ino, &tmp_dir, NULL, tmp_name);
1835 if (dir != tmp_dir || name_len != fs_path_len(tmp_name)) {
1840 ret = !memcmp(tmp_name->start, name, name_len);
1843 fs_path_free(tmp_name);
1848 * Used by process_recorded_refs to determine if a new ref would overwrite an
1849 * already existing ref. In case it detects an overwrite, it returns the
1850 * inode/gen in who_ino/who_gen.
1851 * When an overwrite is detected, process_recorded_refs does proper orphanizing
1852 * to make sure later references to the overwritten inode are possible.
1853 * Orphanizing is however only required for the first ref of an inode.
1854 * process_recorded_refs does an additional is_first_ref check to see if
1855 * orphanizing is really required.
1857 static int will_overwrite_ref(struct send_ctx *sctx, u64 dir, u64 dir_gen,
1858 const char *name, int name_len,
1859 u64 *who_ino, u64 *who_gen, u64 *who_mode)
1863 u64 other_inode = 0;
1865 if (!sctx->parent_root)
1868 ret = is_inode_existent(sctx, dir, dir_gen);
1873 * If we have a parent root we need to verify that the parent dir was
1874 * not deleted and then re-created, if it was then we have no overwrite
1875 * and we can just unlink this entry.
1877 if (sctx->parent_root && dir != BTRFS_FIRST_FREE_OBJECTID) {
1878 ret = get_inode_info(sctx->parent_root, dir, NULL, &gen, NULL,
1880 if (ret < 0 && ret != -ENOENT)
1890 ret = lookup_dir_item_inode(sctx->parent_root, dir, name, name_len,
1892 if (ret < 0 && ret != -ENOENT)
1900 * Check if the overwritten ref was already processed. If yes, the ref
1901 * was already unlinked/moved, so we can safely assume that we will not
1902 * overwrite anything at this point in time.
1904 if (other_inode > sctx->send_progress ||
1905 is_waiting_for_move(sctx, other_inode)) {
1906 ret = get_inode_info(sctx->parent_root, other_inode, NULL,
1907 who_gen, who_mode, NULL, NULL, NULL);
1912 *who_ino = other_inode;
1922 * Checks if the ref was overwritten by an already processed inode. This is
1923 * used by __get_cur_name_and_parent to find out if the ref was orphanized and
1924 * thus the orphan name needs be used.
1925 * process_recorded_refs also uses it to avoid unlinking of refs that were
1928 static int did_overwrite_ref(struct send_ctx *sctx,
1929 u64 dir, u64 dir_gen,
1930 u64 ino, u64 ino_gen,
1931 const char *name, int name_len)
1937 if (!sctx->parent_root)
1940 ret = is_inode_existent(sctx, dir, dir_gen);
1944 if (dir != BTRFS_FIRST_FREE_OBJECTID) {
1945 ret = get_inode_info(sctx->send_root, dir, NULL, &gen, NULL,
1947 if (ret < 0 && ret != -ENOENT)
1957 /* check if the ref was overwritten by another ref */
1958 ret = lookup_dir_item_inode(sctx->send_root, dir, name, name_len,
1960 if (ret < 0 && ret != -ENOENT)
1963 /* was never and will never be overwritten */
1968 ret = get_inode_info(sctx->send_root, ow_inode, NULL, &gen, NULL, NULL,
1973 if (ow_inode == ino && gen == ino_gen) {
1979 * We know that it is or will be overwritten. Check this now.
1980 * The current inode being processed might have been the one that caused
1981 * inode 'ino' to be orphanized, therefore check if ow_inode matches
1982 * the current inode being processed.
1984 if ((ow_inode < sctx->send_progress) ||
1985 (ino != sctx->cur_ino && ow_inode == sctx->cur_ino &&
1986 gen == sctx->cur_inode_gen))
1996 * Same as did_overwrite_ref, but also checks if it is the first ref of an inode
1997 * that got overwritten. This is used by process_recorded_refs to determine
1998 * if it has to use the path as returned by get_cur_path or the orphan name.
2000 static int did_overwrite_first_ref(struct send_ctx *sctx, u64 ino, u64 gen)
2003 struct fs_path *name = NULL;
2007 if (!sctx->parent_root)
2010 name = fs_path_alloc();
2014 ret = get_first_ref(sctx->parent_root, ino, &dir, &dir_gen, name);
2018 ret = did_overwrite_ref(sctx, dir, dir_gen, ino, gen,
2019 name->start, fs_path_len(name));
2027 * Insert a name cache entry. On 32bit kernels the radix tree index is 32bit,
2028 * so we need to do some special handling in case we have clashes. This function
2029 * takes care of this with the help of name_cache_entry::radix_list.
2030 * In case of error, nce is kfreed.
2032 static int name_cache_insert(struct send_ctx *sctx,
2033 struct name_cache_entry *nce)
2036 struct list_head *nce_head;
2038 nce_head = radix_tree_lookup(&sctx->name_cache,
2039 (unsigned long)nce->ino);
2041 nce_head = kmalloc(sizeof(*nce_head), GFP_KERNEL);
2046 INIT_LIST_HEAD(nce_head);
2048 ret = radix_tree_insert(&sctx->name_cache, nce->ino, nce_head);
2055 list_add_tail(&nce->radix_list, nce_head);
2056 list_add_tail(&nce->list, &sctx->name_cache_list);
2057 sctx->name_cache_size++;
2062 static void name_cache_delete(struct send_ctx *sctx,
2063 struct name_cache_entry *nce)
2065 struct list_head *nce_head;
2067 nce_head = radix_tree_lookup(&sctx->name_cache,
2068 (unsigned long)nce->ino);
2070 btrfs_err(sctx->send_root->fs_info,
2071 "name_cache_delete lookup failed ino %llu cache size %d, leaking memory",
2072 nce->ino, sctx->name_cache_size);
2075 list_del(&nce->radix_list);
2076 list_del(&nce->list);
2077 sctx->name_cache_size--;
2080 * We may not get to the final release of nce_head if the lookup fails
2082 if (nce_head && list_empty(nce_head)) {
2083 radix_tree_delete(&sctx->name_cache, (unsigned long)nce->ino);
2088 static struct name_cache_entry *name_cache_search(struct send_ctx *sctx,
2091 struct list_head *nce_head;
2092 struct name_cache_entry *cur;
2094 nce_head = radix_tree_lookup(&sctx->name_cache, (unsigned long)ino);
2098 list_for_each_entry(cur, nce_head, radix_list) {
2099 if (cur->ino == ino && cur->gen == gen)
2106 * Remove some entries from the beginning of name_cache_list.
2108 static void name_cache_clean_unused(struct send_ctx *sctx)
2110 struct name_cache_entry *nce;
2112 if (sctx->name_cache_size < SEND_CTX_NAME_CACHE_CLEAN_SIZE)
2115 while (sctx->name_cache_size > SEND_CTX_MAX_NAME_CACHE_SIZE) {
2116 nce = list_entry(sctx->name_cache_list.next,
2117 struct name_cache_entry, list);
2118 name_cache_delete(sctx, nce);
2123 static void name_cache_free(struct send_ctx *sctx)
2125 struct name_cache_entry *nce;
2127 while (!list_empty(&sctx->name_cache_list)) {
2128 nce = list_entry(sctx->name_cache_list.next,
2129 struct name_cache_entry, list);
2130 name_cache_delete(sctx, nce);
2136 * Used by get_cur_path for each ref up to the root.
2137 * Returns 0 if it succeeded.
2138 * Returns 1 if the inode is not existent or got overwritten. In that case, the
2139 * name is an orphan name. This instructs get_cur_path to stop iterating. If 1
2140 * is returned, parent_ino/parent_gen are not guaranteed to be valid.
2141 * Returns <0 in case of error.
2143 static int __get_cur_name_and_parent(struct send_ctx *sctx,
2147 struct fs_path *dest)
2151 struct name_cache_entry *nce = NULL;
2154 * First check if we already did a call to this function with the same
2155 * ino/gen. If yes, check if the cache entry is still up-to-date. If yes
2156 * return the cached result.
2158 nce = name_cache_search(sctx, ino, gen);
2160 if (ino < sctx->send_progress && nce->need_later_update) {
2161 name_cache_delete(sctx, nce);
2166 * Removes the entry from the list and adds it back to
2167 * the end. This marks the entry as recently used so
2168 * that name_cache_clean_unused does not remove it.
2170 list_move_tail(&nce->list, &sctx->name_cache_list);
2172 *parent_ino = nce->parent_ino;
2173 *parent_gen = nce->parent_gen;
2174 ret = fs_path_add(dest, nce->name, nce->name_len);
2183 * If the inode is not existent yet, add the orphan name and return 1.
2184 * This should only happen for the parent dir that we determine in
2187 ret = is_inode_existent(sctx, ino, gen);
2192 ret = gen_unique_name(sctx, ino, gen, dest);
2200 * Depending on whether the inode was already processed or not, use
2201 * send_root or parent_root for ref lookup.
2203 if (ino < sctx->send_progress)
2204 ret = get_first_ref(sctx->send_root, ino,
2205 parent_ino, parent_gen, dest);
2207 ret = get_first_ref(sctx->parent_root, ino,
2208 parent_ino, parent_gen, dest);
2213 * Check if the ref was overwritten by an inode's ref that was processed
2214 * earlier. If yes, treat as orphan and return 1.
2216 ret = did_overwrite_ref(sctx, *parent_ino, *parent_gen, ino, gen,
2217 dest->start, dest->end - dest->start);
2221 fs_path_reset(dest);
2222 ret = gen_unique_name(sctx, ino, gen, dest);
2230 * Store the result of the lookup in the name cache.
2232 nce = kmalloc(sizeof(*nce) + fs_path_len(dest) + 1, GFP_KERNEL);
2240 nce->parent_ino = *parent_ino;
2241 nce->parent_gen = *parent_gen;
2242 nce->name_len = fs_path_len(dest);
2244 strcpy(nce->name, dest->start);
2246 if (ino < sctx->send_progress)
2247 nce->need_later_update = 0;
2249 nce->need_later_update = 1;
2251 nce_ret = name_cache_insert(sctx, nce);
2254 name_cache_clean_unused(sctx);
2261 * Magic happens here. This function returns the first ref to an inode as it
2262 * would look like while receiving the stream at this point in time.
2263 * We walk the path up to the root. For every inode in between, we check if it
2264 * was already processed/sent. If yes, we continue with the parent as found
2265 * in send_root. If not, we continue with the parent as found in parent_root.
2266 * If we encounter an inode that was deleted at this point in time, we use the
2267 * inodes "orphan" name instead of the real name and stop. Same with new inodes
2268 * that were not created yet and overwritten inodes/refs.
2270 * When do we have orphan inodes:
2271 * 1. When an inode is freshly created and thus no valid refs are available yet
2272 * 2. When a directory lost all it's refs (deleted) but still has dir items
2273 * inside which were not processed yet (pending for move/delete). If anyone
2274 * tried to get the path to the dir items, it would get a path inside that
2276 * 3. When an inode is moved around or gets new links, it may overwrite the ref
2277 * of an unprocessed inode. If in that case the first ref would be
2278 * overwritten, the overwritten inode gets "orphanized". Later when we
2279 * process this overwritten inode, it is restored at a new place by moving
2282 * sctx->send_progress tells this function at which point in time receiving
2285 static int get_cur_path(struct send_ctx *sctx, u64 ino, u64 gen,
2286 struct fs_path *dest)
2289 struct fs_path *name = NULL;
2290 u64 parent_inode = 0;
2294 name = fs_path_alloc();
2301 fs_path_reset(dest);
2303 while (!stop && ino != BTRFS_FIRST_FREE_OBJECTID) {
2304 struct waiting_dir_move *wdm;
2306 fs_path_reset(name);
2308 if (is_waiting_for_rm(sctx, ino, gen)) {
2309 ret = gen_unique_name(sctx, ino, gen, name);
2312 ret = fs_path_add_path(dest, name);
2316 wdm = get_waiting_dir_move(sctx, ino);
2317 if (wdm && wdm->orphanized) {
2318 ret = gen_unique_name(sctx, ino, gen, name);
2321 ret = get_first_ref(sctx->parent_root, ino,
2322 &parent_inode, &parent_gen, name);
2324 ret = __get_cur_name_and_parent(sctx, ino, gen,
2334 ret = fs_path_add_path(dest, name);
2345 fs_path_unreverse(dest);
2350 * Sends a BTRFS_SEND_C_SUBVOL command/item to userspace
2352 static int send_subvol_begin(struct send_ctx *sctx)
2355 struct btrfs_root *send_root = sctx->send_root;
2356 struct btrfs_root *parent_root = sctx->parent_root;
2357 struct btrfs_path *path;
2358 struct btrfs_key key;
2359 struct btrfs_root_ref *ref;
2360 struct extent_buffer *leaf;
2364 path = btrfs_alloc_path();
2368 name = kmalloc(BTRFS_PATH_NAME_MAX, GFP_KERNEL);
2370 btrfs_free_path(path);
2374 key.objectid = send_root->root_key.objectid;
2375 key.type = BTRFS_ROOT_BACKREF_KEY;
2378 ret = btrfs_search_slot_for_read(send_root->fs_info->tree_root,
2387 leaf = path->nodes[0];
2388 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2389 if (key.type != BTRFS_ROOT_BACKREF_KEY ||
2390 key.objectid != send_root->root_key.objectid) {
2394 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
2395 namelen = btrfs_root_ref_name_len(leaf, ref);
2396 read_extent_buffer(leaf, name, (unsigned long)(ref + 1), namelen);
2397 btrfs_release_path(path);
2400 ret = begin_cmd(sctx, BTRFS_SEND_C_SNAPSHOT);
2404 ret = begin_cmd(sctx, BTRFS_SEND_C_SUBVOL);
2409 TLV_PUT_STRING(sctx, BTRFS_SEND_A_PATH, name, namelen);
2411 if (!btrfs_is_empty_uuid(sctx->send_root->root_item.received_uuid))
2412 TLV_PUT_UUID(sctx, BTRFS_SEND_A_UUID,
2413 sctx->send_root->root_item.received_uuid);
2415 TLV_PUT_UUID(sctx, BTRFS_SEND_A_UUID,
2416 sctx->send_root->root_item.uuid);
2418 TLV_PUT_U64(sctx, BTRFS_SEND_A_CTRANSID,
2419 btrfs_root_ctransid(&sctx->send_root->root_item));
2421 if (!btrfs_is_empty_uuid(parent_root->root_item.received_uuid))
2422 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
2423 parent_root->root_item.received_uuid);
2425 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
2426 parent_root->root_item.uuid);
2427 TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_CTRANSID,
2428 btrfs_root_ctransid(&sctx->parent_root->root_item));
2431 ret = send_cmd(sctx);
2435 btrfs_free_path(path);
2440 static int send_truncate(struct send_ctx *sctx, u64 ino, u64 gen, u64 size)
2442 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2446 btrfs_debug(fs_info, "send_truncate %llu size=%llu", ino, size);
2448 p = fs_path_alloc();
2452 ret = begin_cmd(sctx, BTRFS_SEND_C_TRUNCATE);
2456 ret = get_cur_path(sctx, ino, gen, p);
2459 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2460 TLV_PUT_U64(sctx, BTRFS_SEND_A_SIZE, size);
2462 ret = send_cmd(sctx);
2470 static int send_chmod(struct send_ctx *sctx, u64 ino, u64 gen, u64 mode)
2472 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2476 btrfs_debug(fs_info, "send_chmod %llu mode=%llu", ino, mode);
2478 p = fs_path_alloc();
2482 ret = begin_cmd(sctx, BTRFS_SEND_C_CHMOD);
2486 ret = get_cur_path(sctx, ino, gen, p);
2489 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2490 TLV_PUT_U64(sctx, BTRFS_SEND_A_MODE, mode & 07777);
2492 ret = send_cmd(sctx);
2500 static int send_chown(struct send_ctx *sctx, u64 ino, u64 gen, u64 uid, u64 gid)
2502 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2506 btrfs_debug(fs_info, "send_chown %llu uid=%llu, gid=%llu",
2509 p = fs_path_alloc();
2513 ret = begin_cmd(sctx, BTRFS_SEND_C_CHOWN);
2517 ret = get_cur_path(sctx, ino, gen, p);
2520 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2521 TLV_PUT_U64(sctx, BTRFS_SEND_A_UID, uid);
2522 TLV_PUT_U64(sctx, BTRFS_SEND_A_GID, gid);
2524 ret = send_cmd(sctx);
2532 static int send_utimes(struct send_ctx *sctx, u64 ino, u64 gen)
2534 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2536 struct fs_path *p = NULL;
2537 struct btrfs_inode_item *ii;
2538 struct btrfs_path *path = NULL;
2539 struct extent_buffer *eb;
2540 struct btrfs_key key;
2543 btrfs_debug(fs_info, "send_utimes %llu", ino);
2545 p = fs_path_alloc();
2549 path = alloc_path_for_send();
2556 key.type = BTRFS_INODE_ITEM_KEY;
2558 ret = btrfs_search_slot(NULL, sctx->send_root, &key, path, 0, 0);
2564 eb = path->nodes[0];
2565 slot = path->slots[0];
2566 ii = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
2568 ret = begin_cmd(sctx, BTRFS_SEND_C_UTIMES);
2572 ret = get_cur_path(sctx, ino, gen, p);
2575 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2576 TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_ATIME, eb, &ii->atime);
2577 TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_MTIME, eb, &ii->mtime);
2578 TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_CTIME, eb, &ii->ctime);
2579 /* TODO Add otime support when the otime patches get into upstream */
2581 ret = send_cmd(sctx);
2586 btrfs_free_path(path);
2591 * Sends a BTRFS_SEND_C_MKXXX or SYMLINK command to user space. We don't have
2592 * a valid path yet because we did not process the refs yet. So, the inode
2593 * is created as orphan.
2595 static int send_create_inode(struct send_ctx *sctx, u64 ino)
2597 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2605 btrfs_debug(fs_info, "send_create_inode %llu", ino);
2607 p = fs_path_alloc();
2611 if (ino != sctx->cur_ino) {
2612 ret = get_inode_info(sctx->send_root, ino, NULL, &gen, &mode,
2617 gen = sctx->cur_inode_gen;
2618 mode = sctx->cur_inode_mode;
2619 rdev = sctx->cur_inode_rdev;
2622 if (S_ISREG(mode)) {
2623 cmd = BTRFS_SEND_C_MKFILE;
2624 } else if (S_ISDIR(mode)) {
2625 cmd = BTRFS_SEND_C_MKDIR;
2626 } else if (S_ISLNK(mode)) {
2627 cmd = BTRFS_SEND_C_SYMLINK;
2628 } else if (S_ISCHR(mode) || S_ISBLK(mode)) {
2629 cmd = BTRFS_SEND_C_MKNOD;
2630 } else if (S_ISFIFO(mode)) {
2631 cmd = BTRFS_SEND_C_MKFIFO;
2632 } else if (S_ISSOCK(mode)) {
2633 cmd = BTRFS_SEND_C_MKSOCK;
2635 btrfs_warn(sctx->send_root->fs_info, "unexpected inode type %o",
2636 (int)(mode & S_IFMT));
2641 ret = begin_cmd(sctx, cmd);
2645 ret = gen_unique_name(sctx, ino, gen, p);
2649 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2650 TLV_PUT_U64(sctx, BTRFS_SEND_A_INO, ino);
2652 if (S_ISLNK(mode)) {
2654 ret = read_symlink(sctx->send_root, ino, p);
2657 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH_LINK, p);
2658 } else if (S_ISCHR(mode) || S_ISBLK(mode) ||
2659 S_ISFIFO(mode) || S_ISSOCK(mode)) {
2660 TLV_PUT_U64(sctx, BTRFS_SEND_A_RDEV, new_encode_dev(rdev));
2661 TLV_PUT_U64(sctx, BTRFS_SEND_A_MODE, mode);
2664 ret = send_cmd(sctx);
2676 * We need some special handling for inodes that get processed before the parent
2677 * directory got created. See process_recorded_refs for details.
2678 * This function does the check if we already created the dir out of order.
2680 static int did_create_dir(struct send_ctx *sctx, u64 dir)
2683 struct btrfs_path *path = NULL;
2684 struct btrfs_key key;
2685 struct btrfs_key found_key;
2686 struct btrfs_key di_key;
2687 struct extent_buffer *eb;
2688 struct btrfs_dir_item *di;
2691 path = alloc_path_for_send();
2698 key.type = BTRFS_DIR_INDEX_KEY;
2700 ret = btrfs_search_slot(NULL, sctx->send_root, &key, path, 0, 0);
2705 eb = path->nodes[0];
2706 slot = path->slots[0];
2707 if (slot >= btrfs_header_nritems(eb)) {
2708 ret = btrfs_next_leaf(sctx->send_root, path);
2711 } else if (ret > 0) {
2718 btrfs_item_key_to_cpu(eb, &found_key, slot);
2719 if (found_key.objectid != key.objectid ||
2720 found_key.type != key.type) {
2725 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
2726 btrfs_dir_item_key_to_cpu(eb, di, &di_key);
2728 if (di_key.type != BTRFS_ROOT_ITEM_KEY &&
2729 di_key.objectid < sctx->send_progress) {
2738 btrfs_free_path(path);
2743 * Only creates the inode if it is:
2744 * 1. Not a directory
2745 * 2. Or a directory which was not created already due to out of order
2746 * directories. See did_create_dir and process_recorded_refs for details.
2748 static int send_create_inode_if_needed(struct send_ctx *sctx)
2752 if (S_ISDIR(sctx->cur_inode_mode)) {
2753 ret = did_create_dir(sctx, sctx->cur_ino);
2760 return send_create_inode(sctx, sctx->cur_ino);
2763 struct recorded_ref {
2764 struct list_head list;
2766 struct fs_path *full_path;
2772 static void set_ref_path(struct recorded_ref *ref, struct fs_path *path)
2774 ref->full_path = path;
2775 ref->name = (char *)kbasename(ref->full_path->start);
2776 ref->name_len = ref->full_path->end - ref->name;
2780 * We need to process new refs before deleted refs, but compare_tree gives us
2781 * everything mixed. So we first record all refs and later process them.
2782 * This function is a helper to record one ref.
2784 static int __record_ref(struct list_head *head, u64 dir,
2785 u64 dir_gen, struct fs_path *path)
2787 struct recorded_ref *ref;
2789 ref = kmalloc(sizeof(*ref), GFP_KERNEL);
2794 ref->dir_gen = dir_gen;
2795 set_ref_path(ref, path);
2796 list_add_tail(&ref->list, head);
2800 static int dup_ref(struct recorded_ref *ref, struct list_head *list)
2802 struct recorded_ref *new;
2804 new = kmalloc(sizeof(*ref), GFP_KERNEL);
2808 new->dir = ref->dir;
2809 new->dir_gen = ref->dir_gen;
2810 new->full_path = NULL;
2811 INIT_LIST_HEAD(&new->list);
2812 list_add_tail(&new->list, list);
2816 static void __free_recorded_refs(struct list_head *head)
2818 struct recorded_ref *cur;
2820 while (!list_empty(head)) {
2821 cur = list_entry(head->next, struct recorded_ref, list);
2822 fs_path_free(cur->full_path);
2823 list_del(&cur->list);
2828 static void free_recorded_refs(struct send_ctx *sctx)
2830 __free_recorded_refs(&sctx->new_refs);
2831 __free_recorded_refs(&sctx->deleted_refs);
2835 * Renames/moves a file/dir to its orphan name. Used when the first
2836 * ref of an unprocessed inode gets overwritten and for all non empty
2839 static int orphanize_inode(struct send_ctx *sctx, u64 ino, u64 gen,
2840 struct fs_path *path)
2843 struct fs_path *orphan;
2845 orphan = fs_path_alloc();
2849 ret = gen_unique_name(sctx, ino, gen, orphan);
2853 ret = send_rename(sctx, path, orphan);
2856 fs_path_free(orphan);
2860 static struct orphan_dir_info *add_orphan_dir_info(struct send_ctx *sctx,
2861 u64 dir_ino, u64 dir_gen)
2863 struct rb_node **p = &sctx->orphan_dirs.rb_node;
2864 struct rb_node *parent = NULL;
2865 struct orphan_dir_info *entry, *odi;
2869 entry = rb_entry(parent, struct orphan_dir_info, node);
2870 if (dir_ino < entry->ino)
2872 else if (dir_ino > entry->ino)
2873 p = &(*p)->rb_right;
2874 else if (dir_gen < entry->gen)
2876 else if (dir_gen > entry->gen)
2877 p = &(*p)->rb_right;
2882 odi = kmalloc(sizeof(*odi), GFP_KERNEL);
2884 return ERR_PTR(-ENOMEM);
2887 odi->last_dir_index_offset = 0;
2889 rb_link_node(&odi->node, parent, p);
2890 rb_insert_color(&odi->node, &sctx->orphan_dirs);
2894 static struct orphan_dir_info *get_orphan_dir_info(struct send_ctx *sctx,
2895 u64 dir_ino, u64 gen)
2897 struct rb_node *n = sctx->orphan_dirs.rb_node;
2898 struct orphan_dir_info *entry;
2901 entry = rb_entry(n, struct orphan_dir_info, node);
2902 if (dir_ino < entry->ino)
2904 else if (dir_ino > entry->ino)
2906 else if (gen < entry->gen)
2908 else if (gen > entry->gen)
2916 static int is_waiting_for_rm(struct send_ctx *sctx, u64 dir_ino, u64 gen)
2918 struct orphan_dir_info *odi = get_orphan_dir_info(sctx, dir_ino, gen);
2923 static void free_orphan_dir_info(struct send_ctx *sctx,
2924 struct orphan_dir_info *odi)
2928 rb_erase(&odi->node, &sctx->orphan_dirs);
2933 * Returns 1 if a directory can be removed at this point in time.
2934 * We check this by iterating all dir items and checking if the inode behind
2935 * the dir item was already processed.
2937 static int can_rmdir(struct send_ctx *sctx, u64 dir, u64 dir_gen,
2941 struct btrfs_root *root = sctx->parent_root;
2942 struct btrfs_path *path;
2943 struct btrfs_key key;
2944 struct btrfs_key found_key;
2945 struct btrfs_key loc;
2946 struct btrfs_dir_item *di;
2947 struct orphan_dir_info *odi = NULL;
2950 * Don't try to rmdir the top/root subvolume dir.
2952 if (dir == BTRFS_FIRST_FREE_OBJECTID)
2955 path = alloc_path_for_send();
2960 key.type = BTRFS_DIR_INDEX_KEY;
2963 odi = get_orphan_dir_info(sctx, dir, dir_gen);
2965 key.offset = odi->last_dir_index_offset;
2967 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2972 struct waiting_dir_move *dm;
2974 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2975 ret = btrfs_next_leaf(root, path);
2982 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2984 if (found_key.objectid != key.objectid ||
2985 found_key.type != key.type)
2988 di = btrfs_item_ptr(path->nodes[0], path->slots[0],
2989 struct btrfs_dir_item);
2990 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &loc);
2992 dm = get_waiting_dir_move(sctx, loc.objectid);
2994 odi = add_orphan_dir_info(sctx, dir, dir_gen);
3000 odi->last_dir_index_offset = found_key.offset;
3001 dm->rmdir_ino = dir;
3002 dm->rmdir_gen = dir_gen;
3007 if (loc.objectid > send_progress) {
3008 odi = add_orphan_dir_info(sctx, dir, dir_gen);
3014 odi->last_dir_index_offset = found_key.offset;
3021 free_orphan_dir_info(sctx, odi);
3026 btrfs_free_path(path);
3030 static int is_waiting_for_move(struct send_ctx *sctx, u64 ino)
3032 struct waiting_dir_move *entry = get_waiting_dir_move(sctx, ino);
3034 return entry != NULL;
3037 static int add_waiting_dir_move(struct send_ctx *sctx, u64 ino, bool orphanized)
3039 struct rb_node **p = &sctx->waiting_dir_moves.rb_node;
3040 struct rb_node *parent = NULL;
3041 struct waiting_dir_move *entry, *dm;
3043 dm = kmalloc(sizeof(*dm), GFP_KERNEL);
3049 dm->orphanized = orphanized;
3053 entry = rb_entry(parent, struct waiting_dir_move, node);
3054 if (ino < entry->ino) {
3056 } else if (ino > entry->ino) {
3057 p = &(*p)->rb_right;
3064 rb_link_node(&dm->node, parent, p);
3065 rb_insert_color(&dm->node, &sctx->waiting_dir_moves);
3069 static struct waiting_dir_move *
3070 get_waiting_dir_move(struct send_ctx *sctx, u64 ino)
3072 struct rb_node *n = sctx->waiting_dir_moves.rb_node;
3073 struct waiting_dir_move *entry;
3076 entry = rb_entry(n, struct waiting_dir_move, node);
3077 if (ino < entry->ino)
3079 else if (ino > entry->ino)
3087 static void free_waiting_dir_move(struct send_ctx *sctx,
3088 struct waiting_dir_move *dm)
3092 rb_erase(&dm->node, &sctx->waiting_dir_moves);
3096 static int add_pending_dir_move(struct send_ctx *sctx,
3100 struct list_head *new_refs,
3101 struct list_head *deleted_refs,
3102 const bool is_orphan)
3104 struct rb_node **p = &sctx->pending_dir_moves.rb_node;
3105 struct rb_node *parent = NULL;
3106 struct pending_dir_move *entry = NULL, *pm;
3107 struct recorded_ref *cur;
3111 pm = kmalloc(sizeof(*pm), GFP_KERNEL);
3114 pm->parent_ino = parent_ino;
3117 INIT_LIST_HEAD(&pm->list);
3118 INIT_LIST_HEAD(&pm->update_refs);
3119 RB_CLEAR_NODE(&pm->node);
3123 entry = rb_entry(parent, struct pending_dir_move, node);
3124 if (parent_ino < entry->parent_ino) {
3126 } else if (parent_ino > entry->parent_ino) {
3127 p = &(*p)->rb_right;
3134 list_for_each_entry(cur, deleted_refs, list) {
3135 ret = dup_ref(cur, &pm->update_refs);
3139 list_for_each_entry(cur, new_refs, list) {
3140 ret = dup_ref(cur, &pm->update_refs);
3145 ret = add_waiting_dir_move(sctx, pm->ino, is_orphan);
3150 list_add_tail(&pm->list, &entry->list);
3152 rb_link_node(&pm->node, parent, p);
3153 rb_insert_color(&pm->node, &sctx->pending_dir_moves);
3158 __free_recorded_refs(&pm->update_refs);
3164 static struct pending_dir_move *get_pending_dir_moves(struct send_ctx *sctx,
3167 struct rb_node *n = sctx->pending_dir_moves.rb_node;
3168 struct pending_dir_move *entry;
3171 entry = rb_entry(n, struct pending_dir_move, node);
3172 if (parent_ino < entry->parent_ino)
3174 else if (parent_ino > entry->parent_ino)
3182 static int path_loop(struct send_ctx *sctx, struct fs_path *name,
3183 u64 ino, u64 gen, u64 *ancestor_ino)
3186 u64 parent_inode = 0;
3188 u64 start_ino = ino;
3191 while (ino != BTRFS_FIRST_FREE_OBJECTID) {
3192 fs_path_reset(name);
3194 if (is_waiting_for_rm(sctx, ino, gen))
3196 if (is_waiting_for_move(sctx, ino)) {
3197 if (*ancestor_ino == 0)
3198 *ancestor_ino = ino;
3199 ret = get_first_ref(sctx->parent_root, ino,
3200 &parent_inode, &parent_gen, name);
3202 ret = __get_cur_name_and_parent(sctx, ino, gen,
3212 if (parent_inode == start_ino) {
3214 if (*ancestor_ino == 0)
3215 *ancestor_ino = ino;
3224 static int apply_dir_move(struct send_ctx *sctx, struct pending_dir_move *pm)
3226 struct fs_path *from_path = NULL;
3227 struct fs_path *to_path = NULL;
3228 struct fs_path *name = NULL;
3229 u64 orig_progress = sctx->send_progress;
3230 struct recorded_ref *cur;
3231 u64 parent_ino, parent_gen;
3232 struct waiting_dir_move *dm = NULL;
3239 name = fs_path_alloc();
3240 from_path = fs_path_alloc();
3241 if (!name || !from_path) {
3246 dm = get_waiting_dir_move(sctx, pm->ino);
3248 rmdir_ino = dm->rmdir_ino;
3249 rmdir_gen = dm->rmdir_gen;
3250 is_orphan = dm->orphanized;
3251 free_waiting_dir_move(sctx, dm);
3254 ret = gen_unique_name(sctx, pm->ino,
3255 pm->gen, from_path);
3257 ret = get_first_ref(sctx->parent_root, pm->ino,
3258 &parent_ino, &parent_gen, name);
3261 ret = get_cur_path(sctx, parent_ino, parent_gen,
3265 ret = fs_path_add_path(from_path, name);
3270 sctx->send_progress = sctx->cur_ino + 1;
3271 ret = path_loop(sctx, name, pm->ino, pm->gen, &ancestor);
3275 LIST_HEAD(deleted_refs);
3276 ASSERT(ancestor > BTRFS_FIRST_FREE_OBJECTID);
3277 ret = add_pending_dir_move(sctx, pm->ino, pm->gen, ancestor,
3278 &pm->update_refs, &deleted_refs,
3283 dm = get_waiting_dir_move(sctx, pm->ino);
3285 dm->rmdir_ino = rmdir_ino;
3286 dm->rmdir_gen = rmdir_gen;
3290 fs_path_reset(name);
3293 ret = get_cur_path(sctx, pm->ino, pm->gen, to_path);
3297 ret = send_rename(sctx, from_path, to_path);
3302 struct orphan_dir_info *odi;
3305 odi = get_orphan_dir_info(sctx, rmdir_ino, rmdir_gen);
3307 /* already deleted */
3312 ret = can_rmdir(sctx, rmdir_ino, gen, sctx->cur_ino);
3318 name = fs_path_alloc();
3323 ret = get_cur_path(sctx, rmdir_ino, gen, name);
3326 ret = send_rmdir(sctx, name);
3332 ret = send_utimes(sctx, pm->ino, pm->gen);
3337 * After rename/move, need to update the utimes of both new parent(s)
3338 * and old parent(s).
3340 list_for_each_entry(cur, &pm->update_refs, list) {
3342 * The parent inode might have been deleted in the send snapshot
3344 ret = get_inode_info(sctx->send_root, cur->dir, NULL,
3345 NULL, NULL, NULL, NULL, NULL);
3346 if (ret == -ENOENT) {
3353 ret = send_utimes(sctx, cur->dir, cur->dir_gen);
3360 fs_path_free(from_path);
3361 fs_path_free(to_path);
3362 sctx->send_progress = orig_progress;
3367 static void free_pending_move(struct send_ctx *sctx, struct pending_dir_move *m)
3369 if (!list_empty(&m->list))
3371 if (!RB_EMPTY_NODE(&m->node))
3372 rb_erase(&m->node, &sctx->pending_dir_moves);
3373 __free_recorded_refs(&m->update_refs);
3377 static void tail_append_pending_moves(struct send_ctx *sctx,
3378 struct pending_dir_move *moves,
3379 struct list_head *stack)
3381 if (list_empty(&moves->list)) {
3382 list_add_tail(&moves->list, stack);
3385 list_splice_init(&moves->list, &list);
3386 list_add_tail(&moves->list, stack);
3387 list_splice_tail(&list, stack);
3389 if (!RB_EMPTY_NODE(&moves->node)) {
3390 rb_erase(&moves->node, &sctx->pending_dir_moves);
3391 RB_CLEAR_NODE(&moves->node);
3395 static int apply_children_dir_moves(struct send_ctx *sctx)
3397 struct pending_dir_move *pm;
3398 struct list_head stack;
3399 u64 parent_ino = sctx->cur_ino;
3402 pm = get_pending_dir_moves(sctx, parent_ino);
3406 INIT_LIST_HEAD(&stack);
3407 tail_append_pending_moves(sctx, pm, &stack);
3409 while (!list_empty(&stack)) {
3410 pm = list_first_entry(&stack, struct pending_dir_move, list);
3411 parent_ino = pm->ino;
3412 ret = apply_dir_move(sctx, pm);
3413 free_pending_move(sctx, pm);
3416 pm = get_pending_dir_moves(sctx, parent_ino);
3418 tail_append_pending_moves(sctx, pm, &stack);
3423 while (!list_empty(&stack)) {
3424 pm = list_first_entry(&stack, struct pending_dir_move, list);
3425 free_pending_move(sctx, pm);
3431 * We might need to delay a directory rename even when no ancestor directory
3432 * (in the send root) with a higher inode number than ours (sctx->cur_ino) was
3433 * renamed. This happens when we rename a directory to the old name (the name
3434 * in the parent root) of some other unrelated directory that got its rename
3435 * delayed due to some ancestor with higher number that got renamed.
3441 * |---- a/ (ino 257)
3442 * | |---- file (ino 260)
3444 * |---- b/ (ino 258)
3445 * |---- c/ (ino 259)
3449 * |---- a/ (ino 258)
3450 * |---- x/ (ino 259)
3451 * |---- y/ (ino 257)
3452 * |----- file (ino 260)
3454 * Here we can not rename 258 from 'b' to 'a' without the rename of inode 257
3455 * from 'a' to 'x/y' happening first, which in turn depends on the rename of
3456 * inode 259 from 'c' to 'x'. So the order of rename commands the send stream
3459 * 1 - rename 259 from 'c' to 'x'
3460 * 2 - rename 257 from 'a' to 'x/y'
3461 * 3 - rename 258 from 'b' to 'a'
3463 * Returns 1 if the rename of sctx->cur_ino needs to be delayed, 0 if it can
3464 * be done right away and < 0 on error.
3466 static int wait_for_dest_dir_move(struct send_ctx *sctx,
3467 struct recorded_ref *parent_ref,
3468 const bool is_orphan)
3470 struct btrfs_fs_info *fs_info = sctx->parent_root->fs_info;
3471 struct btrfs_path *path;
3472 struct btrfs_key key;
3473 struct btrfs_key di_key;
3474 struct btrfs_dir_item *di;
3478 struct waiting_dir_move *wdm;
3480 if (RB_EMPTY_ROOT(&sctx->waiting_dir_moves))
3483 path = alloc_path_for_send();
3487 key.objectid = parent_ref->dir;
3488 key.type = BTRFS_DIR_ITEM_KEY;
3489 key.offset = btrfs_name_hash(parent_ref->name, parent_ref->name_len);
3491 ret = btrfs_search_slot(NULL, sctx->parent_root, &key, path, 0, 0);
3494 } else if (ret > 0) {
3499 di = btrfs_match_dir_item_name(fs_info, path, parent_ref->name,
3500 parent_ref->name_len);
3506 * di_key.objectid has the number of the inode that has a dentry in the
3507 * parent directory with the same name that sctx->cur_ino is being
3508 * renamed to. We need to check if that inode is in the send root as
3509 * well and if it is currently marked as an inode with a pending rename,
3510 * if it is, we need to delay the rename of sctx->cur_ino as well, so
3511 * that it happens after that other inode is renamed.
3513 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &di_key);
3514 if (di_key.type != BTRFS_INODE_ITEM_KEY) {
3519 ret = get_inode_info(sctx->parent_root, di_key.objectid, NULL,
3520 &left_gen, NULL, NULL, NULL, NULL);
3523 ret = get_inode_info(sctx->send_root, di_key.objectid, NULL,
3524 &right_gen, NULL, NULL, NULL, NULL);
3531 /* Different inode, no need to delay the rename of sctx->cur_ino */
3532 if (right_gen != left_gen) {
3537 wdm = get_waiting_dir_move(sctx, di_key.objectid);
3538 if (wdm && !wdm->orphanized) {
3539 ret = add_pending_dir_move(sctx,
3541 sctx->cur_inode_gen,
3544 &sctx->deleted_refs,
3550 btrfs_free_path(path);
3555 * Check if inode ino2, or any of its ancestors, is inode ino1.
3556 * Return 1 if true, 0 if false and < 0 on error.
3558 static int check_ino_in_path(struct btrfs_root *root,
3563 struct fs_path *fs_path)
3568 return ino1_gen == ino2_gen;
3570 while (ino > BTRFS_FIRST_FREE_OBJECTID) {
3575 fs_path_reset(fs_path);
3576 ret = get_first_ref(root, ino, &parent, &parent_gen, fs_path);
3580 return parent_gen == ino1_gen;
3587 * Check if ino ino1 is an ancestor of inode ino2 in the given root for any
3588 * possible path (in case ino2 is not a directory and has multiple hard links).
3589 * Return 1 if true, 0 if false and < 0 on error.
3591 static int is_ancestor(struct btrfs_root *root,
3595 struct fs_path *fs_path)
3597 bool free_fs_path = false;
3599 struct btrfs_path *path = NULL;
3600 struct btrfs_key key;
3603 fs_path = fs_path_alloc();
3606 free_fs_path = true;
3609 path = alloc_path_for_send();
3615 key.objectid = ino2;
3616 key.type = BTRFS_INODE_REF_KEY;
3619 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3624 struct extent_buffer *leaf = path->nodes[0];
3625 int slot = path->slots[0];
3629 if (slot >= btrfs_header_nritems(leaf)) {
3630 ret = btrfs_next_leaf(root, path);
3638 btrfs_item_key_to_cpu(leaf, &key, slot);
3639 if (key.objectid != ino2)
3641 if (key.type != BTRFS_INODE_REF_KEY &&
3642 key.type != BTRFS_INODE_EXTREF_KEY)
3645 item_size = btrfs_item_size(leaf, slot);
3646 while (cur_offset < item_size) {
3650 if (key.type == BTRFS_INODE_EXTREF_KEY) {
3652 struct btrfs_inode_extref *extref;
3654 ptr = btrfs_item_ptr_offset(leaf, slot);
3655 extref = (struct btrfs_inode_extref *)
3657 parent = btrfs_inode_extref_parent(leaf,
3659 cur_offset += sizeof(*extref);
3660 cur_offset += btrfs_inode_extref_name_len(leaf,
3663 parent = key.offset;
3664 cur_offset = item_size;
3667 ret = get_inode_info(root, parent, NULL, &parent_gen,
3668 NULL, NULL, NULL, NULL);
3671 ret = check_ino_in_path(root, ino1, ino1_gen,
3672 parent, parent_gen, fs_path);
3680 btrfs_free_path(path);
3682 fs_path_free(fs_path);
3686 static int wait_for_parent_move(struct send_ctx *sctx,
3687 struct recorded_ref *parent_ref,
3688 const bool is_orphan)
3691 u64 ino = parent_ref->dir;
3692 u64 ino_gen = parent_ref->dir_gen;
3693 u64 parent_ino_before, parent_ino_after;
3694 struct fs_path *path_before = NULL;
3695 struct fs_path *path_after = NULL;
3698 path_after = fs_path_alloc();
3699 path_before = fs_path_alloc();
3700 if (!path_after || !path_before) {
3706 * Our current directory inode may not yet be renamed/moved because some
3707 * ancestor (immediate or not) has to be renamed/moved first. So find if
3708 * such ancestor exists and make sure our own rename/move happens after
3709 * that ancestor is processed to avoid path build infinite loops (done
3710 * at get_cur_path()).
3712 while (ino > BTRFS_FIRST_FREE_OBJECTID) {
3713 u64 parent_ino_after_gen;
3715 if (is_waiting_for_move(sctx, ino)) {
3717 * If the current inode is an ancestor of ino in the
3718 * parent root, we need to delay the rename of the
3719 * current inode, otherwise don't delayed the rename
3720 * because we can end up with a circular dependency
3721 * of renames, resulting in some directories never
3722 * getting the respective rename operations issued in
3723 * the send stream or getting into infinite path build
3726 ret = is_ancestor(sctx->parent_root,
3727 sctx->cur_ino, sctx->cur_inode_gen,
3733 fs_path_reset(path_before);
3734 fs_path_reset(path_after);
3736 ret = get_first_ref(sctx->send_root, ino, &parent_ino_after,
3737 &parent_ino_after_gen, path_after);
3740 ret = get_first_ref(sctx->parent_root, ino, &parent_ino_before,
3742 if (ret < 0 && ret != -ENOENT) {
3744 } else if (ret == -ENOENT) {
3749 len1 = fs_path_len(path_before);
3750 len2 = fs_path_len(path_after);
3751 if (ino > sctx->cur_ino &&
3752 (parent_ino_before != parent_ino_after || len1 != len2 ||
3753 memcmp(path_before->start, path_after->start, len1))) {
3756 ret = get_inode_info(sctx->parent_root, ino, NULL,
3757 &parent_ino_gen, NULL, NULL, NULL,
3761 if (ino_gen == parent_ino_gen) {
3766 ino = parent_ino_after;
3767 ino_gen = parent_ino_after_gen;
3771 fs_path_free(path_before);
3772 fs_path_free(path_after);
3775 ret = add_pending_dir_move(sctx,
3777 sctx->cur_inode_gen,
3780 &sctx->deleted_refs,
3789 static int update_ref_path(struct send_ctx *sctx, struct recorded_ref *ref)
3792 struct fs_path *new_path;
3795 * Our reference's name member points to its full_path member string, so
3796 * we use here a new path.
3798 new_path = fs_path_alloc();
3802 ret = get_cur_path(sctx, ref->dir, ref->dir_gen, new_path);
3804 fs_path_free(new_path);
3807 ret = fs_path_add(new_path, ref->name, ref->name_len);
3809 fs_path_free(new_path);
3813 fs_path_free(ref->full_path);
3814 set_ref_path(ref, new_path);
3820 * When processing the new references for an inode we may orphanize an existing
3821 * directory inode because its old name conflicts with one of the new references
3822 * of the current inode. Later, when processing another new reference of our
3823 * inode, we might need to orphanize another inode, but the path we have in the
3824 * reference reflects the pre-orphanization name of the directory we previously
3825 * orphanized. For example:
3827 * parent snapshot looks like:
3830 * |----- f1 (ino 257)
3831 * |----- f2 (ino 258)
3832 * |----- d1/ (ino 259)
3833 * |----- d2/ (ino 260)
3835 * send snapshot looks like:
3838 * |----- d1 (ino 258)
3839 * |----- f2/ (ino 259)
3840 * |----- f2_link/ (ino 260)
3841 * | |----- f1 (ino 257)
3843 * |----- d2 (ino 258)
3845 * When processing inode 257 we compute the name for inode 259 as "d1", and we
3846 * cache it in the name cache. Later when we start processing inode 258, when
3847 * collecting all its new references we set a full path of "d1/d2" for its new
3848 * reference with name "d2". When we start processing the new references we
3849 * start by processing the new reference with name "d1", and this results in
3850 * orphanizing inode 259, since its old reference causes a conflict. Then we
3851 * move on the next new reference, with name "d2", and we find out we must
3852 * orphanize inode 260, as its old reference conflicts with ours - but for the
3853 * orphanization we use a source path corresponding to the path we stored in the
3854 * new reference, which is "d1/d2" and not "o259-6-0/d2" - this makes the
3855 * receiver fail since the path component "d1/" no longer exists, it was renamed
3856 * to "o259-6-0/" when processing the previous new reference. So in this case we
3857 * must recompute the path in the new reference and use it for the new
3858 * orphanization operation.
3860 static int refresh_ref_path(struct send_ctx *sctx, struct recorded_ref *ref)
3865 name = kmemdup(ref->name, ref->name_len, GFP_KERNEL);
3869 fs_path_reset(ref->full_path);
3870 ret = get_cur_path(sctx, ref->dir, ref->dir_gen, ref->full_path);
3874 ret = fs_path_add(ref->full_path, name, ref->name_len);
3878 /* Update the reference's base name pointer. */
3879 set_ref_path(ref, ref->full_path);
3886 * This does all the move/link/unlink/rmdir magic.
3888 static int process_recorded_refs(struct send_ctx *sctx, int *pending_move)
3890 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
3892 struct recorded_ref *cur;
3893 struct recorded_ref *cur2;
3894 struct list_head check_dirs;
3895 struct fs_path *valid_path = NULL;
3899 int did_overwrite = 0;
3901 u64 last_dir_ino_rm = 0;
3902 bool can_rename = true;
3903 bool orphanized_dir = false;
3904 bool orphanized_ancestor = false;
3906 btrfs_debug(fs_info, "process_recorded_refs %llu", sctx->cur_ino);
3909 * This should never happen as the root dir always has the same ref
3910 * which is always '..'
3912 BUG_ON(sctx->cur_ino <= BTRFS_FIRST_FREE_OBJECTID);
3913 INIT_LIST_HEAD(&check_dirs);
3915 valid_path = fs_path_alloc();
3922 * First, check if the first ref of the current inode was overwritten
3923 * before. If yes, we know that the current inode was already orphanized
3924 * and thus use the orphan name. If not, we can use get_cur_path to
3925 * get the path of the first ref as it would like while receiving at
3926 * this point in time.
3927 * New inodes are always orphan at the beginning, so force to use the
3928 * orphan name in this case.
3929 * The first ref is stored in valid_path and will be updated if it
3930 * gets moved around.
3932 if (!sctx->cur_inode_new) {
3933 ret = did_overwrite_first_ref(sctx, sctx->cur_ino,
3934 sctx->cur_inode_gen);
3940 if (sctx->cur_inode_new || did_overwrite) {
3941 ret = gen_unique_name(sctx, sctx->cur_ino,
3942 sctx->cur_inode_gen, valid_path);
3947 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen,
3954 * Before doing any rename and link operations, do a first pass on the
3955 * new references to orphanize any unprocessed inodes that may have a
3956 * reference that conflicts with one of the new references of the current
3957 * inode. This needs to happen first because a new reference may conflict
3958 * with the old reference of a parent directory, so we must make sure
3959 * that the path used for link and rename commands don't use an
3960 * orphanized name when an ancestor was not yet orphanized.
3967 * |----- testdir/ (ino 259)
3968 * | |----- a (ino 257)
3970 * |----- b (ino 258)
3975 * |----- testdir_2/ (ino 259)
3976 * | |----- a (ino 260)
3978 * |----- testdir (ino 257)
3979 * |----- b (ino 257)
3980 * |----- b2 (ino 258)
3982 * Processing the new reference for inode 257 with name "b" may happen
3983 * before processing the new reference with name "testdir". If so, we
3984 * must make sure that by the time we send a link command to create the
3985 * hard link "b", inode 259 was already orphanized, since the generated
3986 * path in "valid_path" already contains the orphanized name for 259.
3987 * We are processing inode 257, so only later when processing 259 we do
3988 * the rename operation to change its temporary (orphanized) name to
3991 list_for_each_entry(cur, &sctx->new_refs, list) {
3992 ret = get_cur_inode_state(sctx, cur->dir, cur->dir_gen);
3995 if (ret == inode_state_will_create)
3999 * Check if this new ref would overwrite the first ref of another
4000 * unprocessed inode. If yes, orphanize the overwritten inode.
4001 * If we find an overwritten ref that is not the first ref,
4004 ret = will_overwrite_ref(sctx, cur->dir, cur->dir_gen,
4005 cur->name, cur->name_len,
4006 &ow_inode, &ow_gen, &ow_mode);
4010 ret = is_first_ref(sctx->parent_root,
4011 ow_inode, cur->dir, cur->name,
4016 struct name_cache_entry *nce;
4017 struct waiting_dir_move *wdm;
4019 if (orphanized_dir) {
4020 ret = refresh_ref_path(sctx, cur);
4025 ret = orphanize_inode(sctx, ow_inode, ow_gen,
4029 if (S_ISDIR(ow_mode))
4030 orphanized_dir = true;
4033 * If ow_inode has its rename operation delayed
4034 * make sure that its orphanized name is used in
4035 * the source path when performing its rename
4038 if (is_waiting_for_move(sctx, ow_inode)) {
4039 wdm = get_waiting_dir_move(sctx,
4042 wdm->orphanized = true;
4046 * Make sure we clear our orphanized inode's
4047 * name from the name cache. This is because the
4048 * inode ow_inode might be an ancestor of some
4049 * other inode that will be orphanized as well
4050 * later and has an inode number greater than
4051 * sctx->send_progress. We need to prevent
4052 * future name lookups from using the old name
4053 * and get instead the orphan name.
4055 nce = name_cache_search(sctx, ow_inode, ow_gen);
4057 name_cache_delete(sctx, nce);
4062 * ow_inode might currently be an ancestor of
4063 * cur_ino, therefore compute valid_path (the
4064 * current path of cur_ino) again because it
4065 * might contain the pre-orphanization name of
4066 * ow_inode, which is no longer valid.
4068 ret = is_ancestor(sctx->parent_root,
4070 sctx->cur_ino, NULL);
4072 orphanized_ancestor = true;
4073 fs_path_reset(valid_path);
4074 ret = get_cur_path(sctx, sctx->cur_ino,
4075 sctx->cur_inode_gen,
4082 * If we previously orphanized a directory that
4083 * collided with a new reference that we already
4084 * processed, recompute the current path because
4085 * that directory may be part of the path.
4087 if (orphanized_dir) {
4088 ret = refresh_ref_path(sctx, cur);
4092 ret = send_unlink(sctx, cur->full_path);
4100 list_for_each_entry(cur, &sctx->new_refs, list) {
4102 * We may have refs where the parent directory does not exist
4103 * yet. This happens if the parent directories inum is higher
4104 * than the current inum. To handle this case, we create the
4105 * parent directory out of order. But we need to check if this
4106 * did already happen before due to other refs in the same dir.
4108 ret = get_cur_inode_state(sctx, cur->dir, cur->dir_gen);
4111 if (ret == inode_state_will_create) {
4114 * First check if any of the current inodes refs did
4115 * already create the dir.
4117 list_for_each_entry(cur2, &sctx->new_refs, list) {
4120 if (cur2->dir == cur->dir) {
4127 * If that did not happen, check if a previous inode
4128 * did already create the dir.
4131 ret = did_create_dir(sctx, cur->dir);
4135 ret = send_create_inode(sctx, cur->dir);
4141 if (S_ISDIR(sctx->cur_inode_mode) && sctx->parent_root) {
4142 ret = wait_for_dest_dir_move(sctx, cur, is_orphan);
4151 if (S_ISDIR(sctx->cur_inode_mode) && sctx->parent_root &&
4153 ret = wait_for_parent_move(sctx, cur, is_orphan);
4163 * link/move the ref to the new place. If we have an orphan
4164 * inode, move it and update valid_path. If not, link or move
4165 * it depending on the inode mode.
4167 if (is_orphan && can_rename) {
4168 ret = send_rename(sctx, valid_path, cur->full_path);
4172 ret = fs_path_copy(valid_path, cur->full_path);
4175 } else if (can_rename) {
4176 if (S_ISDIR(sctx->cur_inode_mode)) {
4178 * Dirs can't be linked, so move it. For moved
4179 * dirs, we always have one new and one deleted
4180 * ref. The deleted ref is ignored later.
4182 ret = send_rename(sctx, valid_path,
4185 ret = fs_path_copy(valid_path,
4191 * We might have previously orphanized an inode
4192 * which is an ancestor of our current inode,
4193 * so our reference's full path, which was
4194 * computed before any such orphanizations, must
4197 if (orphanized_dir) {
4198 ret = update_ref_path(sctx, cur);
4202 ret = send_link(sctx, cur->full_path,
4208 ret = dup_ref(cur, &check_dirs);
4213 if (S_ISDIR(sctx->cur_inode_mode) && sctx->cur_inode_deleted) {
4215 * Check if we can already rmdir the directory. If not,
4216 * orphanize it. For every dir item inside that gets deleted
4217 * later, we do this check again and rmdir it then if possible.
4218 * See the use of check_dirs for more details.
4220 ret = can_rmdir(sctx, sctx->cur_ino, sctx->cur_inode_gen,
4225 ret = send_rmdir(sctx, valid_path);
4228 } else if (!is_orphan) {
4229 ret = orphanize_inode(sctx, sctx->cur_ino,
4230 sctx->cur_inode_gen, valid_path);
4236 list_for_each_entry(cur, &sctx->deleted_refs, list) {
4237 ret = dup_ref(cur, &check_dirs);
4241 } else if (S_ISDIR(sctx->cur_inode_mode) &&
4242 !list_empty(&sctx->deleted_refs)) {
4244 * We have a moved dir. Add the old parent to check_dirs
4246 cur = list_entry(sctx->deleted_refs.next, struct recorded_ref,
4248 ret = dup_ref(cur, &check_dirs);
4251 } else if (!S_ISDIR(sctx->cur_inode_mode)) {
4253 * We have a non dir inode. Go through all deleted refs and
4254 * unlink them if they were not already overwritten by other
4257 list_for_each_entry(cur, &sctx->deleted_refs, list) {
4258 ret = did_overwrite_ref(sctx, cur->dir, cur->dir_gen,
4259 sctx->cur_ino, sctx->cur_inode_gen,
4260 cur->name, cur->name_len);
4265 * If we orphanized any ancestor before, we need
4266 * to recompute the full path for deleted names,
4267 * since any such path was computed before we
4268 * processed any references and orphanized any
4271 if (orphanized_ancestor) {
4272 ret = update_ref_path(sctx, cur);
4276 ret = send_unlink(sctx, cur->full_path);
4280 ret = dup_ref(cur, &check_dirs);
4285 * If the inode is still orphan, unlink the orphan. This may
4286 * happen when a previous inode did overwrite the first ref
4287 * of this inode and no new refs were added for the current
4288 * inode. Unlinking does not mean that the inode is deleted in
4289 * all cases. There may still be links to this inode in other
4293 ret = send_unlink(sctx, valid_path);
4300 * We did collect all parent dirs where cur_inode was once located. We
4301 * now go through all these dirs and check if they are pending for
4302 * deletion and if it's finally possible to perform the rmdir now.
4303 * We also update the inode stats of the parent dirs here.
4305 list_for_each_entry(cur, &check_dirs, list) {
4307 * In case we had refs into dirs that were not processed yet,
4308 * we don't need to do the utime and rmdir logic for these dirs.
4309 * The dir will be processed later.
4311 if (cur->dir > sctx->cur_ino)
4314 ret = get_cur_inode_state(sctx, cur->dir, cur->dir_gen);
4318 if (ret == inode_state_did_create ||
4319 ret == inode_state_no_change) {
4320 /* TODO delayed utimes */
4321 ret = send_utimes(sctx, cur->dir, cur->dir_gen);
4324 } else if (ret == inode_state_did_delete &&
4325 cur->dir != last_dir_ino_rm) {
4326 ret = can_rmdir(sctx, cur->dir, cur->dir_gen,
4331 ret = get_cur_path(sctx, cur->dir,
4332 cur->dir_gen, valid_path);
4335 ret = send_rmdir(sctx, valid_path);
4338 last_dir_ino_rm = cur->dir;
4346 __free_recorded_refs(&check_dirs);
4347 free_recorded_refs(sctx);
4348 fs_path_free(valid_path);
4352 static int record_ref(struct btrfs_root *root, u64 dir, struct fs_path *name,
4353 void *ctx, struct list_head *refs)
4356 struct send_ctx *sctx = ctx;
4360 p = fs_path_alloc();
4364 ret = get_inode_info(root, dir, NULL, &gen, NULL, NULL,
4369 ret = get_cur_path(sctx, dir, gen, p);
4372 ret = fs_path_add_path(p, name);
4376 ret = __record_ref(refs, dir, gen, p);
4384 static int __record_new_ref(int num, u64 dir, int index,
4385 struct fs_path *name,
4388 struct send_ctx *sctx = ctx;
4389 return record_ref(sctx->send_root, dir, name, ctx, &sctx->new_refs);
4393 static int __record_deleted_ref(int num, u64 dir, int index,
4394 struct fs_path *name,
4397 struct send_ctx *sctx = ctx;
4398 return record_ref(sctx->parent_root, dir, name, ctx,
4399 &sctx->deleted_refs);
4402 static int record_new_ref(struct send_ctx *sctx)
4406 ret = iterate_inode_ref(sctx->send_root, sctx->left_path,
4407 sctx->cmp_key, 0, __record_new_ref, sctx);
4416 static int record_deleted_ref(struct send_ctx *sctx)
4420 ret = iterate_inode_ref(sctx->parent_root, sctx->right_path,
4421 sctx->cmp_key, 0, __record_deleted_ref, sctx);
4430 struct find_ref_ctx {
4433 struct btrfs_root *root;
4434 struct fs_path *name;
4438 static int __find_iref(int num, u64 dir, int index,
4439 struct fs_path *name,
4442 struct find_ref_ctx *ctx = ctx_;
4446 if (dir == ctx->dir && fs_path_len(name) == fs_path_len(ctx->name) &&
4447 strncmp(name->start, ctx->name->start, fs_path_len(name)) == 0) {
4449 * To avoid doing extra lookups we'll only do this if everything
4452 ret = get_inode_info(ctx->root, dir, NULL, &dir_gen, NULL,
4456 if (dir_gen != ctx->dir_gen)
4458 ctx->found_idx = num;
4464 static int find_iref(struct btrfs_root *root,
4465 struct btrfs_path *path,
4466 struct btrfs_key *key,
4467 u64 dir, u64 dir_gen, struct fs_path *name)
4470 struct find_ref_ctx ctx;
4474 ctx.dir_gen = dir_gen;
4478 ret = iterate_inode_ref(root, path, key, 0, __find_iref, &ctx);
4482 if (ctx.found_idx == -1)
4485 return ctx.found_idx;
4488 static int __record_changed_new_ref(int num, u64 dir, int index,
4489 struct fs_path *name,
4494 struct send_ctx *sctx = ctx;
4496 ret = get_inode_info(sctx->send_root, dir, NULL, &dir_gen, NULL,
4501 ret = find_iref(sctx->parent_root, sctx->right_path,
4502 sctx->cmp_key, dir, dir_gen, name);
4504 ret = __record_new_ref(num, dir, index, name, sctx);
4511 static int __record_changed_deleted_ref(int num, u64 dir, int index,
4512 struct fs_path *name,
4517 struct send_ctx *sctx = ctx;
4519 ret = get_inode_info(sctx->parent_root, dir, NULL, &dir_gen, NULL,
4524 ret = find_iref(sctx->send_root, sctx->left_path, sctx->cmp_key,
4525 dir, dir_gen, name);
4527 ret = __record_deleted_ref(num, dir, index, name, sctx);
4534 static int record_changed_ref(struct send_ctx *sctx)
4538 ret = iterate_inode_ref(sctx->send_root, sctx->left_path,
4539 sctx->cmp_key, 0, __record_changed_new_ref, sctx);
4542 ret = iterate_inode_ref(sctx->parent_root, sctx->right_path,
4543 sctx->cmp_key, 0, __record_changed_deleted_ref, sctx);
4553 * Record and process all refs at once. Needed when an inode changes the
4554 * generation number, which means that it was deleted and recreated.
4556 static int process_all_refs(struct send_ctx *sctx,
4557 enum btrfs_compare_tree_result cmd)
4560 struct btrfs_root *root;
4561 struct btrfs_path *path;
4562 struct btrfs_key key;
4563 struct btrfs_key found_key;
4564 struct extent_buffer *eb;
4566 iterate_inode_ref_t cb;
4567 int pending_move = 0;
4569 path = alloc_path_for_send();
4573 if (cmd == BTRFS_COMPARE_TREE_NEW) {
4574 root = sctx->send_root;
4575 cb = __record_new_ref;
4576 } else if (cmd == BTRFS_COMPARE_TREE_DELETED) {
4577 root = sctx->parent_root;
4578 cb = __record_deleted_ref;
4580 btrfs_err(sctx->send_root->fs_info,
4581 "Wrong command %d in process_all_refs", cmd);
4586 key.objectid = sctx->cmp_key->objectid;
4587 key.type = BTRFS_INODE_REF_KEY;
4589 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4594 eb = path->nodes[0];
4595 slot = path->slots[0];
4596 if (slot >= btrfs_header_nritems(eb)) {
4597 ret = btrfs_next_leaf(root, path);
4605 btrfs_item_key_to_cpu(eb, &found_key, slot);
4607 if (found_key.objectid != key.objectid ||
4608 (found_key.type != BTRFS_INODE_REF_KEY &&
4609 found_key.type != BTRFS_INODE_EXTREF_KEY))
4612 ret = iterate_inode_ref(root, path, &found_key, 0, cb, sctx);
4618 btrfs_release_path(path);
4621 * We don't actually care about pending_move as we are simply
4622 * re-creating this inode and will be rename'ing it into place once we
4623 * rename the parent directory.
4625 ret = process_recorded_refs(sctx, &pending_move);
4627 btrfs_free_path(path);
4631 static int send_set_xattr(struct send_ctx *sctx,
4632 struct fs_path *path,
4633 const char *name, int name_len,
4634 const char *data, int data_len)
4638 ret = begin_cmd(sctx, BTRFS_SEND_C_SET_XATTR);
4642 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
4643 TLV_PUT_STRING(sctx, BTRFS_SEND_A_XATTR_NAME, name, name_len);
4644 TLV_PUT(sctx, BTRFS_SEND_A_XATTR_DATA, data, data_len);
4646 ret = send_cmd(sctx);
4653 static int send_remove_xattr(struct send_ctx *sctx,
4654 struct fs_path *path,
4655 const char *name, int name_len)
4659 ret = begin_cmd(sctx, BTRFS_SEND_C_REMOVE_XATTR);
4663 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
4664 TLV_PUT_STRING(sctx, BTRFS_SEND_A_XATTR_NAME, name, name_len);
4666 ret = send_cmd(sctx);
4673 static int __process_new_xattr(int num, struct btrfs_key *di_key,
4674 const char *name, int name_len, const char *data,
4675 int data_len, void *ctx)
4678 struct send_ctx *sctx = ctx;
4680 struct posix_acl_xattr_header dummy_acl;
4682 /* Capabilities are emitted by finish_inode_if_needed */
4683 if (!strncmp(name, XATTR_NAME_CAPS, name_len))
4686 p = fs_path_alloc();
4691 * This hack is needed because empty acls are stored as zero byte
4692 * data in xattrs. Problem with that is, that receiving these zero byte
4693 * acls will fail later. To fix this, we send a dummy acl list that
4694 * only contains the version number and no entries.
4696 if (!strncmp(name, XATTR_NAME_POSIX_ACL_ACCESS, name_len) ||
4697 !strncmp(name, XATTR_NAME_POSIX_ACL_DEFAULT, name_len)) {
4698 if (data_len == 0) {
4699 dummy_acl.a_version =
4700 cpu_to_le32(POSIX_ACL_XATTR_VERSION);
4701 data = (char *)&dummy_acl;
4702 data_len = sizeof(dummy_acl);
4706 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
4710 ret = send_set_xattr(sctx, p, name, name_len, data, data_len);
4717 static int __process_deleted_xattr(int num, struct btrfs_key *di_key,
4718 const char *name, int name_len,
4719 const char *data, int data_len, void *ctx)
4722 struct send_ctx *sctx = ctx;
4725 p = fs_path_alloc();
4729 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
4733 ret = send_remove_xattr(sctx, p, name, name_len);
4740 static int process_new_xattr(struct send_ctx *sctx)
4744 ret = iterate_dir_item(sctx->send_root, sctx->left_path,
4745 __process_new_xattr, sctx);
4750 static int process_deleted_xattr(struct send_ctx *sctx)
4752 return iterate_dir_item(sctx->parent_root, sctx->right_path,
4753 __process_deleted_xattr, sctx);
4756 struct find_xattr_ctx {
4764 static int __find_xattr(int num, struct btrfs_key *di_key, const char *name,
4765 int name_len, const char *data, int data_len, void *vctx)
4767 struct find_xattr_ctx *ctx = vctx;
4769 if (name_len == ctx->name_len &&
4770 strncmp(name, ctx->name, name_len) == 0) {
4771 ctx->found_idx = num;
4772 ctx->found_data_len = data_len;
4773 ctx->found_data = kmemdup(data, data_len, GFP_KERNEL);
4774 if (!ctx->found_data)
4781 static int find_xattr(struct btrfs_root *root,
4782 struct btrfs_path *path,
4783 struct btrfs_key *key,
4784 const char *name, int name_len,
4785 char **data, int *data_len)
4788 struct find_xattr_ctx ctx;
4791 ctx.name_len = name_len;
4793 ctx.found_data = NULL;
4794 ctx.found_data_len = 0;
4796 ret = iterate_dir_item(root, path, __find_xattr, &ctx);
4800 if (ctx.found_idx == -1)
4803 *data = ctx.found_data;
4804 *data_len = ctx.found_data_len;
4806 kfree(ctx.found_data);
4808 return ctx.found_idx;
4812 static int __process_changed_new_xattr(int num, struct btrfs_key *di_key,
4813 const char *name, int name_len,
4814 const char *data, int data_len,
4818 struct send_ctx *sctx = ctx;
4819 char *found_data = NULL;
4820 int found_data_len = 0;
4822 ret = find_xattr(sctx->parent_root, sctx->right_path,
4823 sctx->cmp_key, name, name_len, &found_data,
4825 if (ret == -ENOENT) {
4826 ret = __process_new_xattr(num, di_key, name, name_len, data,
4828 } else if (ret >= 0) {
4829 if (data_len != found_data_len ||
4830 memcmp(data, found_data, data_len)) {
4831 ret = __process_new_xattr(num, di_key, name, name_len,
4832 data, data_len, ctx);
4842 static int __process_changed_deleted_xattr(int num, struct btrfs_key *di_key,
4843 const char *name, int name_len,
4844 const char *data, int data_len,
4848 struct send_ctx *sctx = ctx;
4850 ret = find_xattr(sctx->send_root, sctx->left_path, sctx->cmp_key,
4851 name, name_len, NULL, NULL);
4853 ret = __process_deleted_xattr(num, di_key, name, name_len, data,
4861 static int process_changed_xattr(struct send_ctx *sctx)
4865 ret = iterate_dir_item(sctx->send_root, sctx->left_path,
4866 __process_changed_new_xattr, sctx);
4869 ret = iterate_dir_item(sctx->parent_root, sctx->right_path,
4870 __process_changed_deleted_xattr, sctx);
4876 static int process_all_new_xattrs(struct send_ctx *sctx)
4879 struct btrfs_root *root;
4880 struct btrfs_path *path;
4881 struct btrfs_key key;
4882 struct btrfs_key found_key;
4883 struct extent_buffer *eb;
4886 path = alloc_path_for_send();
4890 root = sctx->send_root;
4892 key.objectid = sctx->cmp_key->objectid;
4893 key.type = BTRFS_XATTR_ITEM_KEY;
4895 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4900 eb = path->nodes[0];
4901 slot = path->slots[0];
4902 if (slot >= btrfs_header_nritems(eb)) {
4903 ret = btrfs_next_leaf(root, path);
4906 } else if (ret > 0) {
4913 btrfs_item_key_to_cpu(eb, &found_key, slot);
4914 if (found_key.objectid != key.objectid ||
4915 found_key.type != key.type) {
4920 ret = iterate_dir_item(root, path, __process_new_xattr, sctx);
4928 btrfs_free_path(path);
4932 static inline u64 max_send_read_size(const struct send_ctx *sctx)
4934 return sctx->send_max_size - SZ_16K;
4937 static int put_data_header(struct send_ctx *sctx, u32 len)
4939 struct btrfs_tlv_header *hdr;
4941 if (sctx->send_max_size - sctx->send_size < sizeof(*hdr) + len)
4943 hdr = (struct btrfs_tlv_header *)(sctx->send_buf + sctx->send_size);
4944 put_unaligned_le16(BTRFS_SEND_A_DATA, &hdr->tlv_type);
4945 put_unaligned_le16(len, &hdr->tlv_len);
4946 sctx->send_size += sizeof(*hdr);
4950 static int put_file_data(struct send_ctx *sctx, u64 offset, u32 len)
4952 struct btrfs_root *root = sctx->send_root;
4953 struct btrfs_fs_info *fs_info = root->fs_info;
4954 struct inode *inode;
4956 pgoff_t index = offset >> PAGE_SHIFT;
4958 unsigned pg_offset = offset_in_page(offset);
4961 ret = put_data_header(sctx, len);
4965 inode = btrfs_iget(fs_info->sb, sctx->cur_ino, root);
4967 return PTR_ERR(inode);
4969 last_index = (offset + len - 1) >> PAGE_SHIFT;
4971 /* initial readahead */
4972 memset(&sctx->ra, 0, sizeof(struct file_ra_state));
4973 file_ra_state_init(&sctx->ra, inode->i_mapping);
4975 while (index <= last_index) {
4976 unsigned cur_len = min_t(unsigned, len,
4977 PAGE_SIZE - pg_offset);
4979 page = find_lock_page(inode->i_mapping, index);
4981 page_cache_sync_readahead(inode->i_mapping, &sctx->ra,
4982 NULL, index, last_index + 1 - index);
4984 page = find_or_create_page(inode->i_mapping, index,
4992 if (PageReadahead(page)) {
4993 page_cache_async_readahead(inode->i_mapping, &sctx->ra,
4994 NULL, page, index, last_index + 1 - index);
4997 if (!PageUptodate(page)) {
4998 btrfs_readpage(NULL, page);
5000 if (!PageUptodate(page)) {
5008 memcpy_from_page(sctx->send_buf + sctx->send_size, page,
5009 pg_offset, cur_len);
5015 sctx->send_size += cur_len;
5022 * Read some bytes from the current inode/file and send a write command to
5025 static int send_write(struct send_ctx *sctx, u64 offset, u32 len)
5027 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
5031 p = fs_path_alloc();
5035 btrfs_debug(fs_info, "send_write offset=%llu, len=%d", offset, len);
5037 ret = begin_cmd(sctx, BTRFS_SEND_C_WRITE);
5041 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5045 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5046 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5047 ret = put_file_data(sctx, offset, len);
5051 ret = send_cmd(sctx);
5060 * Send a clone command to user space.
5062 static int send_clone(struct send_ctx *sctx,
5063 u64 offset, u32 len,
5064 struct clone_root *clone_root)
5070 btrfs_debug(sctx->send_root->fs_info,
5071 "send_clone offset=%llu, len=%d, clone_root=%llu, clone_inode=%llu, clone_offset=%llu",
5072 offset, len, clone_root->root->root_key.objectid,
5073 clone_root->ino, clone_root->offset);
5075 p = fs_path_alloc();
5079 ret = begin_cmd(sctx, BTRFS_SEND_C_CLONE);
5083 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5087 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5088 TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_LEN, len);
5089 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5091 if (clone_root->root == sctx->send_root) {
5092 ret = get_inode_info(sctx->send_root, clone_root->ino, NULL,
5093 &gen, NULL, NULL, NULL, NULL);
5096 ret = get_cur_path(sctx, clone_root->ino, gen, p);
5098 ret = get_inode_path(clone_root->root, clone_root->ino, p);
5104 * If the parent we're using has a received_uuid set then use that as
5105 * our clone source as that is what we will look for when doing a
5108 * This covers the case that we create a snapshot off of a received
5109 * subvolume and then use that as the parent and try to receive on a
5112 if (!btrfs_is_empty_uuid(clone_root->root->root_item.received_uuid))
5113 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
5114 clone_root->root->root_item.received_uuid);
5116 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
5117 clone_root->root->root_item.uuid);
5118 TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_CTRANSID,
5119 btrfs_root_ctransid(&clone_root->root->root_item));
5120 TLV_PUT_PATH(sctx, BTRFS_SEND_A_CLONE_PATH, p);
5121 TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_OFFSET,
5122 clone_root->offset);
5124 ret = send_cmd(sctx);
5133 * Send an update extent command to user space.
5135 static int send_update_extent(struct send_ctx *sctx,
5136 u64 offset, u32 len)
5141 p = fs_path_alloc();
5145 ret = begin_cmd(sctx, BTRFS_SEND_C_UPDATE_EXTENT);
5149 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5153 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5154 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5155 TLV_PUT_U64(sctx, BTRFS_SEND_A_SIZE, len);
5157 ret = send_cmd(sctx);
5165 static int send_hole(struct send_ctx *sctx, u64 end)
5167 struct fs_path *p = NULL;
5168 u64 read_size = max_send_read_size(sctx);
5169 u64 offset = sctx->cur_inode_last_extent;
5173 * A hole that starts at EOF or beyond it. Since we do not yet support
5174 * fallocate (for extent preallocation and hole punching), sending a
5175 * write of zeroes starting at EOF or beyond would later require issuing
5176 * a truncate operation which would undo the write and achieve nothing.
5178 if (offset >= sctx->cur_inode_size)
5182 * Don't go beyond the inode's i_size due to prealloc extents that start
5185 end = min_t(u64, end, sctx->cur_inode_size);
5187 if (sctx->flags & BTRFS_SEND_FLAG_NO_FILE_DATA)
5188 return send_update_extent(sctx, offset, end - offset);
5190 p = fs_path_alloc();
5193 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5195 goto tlv_put_failure;
5196 while (offset < end) {
5197 u64 len = min(end - offset, read_size);
5199 ret = begin_cmd(sctx, BTRFS_SEND_C_WRITE);
5202 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5203 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5204 ret = put_data_header(sctx, len);
5207 memset(sctx->send_buf + sctx->send_size, 0, len);
5208 sctx->send_size += len;
5209 ret = send_cmd(sctx);
5214 sctx->cur_inode_next_write_offset = offset;
5220 static int send_extent_data(struct send_ctx *sctx,
5224 u64 read_size = max_send_read_size(sctx);
5227 if (sctx->flags & BTRFS_SEND_FLAG_NO_FILE_DATA)
5228 return send_update_extent(sctx, offset, len);
5230 while (sent < len) {
5231 u64 size = min(len - sent, read_size);
5234 ret = send_write(sctx, offset + sent, size);
5243 * Search for a capability xattr related to sctx->cur_ino. If the capability is
5244 * found, call send_set_xattr function to emit it.
5246 * Return 0 if there isn't a capability, or when the capability was emitted
5247 * successfully, or < 0 if an error occurred.
5249 static int send_capabilities(struct send_ctx *sctx)
5251 struct fs_path *fspath = NULL;
5252 struct btrfs_path *path;
5253 struct btrfs_dir_item *di;
5254 struct extent_buffer *leaf;
5255 unsigned long data_ptr;
5260 path = alloc_path_for_send();
5264 di = btrfs_lookup_xattr(NULL, sctx->send_root, path, sctx->cur_ino,
5265 XATTR_NAME_CAPS, strlen(XATTR_NAME_CAPS), 0);
5267 /* There is no xattr for this inode */
5269 } else if (IS_ERR(di)) {
5274 leaf = path->nodes[0];
5275 buf_len = btrfs_dir_data_len(leaf, di);
5277 fspath = fs_path_alloc();
5278 buf = kmalloc(buf_len, GFP_KERNEL);
5279 if (!fspath || !buf) {
5284 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, fspath);
5288 data_ptr = (unsigned long)(di + 1) + btrfs_dir_name_len(leaf, di);
5289 read_extent_buffer(leaf, buf, data_ptr, buf_len);
5291 ret = send_set_xattr(sctx, fspath, XATTR_NAME_CAPS,
5292 strlen(XATTR_NAME_CAPS), buf, buf_len);
5295 fs_path_free(fspath);
5296 btrfs_free_path(path);
5300 static int clone_range(struct send_ctx *sctx,
5301 struct clone_root *clone_root,
5302 const u64 disk_byte,
5307 struct btrfs_path *path;
5308 struct btrfs_key key;
5310 u64 clone_src_i_size = 0;
5313 * Prevent cloning from a zero offset with a length matching the sector
5314 * size because in some scenarios this will make the receiver fail.
5316 * For example, if in the source filesystem the extent at offset 0
5317 * has a length of sectorsize and it was written using direct IO, then
5318 * it can never be an inline extent (even if compression is enabled).
5319 * Then this extent can be cloned in the original filesystem to a non
5320 * zero file offset, but it may not be possible to clone in the
5321 * destination filesystem because it can be inlined due to compression
5322 * on the destination filesystem (as the receiver's write operations are
5323 * always done using buffered IO). The same happens when the original
5324 * filesystem does not have compression enabled but the destination
5327 if (clone_root->offset == 0 &&
5328 len == sctx->send_root->fs_info->sectorsize)
5329 return send_extent_data(sctx, offset, len);
5331 path = alloc_path_for_send();
5336 * There are inodes that have extents that lie behind its i_size. Don't
5337 * accept clones from these extents.
5339 ret = __get_inode_info(clone_root->root, path, clone_root->ino,
5340 &clone_src_i_size, NULL, NULL, NULL, NULL, NULL);
5341 btrfs_release_path(path);
5346 * We can't send a clone operation for the entire range if we find
5347 * extent items in the respective range in the source file that
5348 * refer to different extents or if we find holes.
5349 * So check for that and do a mix of clone and regular write/copy
5350 * operations if needed.
5354 * mkfs.btrfs -f /dev/sda
5355 * mount /dev/sda /mnt
5356 * xfs_io -f -c "pwrite -S 0xaa 0K 100K" /mnt/foo
5357 * cp --reflink=always /mnt/foo /mnt/bar
5358 * xfs_io -c "pwrite -S 0xbb 50K 50K" /mnt/foo
5359 * btrfs subvolume snapshot -r /mnt /mnt/snap
5361 * If when we send the snapshot and we are processing file bar (which
5362 * has a higher inode number than foo) we blindly send a clone operation
5363 * for the [0, 100K[ range from foo to bar, the receiver ends up getting
5364 * a file bar that matches the content of file foo - iow, doesn't match
5365 * the content from bar in the original filesystem.
5367 key.objectid = clone_root->ino;
5368 key.type = BTRFS_EXTENT_DATA_KEY;
5369 key.offset = clone_root->offset;
5370 ret = btrfs_search_slot(NULL, clone_root->root, &key, path, 0, 0);
5373 if (ret > 0 && path->slots[0] > 0) {
5374 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1);
5375 if (key.objectid == clone_root->ino &&
5376 key.type == BTRFS_EXTENT_DATA_KEY)
5381 struct extent_buffer *leaf = path->nodes[0];
5382 int slot = path->slots[0];
5383 struct btrfs_file_extent_item *ei;
5387 u64 clone_data_offset;
5389 if (slot >= btrfs_header_nritems(leaf)) {
5390 ret = btrfs_next_leaf(clone_root->root, path);
5398 btrfs_item_key_to_cpu(leaf, &key, slot);
5401 * We might have an implicit trailing hole (NO_HOLES feature
5402 * enabled). We deal with it after leaving this loop.
5404 if (key.objectid != clone_root->ino ||
5405 key.type != BTRFS_EXTENT_DATA_KEY)
5408 ei = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5409 type = btrfs_file_extent_type(leaf, ei);
5410 if (type == BTRFS_FILE_EXTENT_INLINE) {
5411 ext_len = btrfs_file_extent_ram_bytes(leaf, ei);
5412 ext_len = PAGE_ALIGN(ext_len);
5414 ext_len = btrfs_file_extent_num_bytes(leaf, ei);
5417 if (key.offset + ext_len <= clone_root->offset)
5420 if (key.offset > clone_root->offset) {
5421 /* Implicit hole, NO_HOLES feature enabled. */
5422 u64 hole_len = key.offset - clone_root->offset;
5426 ret = send_extent_data(sctx, offset, hole_len);
5434 clone_root->offset += hole_len;
5435 data_offset += hole_len;
5438 if (key.offset >= clone_root->offset + len)
5441 if (key.offset >= clone_src_i_size)
5444 if (key.offset + ext_len > clone_src_i_size)
5445 ext_len = clone_src_i_size - key.offset;
5447 clone_data_offset = btrfs_file_extent_offset(leaf, ei);
5448 if (btrfs_file_extent_disk_bytenr(leaf, ei) == disk_byte) {
5449 clone_root->offset = key.offset;
5450 if (clone_data_offset < data_offset &&
5451 clone_data_offset + ext_len > data_offset) {
5454 extent_offset = data_offset - clone_data_offset;
5455 ext_len -= extent_offset;
5456 clone_data_offset += extent_offset;
5457 clone_root->offset += extent_offset;
5461 clone_len = min_t(u64, ext_len, len);
5463 if (btrfs_file_extent_disk_bytenr(leaf, ei) == disk_byte &&
5464 clone_data_offset == data_offset) {
5465 const u64 src_end = clone_root->offset + clone_len;
5466 const u64 sectorsize = SZ_64K;
5469 * We can't clone the last block, when its size is not
5470 * sector size aligned, into the middle of a file. If we
5471 * do so, the receiver will get a failure (-EINVAL) when
5472 * trying to clone or will silently corrupt the data in
5473 * the destination file if it's on a kernel without the
5474 * fix introduced by commit ac765f83f1397646
5475 * ("Btrfs: fix data corruption due to cloning of eof
5478 * So issue a clone of the aligned down range plus a
5479 * regular write for the eof block, if we hit that case.
5481 * Also, we use the maximum possible sector size, 64K,
5482 * because we don't know what's the sector size of the
5483 * filesystem that receives the stream, so we have to
5484 * assume the largest possible sector size.
5486 if (src_end == clone_src_i_size &&
5487 !IS_ALIGNED(src_end, sectorsize) &&
5488 offset + clone_len < sctx->cur_inode_size) {
5491 slen = ALIGN_DOWN(src_end - clone_root->offset,
5494 ret = send_clone(sctx, offset, slen,
5499 ret = send_extent_data(sctx, offset + slen,
5502 ret = send_clone(sctx, offset, clone_len,
5506 ret = send_extent_data(sctx, offset, clone_len);
5515 offset += clone_len;
5516 clone_root->offset += clone_len;
5519 * If we are cloning from the file we are currently processing,
5520 * and using the send root as the clone root, we must stop once
5521 * the current clone offset reaches the current eof of the file
5522 * at the receiver, otherwise we would issue an invalid clone
5523 * operation (source range going beyond eof) and cause the
5524 * receiver to fail. So if we reach the current eof, bail out
5525 * and fallback to a regular write.
5527 if (clone_root->root == sctx->send_root &&
5528 clone_root->ino == sctx->cur_ino &&
5529 clone_root->offset >= sctx->cur_inode_next_write_offset)
5532 data_offset += clone_len;
5538 ret = send_extent_data(sctx, offset, len);
5542 btrfs_free_path(path);
5546 static int send_write_or_clone(struct send_ctx *sctx,
5547 struct btrfs_path *path,
5548 struct btrfs_key *key,
5549 struct clone_root *clone_root)
5552 u64 offset = key->offset;
5554 u64 bs = sctx->send_root->fs_info->sb->s_blocksize;
5556 end = min_t(u64, btrfs_file_extent_end(path), sctx->cur_inode_size);
5560 if (clone_root && IS_ALIGNED(end, bs)) {
5561 struct btrfs_file_extent_item *ei;
5565 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
5566 struct btrfs_file_extent_item);
5567 disk_byte = btrfs_file_extent_disk_bytenr(path->nodes[0], ei);
5568 data_offset = btrfs_file_extent_offset(path->nodes[0], ei);
5569 ret = clone_range(sctx, clone_root, disk_byte, data_offset,
5570 offset, end - offset);
5572 ret = send_extent_data(sctx, offset, end - offset);
5574 sctx->cur_inode_next_write_offset = end;
5578 static int is_extent_unchanged(struct send_ctx *sctx,
5579 struct btrfs_path *left_path,
5580 struct btrfs_key *ekey)
5583 struct btrfs_key key;
5584 struct btrfs_path *path = NULL;
5585 struct extent_buffer *eb;
5587 struct btrfs_key found_key;
5588 struct btrfs_file_extent_item *ei;
5593 u64 left_offset_fixed;
5601 path = alloc_path_for_send();
5605 eb = left_path->nodes[0];
5606 slot = left_path->slots[0];
5607 ei = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
5608 left_type = btrfs_file_extent_type(eb, ei);
5610 if (left_type != BTRFS_FILE_EXTENT_REG) {
5614 left_disknr = btrfs_file_extent_disk_bytenr(eb, ei);
5615 left_len = btrfs_file_extent_num_bytes(eb, ei);
5616 left_offset = btrfs_file_extent_offset(eb, ei);
5617 left_gen = btrfs_file_extent_generation(eb, ei);
5620 * Following comments will refer to these graphics. L is the left
5621 * extents which we are checking at the moment. 1-8 are the right
5622 * extents that we iterate.
5625 * |-1-|-2a-|-3-|-4-|-5-|-6-|
5628 * |--1--|-2b-|...(same as above)
5630 * Alternative situation. Happens on files where extents got split.
5632 * |-----------7-----------|-6-|
5634 * Alternative situation. Happens on files which got larger.
5637 * Nothing follows after 8.
5640 key.objectid = ekey->objectid;
5641 key.type = BTRFS_EXTENT_DATA_KEY;
5642 key.offset = ekey->offset;
5643 ret = btrfs_search_slot_for_read(sctx->parent_root, &key, path, 0, 0);
5652 * Handle special case where the right side has no extents at all.
5654 eb = path->nodes[0];
5655 slot = path->slots[0];
5656 btrfs_item_key_to_cpu(eb, &found_key, slot);
5657 if (found_key.objectid != key.objectid ||
5658 found_key.type != key.type) {
5659 /* If we're a hole then just pretend nothing changed */
5660 ret = (left_disknr) ? 0 : 1;
5665 * We're now on 2a, 2b or 7.
5668 while (key.offset < ekey->offset + left_len) {
5669 ei = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
5670 right_type = btrfs_file_extent_type(eb, ei);
5671 if (right_type != BTRFS_FILE_EXTENT_REG &&
5672 right_type != BTRFS_FILE_EXTENT_INLINE) {
5677 if (right_type == BTRFS_FILE_EXTENT_INLINE) {
5678 right_len = btrfs_file_extent_ram_bytes(eb, ei);
5679 right_len = PAGE_ALIGN(right_len);
5681 right_len = btrfs_file_extent_num_bytes(eb, ei);
5685 * Are we at extent 8? If yes, we know the extent is changed.
5686 * This may only happen on the first iteration.
5688 if (found_key.offset + right_len <= ekey->offset) {
5689 /* If we're a hole just pretend nothing changed */
5690 ret = (left_disknr) ? 0 : 1;
5695 * We just wanted to see if when we have an inline extent, what
5696 * follows it is a regular extent (wanted to check the above
5697 * condition for inline extents too). This should normally not
5698 * happen but it's possible for example when we have an inline
5699 * compressed extent representing data with a size matching
5700 * the page size (currently the same as sector size).
5702 if (right_type == BTRFS_FILE_EXTENT_INLINE) {
5707 right_disknr = btrfs_file_extent_disk_bytenr(eb, ei);
5708 right_offset = btrfs_file_extent_offset(eb, ei);
5709 right_gen = btrfs_file_extent_generation(eb, ei);
5711 left_offset_fixed = left_offset;
5712 if (key.offset < ekey->offset) {
5713 /* Fix the right offset for 2a and 7. */
5714 right_offset += ekey->offset - key.offset;
5716 /* Fix the left offset for all behind 2a and 2b */
5717 left_offset_fixed += key.offset - ekey->offset;
5721 * Check if we have the same extent.
5723 if (left_disknr != right_disknr ||
5724 left_offset_fixed != right_offset ||
5725 left_gen != right_gen) {
5731 * Go to the next extent.
5733 ret = btrfs_next_item(sctx->parent_root, path);
5737 eb = path->nodes[0];
5738 slot = path->slots[0];
5739 btrfs_item_key_to_cpu(eb, &found_key, slot);
5741 if (ret || found_key.objectid != key.objectid ||
5742 found_key.type != key.type) {
5743 key.offset += right_len;
5746 if (found_key.offset != key.offset + right_len) {
5754 * We're now behind the left extent (treat as unchanged) or at the end
5755 * of the right side (treat as changed).
5757 if (key.offset >= ekey->offset + left_len)
5764 btrfs_free_path(path);
5768 static int get_last_extent(struct send_ctx *sctx, u64 offset)
5770 struct btrfs_path *path;
5771 struct btrfs_root *root = sctx->send_root;
5772 struct btrfs_key key;
5775 path = alloc_path_for_send();
5779 sctx->cur_inode_last_extent = 0;
5781 key.objectid = sctx->cur_ino;
5782 key.type = BTRFS_EXTENT_DATA_KEY;
5783 key.offset = offset;
5784 ret = btrfs_search_slot_for_read(root, &key, path, 0, 1);
5788 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
5789 if (key.objectid != sctx->cur_ino || key.type != BTRFS_EXTENT_DATA_KEY)
5792 sctx->cur_inode_last_extent = btrfs_file_extent_end(path);
5794 btrfs_free_path(path);
5798 static int range_is_hole_in_parent(struct send_ctx *sctx,
5802 struct btrfs_path *path;
5803 struct btrfs_key key;
5804 struct btrfs_root *root = sctx->parent_root;
5805 u64 search_start = start;
5808 path = alloc_path_for_send();
5812 key.objectid = sctx->cur_ino;
5813 key.type = BTRFS_EXTENT_DATA_KEY;
5814 key.offset = search_start;
5815 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5818 if (ret > 0 && path->slots[0] > 0)
5821 while (search_start < end) {
5822 struct extent_buffer *leaf = path->nodes[0];
5823 int slot = path->slots[0];
5824 struct btrfs_file_extent_item *fi;
5827 if (slot >= btrfs_header_nritems(leaf)) {
5828 ret = btrfs_next_leaf(root, path);
5836 btrfs_item_key_to_cpu(leaf, &key, slot);
5837 if (key.objectid < sctx->cur_ino ||
5838 key.type < BTRFS_EXTENT_DATA_KEY)
5840 if (key.objectid > sctx->cur_ino ||
5841 key.type > BTRFS_EXTENT_DATA_KEY ||
5845 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5846 extent_end = btrfs_file_extent_end(path);
5847 if (extent_end <= start)
5849 if (btrfs_file_extent_disk_bytenr(leaf, fi) == 0) {
5850 search_start = extent_end;
5860 btrfs_free_path(path);
5864 static int maybe_send_hole(struct send_ctx *sctx, struct btrfs_path *path,
5865 struct btrfs_key *key)
5869 if (sctx->cur_ino != key->objectid || !need_send_hole(sctx))
5872 if (sctx->cur_inode_last_extent == (u64)-1) {
5873 ret = get_last_extent(sctx, key->offset - 1);
5878 if (path->slots[0] == 0 &&
5879 sctx->cur_inode_last_extent < key->offset) {
5881 * We might have skipped entire leafs that contained only
5882 * file extent items for our current inode. These leafs have
5883 * a generation number smaller (older) than the one in the
5884 * current leaf and the leaf our last extent came from, and
5885 * are located between these 2 leafs.
5887 ret = get_last_extent(sctx, key->offset - 1);
5892 if (sctx->cur_inode_last_extent < key->offset) {
5893 ret = range_is_hole_in_parent(sctx,
5894 sctx->cur_inode_last_extent,
5899 ret = send_hole(sctx, key->offset);
5903 sctx->cur_inode_last_extent = btrfs_file_extent_end(path);
5907 static int process_extent(struct send_ctx *sctx,
5908 struct btrfs_path *path,
5909 struct btrfs_key *key)
5911 struct clone_root *found_clone = NULL;
5914 if (S_ISLNK(sctx->cur_inode_mode))
5917 if (sctx->parent_root && !sctx->cur_inode_new) {
5918 ret = is_extent_unchanged(sctx, path, key);
5926 struct btrfs_file_extent_item *ei;
5929 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
5930 struct btrfs_file_extent_item);
5931 type = btrfs_file_extent_type(path->nodes[0], ei);
5932 if (type == BTRFS_FILE_EXTENT_PREALLOC ||
5933 type == BTRFS_FILE_EXTENT_REG) {
5935 * The send spec does not have a prealloc command yet,
5936 * so just leave a hole for prealloc'ed extents until
5937 * we have enough commands queued up to justify rev'ing
5940 if (type == BTRFS_FILE_EXTENT_PREALLOC) {
5945 /* Have a hole, just skip it. */
5946 if (btrfs_file_extent_disk_bytenr(path->nodes[0], ei) == 0) {
5953 ret = find_extent_clone(sctx, path, key->objectid, key->offset,
5954 sctx->cur_inode_size, &found_clone);
5955 if (ret != -ENOENT && ret < 0)
5958 ret = send_write_or_clone(sctx, path, key, found_clone);
5962 ret = maybe_send_hole(sctx, path, key);
5967 static int process_all_extents(struct send_ctx *sctx)
5970 struct btrfs_root *root;
5971 struct btrfs_path *path;
5972 struct btrfs_key key;
5973 struct btrfs_key found_key;
5974 struct extent_buffer *eb;
5977 root = sctx->send_root;
5978 path = alloc_path_for_send();
5982 key.objectid = sctx->cmp_key->objectid;
5983 key.type = BTRFS_EXTENT_DATA_KEY;
5985 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5990 eb = path->nodes[0];
5991 slot = path->slots[0];
5993 if (slot >= btrfs_header_nritems(eb)) {
5994 ret = btrfs_next_leaf(root, path);
5997 } else if (ret > 0) {
6004 btrfs_item_key_to_cpu(eb, &found_key, slot);
6006 if (found_key.objectid != key.objectid ||
6007 found_key.type != key.type) {
6012 ret = process_extent(sctx, path, &found_key);
6020 btrfs_free_path(path);
6024 static int process_recorded_refs_if_needed(struct send_ctx *sctx, int at_end,
6026 int *refs_processed)
6030 if (sctx->cur_ino == 0)
6032 if (!at_end && sctx->cur_ino == sctx->cmp_key->objectid &&
6033 sctx->cmp_key->type <= BTRFS_INODE_EXTREF_KEY)
6035 if (list_empty(&sctx->new_refs) && list_empty(&sctx->deleted_refs))
6038 ret = process_recorded_refs(sctx, pending_move);
6042 *refs_processed = 1;
6047 static int finish_inode_if_needed(struct send_ctx *sctx, int at_end)
6058 int need_truncate = 1;
6059 int pending_move = 0;
6060 int refs_processed = 0;
6062 if (sctx->ignore_cur_inode)
6065 ret = process_recorded_refs_if_needed(sctx, at_end, &pending_move,
6071 * We have processed the refs and thus need to advance send_progress.
6072 * Now, calls to get_cur_xxx will take the updated refs of the current
6073 * inode into account.
6075 * On the other hand, if our current inode is a directory and couldn't
6076 * be moved/renamed because its parent was renamed/moved too and it has
6077 * a higher inode number, we can only move/rename our current inode
6078 * after we moved/renamed its parent. Therefore in this case operate on
6079 * the old path (pre move/rename) of our current inode, and the
6080 * move/rename will be performed later.
6082 if (refs_processed && !pending_move)
6083 sctx->send_progress = sctx->cur_ino + 1;
6085 if (sctx->cur_ino == 0 || sctx->cur_inode_deleted)
6087 if (!at_end && sctx->cmp_key->objectid == sctx->cur_ino)
6090 ret = get_inode_info(sctx->send_root, sctx->cur_ino, NULL, NULL,
6091 &left_mode, &left_uid, &left_gid, NULL);
6095 if (!sctx->parent_root || sctx->cur_inode_new) {
6097 if (!S_ISLNK(sctx->cur_inode_mode))
6099 if (sctx->cur_inode_next_write_offset == sctx->cur_inode_size)
6104 ret = get_inode_info(sctx->parent_root, sctx->cur_ino,
6105 &old_size, NULL, &right_mode, &right_uid,
6110 if (left_uid != right_uid || left_gid != right_gid)
6112 if (!S_ISLNK(sctx->cur_inode_mode) && left_mode != right_mode)
6114 if ((old_size == sctx->cur_inode_size) ||
6115 (sctx->cur_inode_size > old_size &&
6116 sctx->cur_inode_next_write_offset == sctx->cur_inode_size))
6120 if (S_ISREG(sctx->cur_inode_mode)) {
6121 if (need_send_hole(sctx)) {
6122 if (sctx->cur_inode_last_extent == (u64)-1 ||
6123 sctx->cur_inode_last_extent <
6124 sctx->cur_inode_size) {
6125 ret = get_last_extent(sctx, (u64)-1);
6129 if (sctx->cur_inode_last_extent <
6130 sctx->cur_inode_size) {
6131 ret = send_hole(sctx, sctx->cur_inode_size);
6136 if (need_truncate) {
6137 ret = send_truncate(sctx, sctx->cur_ino,
6138 sctx->cur_inode_gen,
6139 sctx->cur_inode_size);
6146 ret = send_chown(sctx, sctx->cur_ino, sctx->cur_inode_gen,
6147 left_uid, left_gid);
6152 ret = send_chmod(sctx, sctx->cur_ino, sctx->cur_inode_gen,
6158 ret = send_capabilities(sctx);
6163 * If other directory inodes depended on our current directory
6164 * inode's move/rename, now do their move/rename operations.
6166 if (!is_waiting_for_move(sctx, sctx->cur_ino)) {
6167 ret = apply_children_dir_moves(sctx);
6171 * Need to send that every time, no matter if it actually
6172 * changed between the two trees as we have done changes to
6173 * the inode before. If our inode is a directory and it's
6174 * waiting to be moved/renamed, we will send its utimes when
6175 * it's moved/renamed, therefore we don't need to do it here.
6177 sctx->send_progress = sctx->cur_ino + 1;
6178 ret = send_utimes(sctx, sctx->cur_ino, sctx->cur_inode_gen);
6187 struct parent_paths_ctx {
6188 struct list_head *refs;
6189 struct send_ctx *sctx;
6192 static int record_parent_ref(int num, u64 dir, int index, struct fs_path *name,
6195 struct parent_paths_ctx *ppctx = ctx;
6197 return record_ref(ppctx->sctx->parent_root, dir, name, ppctx->sctx,
6202 * Issue unlink operations for all paths of the current inode found in the
6205 static int btrfs_unlink_all_paths(struct send_ctx *sctx)
6207 LIST_HEAD(deleted_refs);
6208 struct btrfs_path *path;
6209 struct btrfs_key key;
6210 struct parent_paths_ctx ctx;
6213 path = alloc_path_for_send();
6217 key.objectid = sctx->cur_ino;
6218 key.type = BTRFS_INODE_REF_KEY;
6220 ret = btrfs_search_slot(NULL, sctx->parent_root, &key, path, 0, 0);
6224 ctx.refs = &deleted_refs;
6228 struct extent_buffer *eb = path->nodes[0];
6229 int slot = path->slots[0];
6231 if (slot >= btrfs_header_nritems(eb)) {
6232 ret = btrfs_next_leaf(sctx->parent_root, path);
6240 btrfs_item_key_to_cpu(eb, &key, slot);
6241 if (key.objectid != sctx->cur_ino)
6243 if (key.type != BTRFS_INODE_REF_KEY &&
6244 key.type != BTRFS_INODE_EXTREF_KEY)
6247 ret = iterate_inode_ref(sctx->parent_root, path, &key, 1,
6248 record_parent_ref, &ctx);
6255 while (!list_empty(&deleted_refs)) {
6256 struct recorded_ref *ref;
6258 ref = list_first_entry(&deleted_refs, struct recorded_ref, list);
6259 ret = send_unlink(sctx, ref->full_path);
6262 fs_path_free(ref->full_path);
6263 list_del(&ref->list);
6268 btrfs_free_path(path);
6270 __free_recorded_refs(&deleted_refs);
6274 static int changed_inode(struct send_ctx *sctx,
6275 enum btrfs_compare_tree_result result)
6278 struct btrfs_key *key = sctx->cmp_key;
6279 struct btrfs_inode_item *left_ii = NULL;
6280 struct btrfs_inode_item *right_ii = NULL;
6284 sctx->cur_ino = key->objectid;
6285 sctx->cur_inode_new_gen = 0;
6286 sctx->cur_inode_last_extent = (u64)-1;
6287 sctx->cur_inode_next_write_offset = 0;
6288 sctx->ignore_cur_inode = false;
6291 * Set send_progress to current inode. This will tell all get_cur_xxx
6292 * functions that the current inode's refs are not updated yet. Later,
6293 * when process_recorded_refs is finished, it is set to cur_ino + 1.
6295 sctx->send_progress = sctx->cur_ino;
6297 if (result == BTRFS_COMPARE_TREE_NEW ||
6298 result == BTRFS_COMPARE_TREE_CHANGED) {
6299 left_ii = btrfs_item_ptr(sctx->left_path->nodes[0],
6300 sctx->left_path->slots[0],
6301 struct btrfs_inode_item);
6302 left_gen = btrfs_inode_generation(sctx->left_path->nodes[0],
6305 right_ii = btrfs_item_ptr(sctx->right_path->nodes[0],
6306 sctx->right_path->slots[0],
6307 struct btrfs_inode_item);
6308 right_gen = btrfs_inode_generation(sctx->right_path->nodes[0],
6311 if (result == BTRFS_COMPARE_TREE_CHANGED) {
6312 right_ii = btrfs_item_ptr(sctx->right_path->nodes[0],
6313 sctx->right_path->slots[0],
6314 struct btrfs_inode_item);
6316 right_gen = btrfs_inode_generation(sctx->right_path->nodes[0],
6320 * The cur_ino = root dir case is special here. We can't treat
6321 * the inode as deleted+reused because it would generate a
6322 * stream that tries to delete/mkdir the root dir.
6324 if (left_gen != right_gen &&
6325 sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID)
6326 sctx->cur_inode_new_gen = 1;
6330 * Normally we do not find inodes with a link count of zero (orphans)
6331 * because the most common case is to create a snapshot and use it
6332 * for a send operation. However other less common use cases involve
6333 * using a subvolume and send it after turning it to RO mode just
6334 * after deleting all hard links of a file while holding an open
6335 * file descriptor against it or turning a RO snapshot into RW mode,
6336 * keep an open file descriptor against a file, delete it and then
6337 * turn the snapshot back to RO mode before using it for a send
6338 * operation. So if we find such cases, ignore the inode and all its
6339 * items completely if it's a new inode, or if it's a changed inode
6340 * make sure all its previous paths (from the parent snapshot) are all
6341 * unlinked and all other the inode items are ignored.
6343 if (result == BTRFS_COMPARE_TREE_NEW ||
6344 result == BTRFS_COMPARE_TREE_CHANGED) {
6347 nlinks = btrfs_inode_nlink(sctx->left_path->nodes[0], left_ii);
6349 sctx->ignore_cur_inode = true;
6350 if (result == BTRFS_COMPARE_TREE_CHANGED)
6351 ret = btrfs_unlink_all_paths(sctx);
6356 if (result == BTRFS_COMPARE_TREE_NEW) {
6357 sctx->cur_inode_gen = left_gen;
6358 sctx->cur_inode_new = 1;
6359 sctx->cur_inode_deleted = 0;
6360 sctx->cur_inode_size = btrfs_inode_size(
6361 sctx->left_path->nodes[0], left_ii);
6362 sctx->cur_inode_mode = btrfs_inode_mode(
6363 sctx->left_path->nodes[0], left_ii);
6364 sctx->cur_inode_rdev = btrfs_inode_rdev(
6365 sctx->left_path->nodes[0], left_ii);
6366 if (sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID)
6367 ret = send_create_inode_if_needed(sctx);
6368 } else if (result == BTRFS_COMPARE_TREE_DELETED) {
6369 sctx->cur_inode_gen = right_gen;
6370 sctx->cur_inode_new = 0;
6371 sctx->cur_inode_deleted = 1;
6372 sctx->cur_inode_size = btrfs_inode_size(
6373 sctx->right_path->nodes[0], right_ii);
6374 sctx->cur_inode_mode = btrfs_inode_mode(
6375 sctx->right_path->nodes[0], right_ii);
6376 } else if (result == BTRFS_COMPARE_TREE_CHANGED) {
6378 * We need to do some special handling in case the inode was
6379 * reported as changed with a changed generation number. This
6380 * means that the original inode was deleted and new inode
6381 * reused the same inum. So we have to treat the old inode as
6382 * deleted and the new one as new.
6384 if (sctx->cur_inode_new_gen) {
6386 * First, process the inode as if it was deleted.
6388 sctx->cur_inode_gen = right_gen;
6389 sctx->cur_inode_new = 0;
6390 sctx->cur_inode_deleted = 1;
6391 sctx->cur_inode_size = btrfs_inode_size(
6392 sctx->right_path->nodes[0], right_ii);
6393 sctx->cur_inode_mode = btrfs_inode_mode(
6394 sctx->right_path->nodes[0], right_ii);
6395 ret = process_all_refs(sctx,
6396 BTRFS_COMPARE_TREE_DELETED);
6401 * Now process the inode as if it was new.
6403 sctx->cur_inode_gen = left_gen;
6404 sctx->cur_inode_new = 1;
6405 sctx->cur_inode_deleted = 0;
6406 sctx->cur_inode_size = btrfs_inode_size(
6407 sctx->left_path->nodes[0], left_ii);
6408 sctx->cur_inode_mode = btrfs_inode_mode(
6409 sctx->left_path->nodes[0], left_ii);
6410 sctx->cur_inode_rdev = btrfs_inode_rdev(
6411 sctx->left_path->nodes[0], left_ii);
6412 ret = send_create_inode_if_needed(sctx);
6416 ret = process_all_refs(sctx, BTRFS_COMPARE_TREE_NEW);
6420 * Advance send_progress now as we did not get into
6421 * process_recorded_refs_if_needed in the new_gen case.
6423 sctx->send_progress = sctx->cur_ino + 1;
6426 * Now process all extents and xattrs of the inode as if
6427 * they were all new.
6429 ret = process_all_extents(sctx);
6432 ret = process_all_new_xattrs(sctx);
6436 sctx->cur_inode_gen = left_gen;
6437 sctx->cur_inode_new = 0;
6438 sctx->cur_inode_new_gen = 0;
6439 sctx->cur_inode_deleted = 0;
6440 sctx->cur_inode_size = btrfs_inode_size(
6441 sctx->left_path->nodes[0], left_ii);
6442 sctx->cur_inode_mode = btrfs_inode_mode(
6443 sctx->left_path->nodes[0], left_ii);
6452 * We have to process new refs before deleted refs, but compare_trees gives us
6453 * the new and deleted refs mixed. To fix this, we record the new/deleted refs
6454 * first and later process them in process_recorded_refs.
6455 * For the cur_inode_new_gen case, we skip recording completely because
6456 * changed_inode did already initiate processing of refs. The reason for this is
6457 * that in this case, compare_tree actually compares the refs of 2 different
6458 * inodes. To fix this, process_all_refs is used in changed_inode to handle all
6459 * refs of the right tree as deleted and all refs of the left tree as new.
6461 static int changed_ref(struct send_ctx *sctx,
6462 enum btrfs_compare_tree_result result)
6466 if (sctx->cur_ino != sctx->cmp_key->objectid) {
6467 inconsistent_snapshot_error(sctx, result, "reference");
6471 if (!sctx->cur_inode_new_gen &&
6472 sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID) {
6473 if (result == BTRFS_COMPARE_TREE_NEW)
6474 ret = record_new_ref(sctx);
6475 else if (result == BTRFS_COMPARE_TREE_DELETED)
6476 ret = record_deleted_ref(sctx);
6477 else if (result == BTRFS_COMPARE_TREE_CHANGED)
6478 ret = record_changed_ref(sctx);
6485 * Process new/deleted/changed xattrs. We skip processing in the
6486 * cur_inode_new_gen case because changed_inode did already initiate processing
6487 * of xattrs. The reason is the same as in changed_ref
6489 static int changed_xattr(struct send_ctx *sctx,
6490 enum btrfs_compare_tree_result result)
6494 if (sctx->cur_ino != sctx->cmp_key->objectid) {
6495 inconsistent_snapshot_error(sctx, result, "xattr");
6499 if (!sctx->cur_inode_new_gen && !sctx->cur_inode_deleted) {
6500 if (result == BTRFS_COMPARE_TREE_NEW)
6501 ret = process_new_xattr(sctx);
6502 else if (result == BTRFS_COMPARE_TREE_DELETED)
6503 ret = process_deleted_xattr(sctx);
6504 else if (result == BTRFS_COMPARE_TREE_CHANGED)
6505 ret = process_changed_xattr(sctx);
6512 * Process new/deleted/changed extents. We skip processing in the
6513 * cur_inode_new_gen case because changed_inode did already initiate processing
6514 * of extents. The reason is the same as in changed_ref
6516 static int changed_extent(struct send_ctx *sctx,
6517 enum btrfs_compare_tree_result result)
6522 * We have found an extent item that changed without the inode item
6523 * having changed. This can happen either after relocation (where the
6524 * disk_bytenr of an extent item is replaced at
6525 * relocation.c:replace_file_extents()) or after deduplication into a
6526 * file in both the parent and send snapshots (where an extent item can
6527 * get modified or replaced with a new one). Note that deduplication
6528 * updates the inode item, but it only changes the iversion (sequence
6529 * field in the inode item) of the inode, so if a file is deduplicated
6530 * the same amount of times in both the parent and send snapshots, its
6531 * iversion becomes the same in both snapshots, whence the inode item is
6532 * the same on both snapshots.
6534 if (sctx->cur_ino != sctx->cmp_key->objectid)
6537 if (!sctx->cur_inode_new_gen && !sctx->cur_inode_deleted) {
6538 if (result != BTRFS_COMPARE_TREE_DELETED)
6539 ret = process_extent(sctx, sctx->left_path,
6546 static int dir_changed(struct send_ctx *sctx, u64 dir)
6548 u64 orig_gen, new_gen;
6551 ret = get_inode_info(sctx->send_root, dir, NULL, &new_gen, NULL, NULL,
6556 ret = get_inode_info(sctx->parent_root, dir, NULL, &orig_gen, NULL,
6561 return (orig_gen != new_gen) ? 1 : 0;
6564 static int compare_refs(struct send_ctx *sctx, struct btrfs_path *path,
6565 struct btrfs_key *key)
6567 struct btrfs_inode_extref *extref;
6568 struct extent_buffer *leaf;
6569 u64 dirid = 0, last_dirid = 0;
6576 /* Easy case, just check this one dirid */
6577 if (key->type == BTRFS_INODE_REF_KEY) {
6578 dirid = key->offset;
6580 ret = dir_changed(sctx, dirid);
6584 leaf = path->nodes[0];
6585 item_size = btrfs_item_size(leaf, path->slots[0]);
6586 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
6587 while (cur_offset < item_size) {
6588 extref = (struct btrfs_inode_extref *)(ptr +
6590 dirid = btrfs_inode_extref_parent(leaf, extref);
6591 ref_name_len = btrfs_inode_extref_name_len(leaf, extref);
6592 cur_offset += ref_name_len + sizeof(*extref);
6593 if (dirid == last_dirid)
6595 ret = dir_changed(sctx, dirid);
6605 * Updates compare related fields in sctx and simply forwards to the actual
6606 * changed_xxx functions.
6608 static int changed_cb(struct btrfs_path *left_path,
6609 struct btrfs_path *right_path,
6610 struct btrfs_key *key,
6611 enum btrfs_compare_tree_result result,
6612 struct send_ctx *sctx)
6617 * We can not hold the commit root semaphore here. This is because in
6618 * the case of sending and receiving to the same filesystem, using a
6619 * pipe, could result in a deadlock:
6621 * 1) The task running send blocks on the pipe because it's full;
6623 * 2) The task running receive, which is the only consumer of the pipe,
6624 * is waiting for a transaction commit (for example due to a space
6625 * reservation when doing a write or triggering a transaction commit
6626 * when creating a subvolume);
6628 * 3) The transaction is waiting to write lock the commit root semaphore,
6629 * but can not acquire it since it's being held at 1).
6631 * Down this call chain we write to the pipe through kernel_write().
6632 * The same type of problem can also happen when sending to a file that
6633 * is stored in the same filesystem - when reserving space for a write
6634 * into the file, we can trigger a transaction commit.
6636 * Our caller has supplied us with clones of leaves from the send and
6637 * parent roots, so we're safe here from a concurrent relocation and
6638 * further reallocation of metadata extents while we are here. Below we
6639 * also assert that the leaves are clones.
6641 lockdep_assert_not_held(&sctx->send_root->fs_info->commit_root_sem);
6644 * We always have a send root, so left_path is never NULL. We will not
6645 * have a leaf when we have reached the end of the send root but have
6646 * not yet reached the end of the parent root.
6648 if (left_path->nodes[0])
6649 ASSERT(test_bit(EXTENT_BUFFER_UNMAPPED,
6650 &left_path->nodes[0]->bflags));
6652 * When doing a full send we don't have a parent root, so right_path is
6653 * NULL. When doing an incremental send, we may have reached the end of
6654 * the parent root already, so we don't have a leaf at right_path.
6656 if (right_path && right_path->nodes[0])
6657 ASSERT(test_bit(EXTENT_BUFFER_UNMAPPED,
6658 &right_path->nodes[0]->bflags));
6660 if (result == BTRFS_COMPARE_TREE_SAME) {
6661 if (key->type == BTRFS_INODE_REF_KEY ||
6662 key->type == BTRFS_INODE_EXTREF_KEY) {
6663 ret = compare_refs(sctx, left_path, key);
6668 } else if (key->type == BTRFS_EXTENT_DATA_KEY) {
6669 return maybe_send_hole(sctx, left_path, key);
6673 result = BTRFS_COMPARE_TREE_CHANGED;
6677 sctx->left_path = left_path;
6678 sctx->right_path = right_path;
6679 sctx->cmp_key = key;
6681 ret = finish_inode_if_needed(sctx, 0);
6685 /* Ignore non-FS objects */
6686 if (key->objectid == BTRFS_FREE_INO_OBJECTID ||
6687 key->objectid == BTRFS_FREE_SPACE_OBJECTID)
6690 if (key->type == BTRFS_INODE_ITEM_KEY) {
6691 ret = changed_inode(sctx, result);
6692 } else if (!sctx->ignore_cur_inode) {
6693 if (key->type == BTRFS_INODE_REF_KEY ||
6694 key->type == BTRFS_INODE_EXTREF_KEY)
6695 ret = changed_ref(sctx, result);
6696 else if (key->type == BTRFS_XATTR_ITEM_KEY)
6697 ret = changed_xattr(sctx, result);
6698 else if (key->type == BTRFS_EXTENT_DATA_KEY)
6699 ret = changed_extent(sctx, result);
6706 static int search_key_again(const struct send_ctx *sctx,
6707 struct btrfs_root *root,
6708 struct btrfs_path *path,
6709 const struct btrfs_key *key)
6713 if (!path->need_commit_sem)
6714 lockdep_assert_held_read(&root->fs_info->commit_root_sem);
6717 * Roots used for send operations are readonly and no one can add,
6718 * update or remove keys from them, so we should be able to find our
6719 * key again. The only exception is deduplication, which can operate on
6720 * readonly roots and add, update or remove keys to/from them - but at
6721 * the moment we don't allow it to run in parallel with send.
6723 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
6726 btrfs_print_tree(path->nodes[path->lowest_level], false);
6727 btrfs_err(root->fs_info,
6728 "send: key (%llu %u %llu) not found in %s root %llu, lowest_level %d, slot %d",
6729 key->objectid, key->type, key->offset,
6730 (root == sctx->parent_root ? "parent" : "send"),
6731 root->root_key.objectid, path->lowest_level,
6732 path->slots[path->lowest_level]);
6739 static int full_send_tree(struct send_ctx *sctx)
6742 struct btrfs_root *send_root = sctx->send_root;
6743 struct btrfs_key key;
6744 struct btrfs_fs_info *fs_info = send_root->fs_info;
6745 struct btrfs_path *path;
6747 path = alloc_path_for_send();
6750 path->reada = READA_FORWARD_ALWAYS;
6752 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
6753 key.type = BTRFS_INODE_ITEM_KEY;
6756 down_read(&fs_info->commit_root_sem);
6757 sctx->last_reloc_trans = fs_info->last_reloc_trans;
6758 up_read(&fs_info->commit_root_sem);
6760 ret = btrfs_search_slot_for_read(send_root, &key, path, 1, 0);
6767 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
6769 ret = changed_cb(path, NULL, &key,
6770 BTRFS_COMPARE_TREE_NEW, sctx);
6774 down_read(&fs_info->commit_root_sem);
6775 if (fs_info->last_reloc_trans > sctx->last_reloc_trans) {
6776 sctx->last_reloc_trans = fs_info->last_reloc_trans;
6777 up_read(&fs_info->commit_root_sem);
6779 * A transaction used for relocating a block group was
6780 * committed or is about to finish its commit. Release
6781 * our path (leaf) and restart the search, so that we
6782 * avoid operating on any file extent items that are
6783 * stale, with a disk_bytenr that reflects a pre
6784 * relocation value. This way we avoid as much as
6785 * possible to fallback to regular writes when checking
6786 * if we can clone file ranges.
6788 btrfs_release_path(path);
6789 ret = search_key_again(sctx, send_root, path, &key);
6793 up_read(&fs_info->commit_root_sem);
6796 ret = btrfs_next_item(send_root, path);
6806 ret = finish_inode_if_needed(sctx, 1);
6809 btrfs_free_path(path);
6813 static int replace_node_with_clone(struct btrfs_path *path, int level)
6815 struct extent_buffer *clone;
6817 clone = btrfs_clone_extent_buffer(path->nodes[level]);
6821 free_extent_buffer(path->nodes[level]);
6822 path->nodes[level] = clone;
6827 static int tree_move_down(struct btrfs_path *path, int *level, u64 reada_min_gen)
6829 struct extent_buffer *eb;
6830 struct extent_buffer *parent = path->nodes[*level];
6831 int slot = path->slots[*level];
6832 const int nritems = btrfs_header_nritems(parent);
6836 lockdep_assert_held_read(&parent->fs_info->commit_root_sem);
6838 BUG_ON(*level == 0);
6839 eb = btrfs_read_node_slot(parent, slot);
6844 * Trigger readahead for the next leaves we will process, so that it is
6845 * very likely that when we need them they are already in memory and we
6846 * will not block on disk IO. For nodes we only do readahead for one,
6847 * since the time window between processing nodes is typically larger.
6849 reada_max = (*level == 1 ? SZ_128K : eb->fs_info->nodesize);
6851 for (slot++; slot < nritems && reada_done < reada_max; slot++) {
6852 if (btrfs_node_ptr_generation(parent, slot) > reada_min_gen) {
6853 btrfs_readahead_node_child(parent, slot);
6854 reada_done += eb->fs_info->nodesize;
6858 path->nodes[*level - 1] = eb;
6859 path->slots[*level - 1] = 0;
6863 return replace_node_with_clone(path, 0);
6868 static int tree_move_next_or_upnext(struct btrfs_path *path,
6869 int *level, int root_level)
6873 nritems = btrfs_header_nritems(path->nodes[*level]);
6875 path->slots[*level]++;
6877 while (path->slots[*level] >= nritems) {
6878 if (*level == root_level) {
6879 path->slots[*level] = nritems - 1;
6884 path->slots[*level] = 0;
6885 free_extent_buffer(path->nodes[*level]);
6886 path->nodes[*level] = NULL;
6888 path->slots[*level]++;
6890 nritems = btrfs_header_nritems(path->nodes[*level]);
6897 * Returns 1 if it had to move up and next. 0 is returned if it moved only next
6900 static int tree_advance(struct btrfs_path *path,
6901 int *level, int root_level,
6903 struct btrfs_key *key,
6908 if (*level == 0 || !allow_down) {
6909 ret = tree_move_next_or_upnext(path, level, root_level);
6911 ret = tree_move_down(path, level, reada_min_gen);
6915 * Even if we have reached the end of a tree, ret is -1, update the key
6916 * anyway, so that in case we need to restart due to a block group
6917 * relocation, we can assert that the last key of the root node still
6918 * exists in the tree.
6921 btrfs_item_key_to_cpu(path->nodes[*level], key,
6922 path->slots[*level]);
6924 btrfs_node_key_to_cpu(path->nodes[*level], key,
6925 path->slots[*level]);
6930 static int tree_compare_item(struct btrfs_path *left_path,
6931 struct btrfs_path *right_path,
6936 unsigned long off1, off2;
6938 len1 = btrfs_item_size(left_path->nodes[0], left_path->slots[0]);
6939 len2 = btrfs_item_size(right_path->nodes[0], right_path->slots[0]);
6943 off1 = btrfs_item_ptr_offset(left_path->nodes[0], left_path->slots[0]);
6944 off2 = btrfs_item_ptr_offset(right_path->nodes[0],
6945 right_path->slots[0]);
6947 read_extent_buffer(left_path->nodes[0], tmp_buf, off1, len1);
6949 cmp = memcmp_extent_buffer(right_path->nodes[0], tmp_buf, off2, len1);
6956 * A transaction used for relocating a block group was committed or is about to
6957 * finish its commit. Release our paths and restart the search, so that we are
6958 * not using stale extent buffers:
6960 * 1) For levels > 0, we are only holding references of extent buffers, without
6961 * any locks on them, which does not prevent them from having been relocated
6962 * and reallocated after the last time we released the commit root semaphore.
6963 * The exception are the root nodes, for which we always have a clone, see
6964 * the comment at btrfs_compare_trees();
6966 * 2) For leaves, level 0, we are holding copies (clones) of extent buffers, so
6967 * we are safe from the concurrent relocation and reallocation. However they
6968 * can have file extent items with a pre relocation disk_bytenr value, so we
6969 * restart the start from the current commit roots and clone the new leaves so
6970 * that we get the post relocation disk_bytenr values. Not doing so, could
6971 * make us clone the wrong data in case there are new extents using the old
6972 * disk_bytenr that happen to be shared.
6974 static int restart_after_relocation(struct btrfs_path *left_path,
6975 struct btrfs_path *right_path,
6976 const struct btrfs_key *left_key,
6977 const struct btrfs_key *right_key,
6980 const struct send_ctx *sctx)
6985 lockdep_assert_held_read(&sctx->send_root->fs_info->commit_root_sem);
6987 btrfs_release_path(left_path);
6988 btrfs_release_path(right_path);
6991 * Since keys can not be added or removed to/from our roots because they
6992 * are readonly and we do not allow deduplication to run in parallel
6993 * (which can add, remove or change keys), the layout of the trees should
6996 left_path->lowest_level = left_level;
6997 ret = search_key_again(sctx, sctx->send_root, left_path, left_key);
7001 right_path->lowest_level = right_level;
7002 ret = search_key_again(sctx, sctx->parent_root, right_path, right_key);
7007 * If the lowest level nodes are leaves, clone them so that they can be
7008 * safely used by changed_cb() while not under the protection of the
7009 * commit root semaphore, even if relocation and reallocation happens in
7012 if (left_level == 0) {
7013 ret = replace_node_with_clone(left_path, 0);
7018 if (right_level == 0) {
7019 ret = replace_node_with_clone(right_path, 0);
7025 * Now clone the root nodes (unless they happen to be the leaves we have
7026 * already cloned). This is to protect against concurrent snapshotting of
7027 * the send and parent roots (see the comment at btrfs_compare_trees()).
7029 root_level = btrfs_header_level(sctx->send_root->commit_root);
7030 if (root_level > 0) {
7031 ret = replace_node_with_clone(left_path, root_level);
7036 root_level = btrfs_header_level(sctx->parent_root->commit_root);
7037 if (root_level > 0) {
7038 ret = replace_node_with_clone(right_path, root_level);
7047 * This function compares two trees and calls the provided callback for
7048 * every changed/new/deleted item it finds.
7049 * If shared tree blocks are encountered, whole subtrees are skipped, making
7050 * the compare pretty fast on snapshotted subvolumes.
7052 * This currently works on commit roots only. As commit roots are read only,
7053 * we don't do any locking. The commit roots are protected with transactions.
7054 * Transactions are ended and rejoined when a commit is tried in between.
7056 * This function checks for modifications done to the trees while comparing.
7057 * If it detects a change, it aborts immediately.
7059 static int btrfs_compare_trees(struct btrfs_root *left_root,
7060 struct btrfs_root *right_root, struct send_ctx *sctx)
7062 struct btrfs_fs_info *fs_info = left_root->fs_info;
7065 struct btrfs_path *left_path = NULL;
7066 struct btrfs_path *right_path = NULL;
7067 struct btrfs_key left_key;
7068 struct btrfs_key right_key;
7069 char *tmp_buf = NULL;
7070 int left_root_level;
7071 int right_root_level;
7074 int left_end_reached = 0;
7075 int right_end_reached = 0;
7076 int advance_left = 0;
7077 int advance_right = 0;
7084 left_path = btrfs_alloc_path();
7089 right_path = btrfs_alloc_path();
7095 tmp_buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
7101 left_path->search_commit_root = 1;
7102 left_path->skip_locking = 1;
7103 right_path->search_commit_root = 1;
7104 right_path->skip_locking = 1;
7107 * Strategy: Go to the first items of both trees. Then do
7109 * If both trees are at level 0
7110 * Compare keys of current items
7111 * If left < right treat left item as new, advance left tree
7113 * If left > right treat right item as deleted, advance right tree
7115 * If left == right do deep compare of items, treat as changed if
7116 * needed, advance both trees and repeat
7117 * If both trees are at the same level but not at level 0
7118 * Compare keys of current nodes/leafs
7119 * If left < right advance left tree and repeat
7120 * If left > right advance right tree and repeat
7121 * If left == right compare blockptrs of the next nodes/leafs
7122 * If they match advance both trees but stay at the same level
7124 * If they don't match advance both trees while allowing to go
7126 * If tree levels are different
7127 * Advance the tree that needs it and repeat
7129 * Advancing a tree means:
7130 * If we are at level 0, try to go to the next slot. If that's not
7131 * possible, go one level up and repeat. Stop when we found a level
7132 * where we could go to the next slot. We may at this point be on a
7135 * If we are not at level 0 and not on shared tree blocks, go one
7138 * If we are not at level 0 and on shared tree blocks, go one slot to
7139 * the right if possible or go up and right.
7142 down_read(&fs_info->commit_root_sem);
7143 left_level = btrfs_header_level(left_root->commit_root);
7144 left_root_level = left_level;
7146 * We clone the root node of the send and parent roots to prevent races
7147 * with snapshot creation of these roots. Snapshot creation COWs the
7148 * root node of a tree, so after the transaction is committed the old
7149 * extent can be reallocated while this send operation is still ongoing.
7150 * So we clone them, under the commit root semaphore, to be race free.
7152 left_path->nodes[left_level] =
7153 btrfs_clone_extent_buffer(left_root->commit_root);
7154 if (!left_path->nodes[left_level]) {
7159 right_level = btrfs_header_level(right_root->commit_root);
7160 right_root_level = right_level;
7161 right_path->nodes[right_level] =
7162 btrfs_clone_extent_buffer(right_root->commit_root);
7163 if (!right_path->nodes[right_level]) {
7168 * Our right root is the parent root, while the left root is the "send"
7169 * root. We know that all new nodes/leaves in the left root must have
7170 * a generation greater than the right root's generation, so we trigger
7171 * readahead for those nodes and leaves of the left root, as we know we
7172 * will need to read them at some point.
7174 reada_min_gen = btrfs_header_generation(right_root->commit_root);
7176 if (left_level == 0)
7177 btrfs_item_key_to_cpu(left_path->nodes[left_level],
7178 &left_key, left_path->slots[left_level]);
7180 btrfs_node_key_to_cpu(left_path->nodes[left_level],
7181 &left_key, left_path->slots[left_level]);
7182 if (right_level == 0)
7183 btrfs_item_key_to_cpu(right_path->nodes[right_level],
7184 &right_key, right_path->slots[right_level]);
7186 btrfs_node_key_to_cpu(right_path->nodes[right_level],
7187 &right_key, right_path->slots[right_level]);
7189 sctx->last_reloc_trans = fs_info->last_reloc_trans;
7192 if (need_resched() ||
7193 rwsem_is_contended(&fs_info->commit_root_sem)) {
7194 up_read(&fs_info->commit_root_sem);
7196 down_read(&fs_info->commit_root_sem);
7199 if (fs_info->last_reloc_trans > sctx->last_reloc_trans) {
7200 ret = restart_after_relocation(left_path, right_path,
7201 &left_key, &right_key,
7202 left_level, right_level,
7206 sctx->last_reloc_trans = fs_info->last_reloc_trans;
7209 if (advance_left && !left_end_reached) {
7210 ret = tree_advance(left_path, &left_level,
7212 advance_left != ADVANCE_ONLY_NEXT,
7213 &left_key, reada_min_gen);
7215 left_end_reached = ADVANCE;
7220 if (advance_right && !right_end_reached) {
7221 ret = tree_advance(right_path, &right_level,
7223 advance_right != ADVANCE_ONLY_NEXT,
7224 &right_key, reada_min_gen);
7226 right_end_reached = ADVANCE;
7232 if (left_end_reached && right_end_reached) {
7235 } else if (left_end_reached) {
7236 if (right_level == 0) {
7237 up_read(&fs_info->commit_root_sem);
7238 ret = changed_cb(left_path, right_path,
7240 BTRFS_COMPARE_TREE_DELETED,
7244 down_read(&fs_info->commit_root_sem);
7246 advance_right = ADVANCE;
7248 } else if (right_end_reached) {
7249 if (left_level == 0) {
7250 up_read(&fs_info->commit_root_sem);
7251 ret = changed_cb(left_path, right_path,
7253 BTRFS_COMPARE_TREE_NEW,
7257 down_read(&fs_info->commit_root_sem);
7259 advance_left = ADVANCE;
7263 if (left_level == 0 && right_level == 0) {
7264 up_read(&fs_info->commit_root_sem);
7265 cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
7267 ret = changed_cb(left_path, right_path,
7269 BTRFS_COMPARE_TREE_NEW,
7271 advance_left = ADVANCE;
7272 } else if (cmp > 0) {
7273 ret = changed_cb(left_path, right_path,
7275 BTRFS_COMPARE_TREE_DELETED,
7277 advance_right = ADVANCE;
7279 enum btrfs_compare_tree_result result;
7281 WARN_ON(!extent_buffer_uptodate(left_path->nodes[0]));
7282 ret = tree_compare_item(left_path, right_path,
7285 result = BTRFS_COMPARE_TREE_CHANGED;
7287 result = BTRFS_COMPARE_TREE_SAME;
7288 ret = changed_cb(left_path, right_path,
7289 &left_key, result, sctx);
7290 advance_left = ADVANCE;
7291 advance_right = ADVANCE;
7296 down_read(&fs_info->commit_root_sem);
7297 } else if (left_level == right_level) {
7298 cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
7300 advance_left = ADVANCE;
7301 } else if (cmp > 0) {
7302 advance_right = ADVANCE;
7304 left_blockptr = btrfs_node_blockptr(
7305 left_path->nodes[left_level],
7306 left_path->slots[left_level]);
7307 right_blockptr = btrfs_node_blockptr(
7308 right_path->nodes[right_level],
7309 right_path->slots[right_level]);
7310 left_gen = btrfs_node_ptr_generation(
7311 left_path->nodes[left_level],
7312 left_path->slots[left_level]);
7313 right_gen = btrfs_node_ptr_generation(
7314 right_path->nodes[right_level],
7315 right_path->slots[right_level]);
7316 if (left_blockptr == right_blockptr &&
7317 left_gen == right_gen) {
7319 * As we're on a shared block, don't
7320 * allow to go deeper.
7322 advance_left = ADVANCE_ONLY_NEXT;
7323 advance_right = ADVANCE_ONLY_NEXT;
7325 advance_left = ADVANCE;
7326 advance_right = ADVANCE;
7329 } else if (left_level < right_level) {
7330 advance_right = ADVANCE;
7332 advance_left = ADVANCE;
7337 up_read(&fs_info->commit_root_sem);
7339 btrfs_free_path(left_path);
7340 btrfs_free_path(right_path);
7345 static int send_subvol(struct send_ctx *sctx)
7349 if (!(sctx->flags & BTRFS_SEND_FLAG_OMIT_STREAM_HEADER)) {
7350 ret = send_header(sctx);
7355 ret = send_subvol_begin(sctx);
7359 if (sctx->parent_root) {
7360 ret = btrfs_compare_trees(sctx->send_root, sctx->parent_root, sctx);
7363 ret = finish_inode_if_needed(sctx, 1);
7367 ret = full_send_tree(sctx);
7373 free_recorded_refs(sctx);
7378 * If orphan cleanup did remove any orphans from a root, it means the tree
7379 * was modified and therefore the commit root is not the same as the current
7380 * root anymore. This is a problem, because send uses the commit root and
7381 * therefore can see inode items that don't exist in the current root anymore,
7382 * and for example make calls to btrfs_iget, which will do tree lookups based
7383 * on the current root and not on the commit root. Those lookups will fail,
7384 * returning a -ESTALE error, and making send fail with that error. So make
7385 * sure a send does not see any orphans we have just removed, and that it will
7386 * see the same inodes regardless of whether a transaction commit happened
7387 * before it started (meaning that the commit root will be the same as the
7388 * current root) or not.
7390 static int ensure_commit_roots_uptodate(struct send_ctx *sctx)
7393 struct btrfs_trans_handle *trans = NULL;
7396 if (sctx->parent_root &&
7397 sctx->parent_root->node != sctx->parent_root->commit_root)
7400 for (i = 0; i < sctx->clone_roots_cnt; i++)
7401 if (sctx->clone_roots[i].root->node !=
7402 sctx->clone_roots[i].root->commit_root)
7406 return btrfs_end_transaction(trans);
7411 /* Use any root, all fs roots will get their commit roots updated. */
7413 trans = btrfs_join_transaction(sctx->send_root);
7415 return PTR_ERR(trans);
7419 return btrfs_commit_transaction(trans);
7423 * Make sure any existing dellaloc is flushed for any root used by a send
7424 * operation so that we do not miss any data and we do not race with writeback
7425 * finishing and changing a tree while send is using the tree. This could
7426 * happen if a subvolume is in RW mode, has delalloc, is turned to RO mode and
7427 * a send operation then uses the subvolume.
7428 * After flushing delalloc ensure_commit_roots_uptodate() must be called.
7430 static int flush_delalloc_roots(struct send_ctx *sctx)
7432 struct btrfs_root *root = sctx->parent_root;
7437 ret = btrfs_start_delalloc_snapshot(root, false);
7440 btrfs_wait_ordered_extents(root, U64_MAX, 0, U64_MAX);
7443 for (i = 0; i < sctx->clone_roots_cnt; i++) {
7444 root = sctx->clone_roots[i].root;
7445 ret = btrfs_start_delalloc_snapshot(root, false);
7448 btrfs_wait_ordered_extents(root, U64_MAX, 0, U64_MAX);
7454 static void btrfs_root_dec_send_in_progress(struct btrfs_root* root)
7456 spin_lock(&root->root_item_lock);
7457 root->send_in_progress--;
7459 * Not much left to do, we don't know why it's unbalanced and
7460 * can't blindly reset it to 0.
7462 if (root->send_in_progress < 0)
7463 btrfs_err(root->fs_info,
7464 "send_in_progress unbalanced %d root %llu",
7465 root->send_in_progress, root->root_key.objectid);
7466 spin_unlock(&root->root_item_lock);
7469 static void dedupe_in_progress_warn(const struct btrfs_root *root)
7471 btrfs_warn_rl(root->fs_info,
7472 "cannot use root %llu for send while deduplications on it are in progress (%d in progress)",
7473 root->root_key.objectid, root->dedupe_in_progress);
7476 long btrfs_ioctl_send(struct file *mnt_file, struct btrfs_ioctl_send_args *arg)
7479 struct btrfs_root *send_root = BTRFS_I(file_inode(mnt_file))->root;
7480 struct btrfs_fs_info *fs_info = send_root->fs_info;
7481 struct btrfs_root *clone_root;
7482 struct send_ctx *sctx = NULL;
7484 u64 *clone_sources_tmp = NULL;
7485 int clone_sources_to_rollback = 0;
7487 int sort_clone_roots = 0;
7489 if (!capable(CAP_SYS_ADMIN))
7493 * The subvolume must remain read-only during send, protect against
7494 * making it RW. This also protects against deletion.
7496 spin_lock(&send_root->root_item_lock);
7497 if (btrfs_root_readonly(send_root) && send_root->dedupe_in_progress) {
7498 dedupe_in_progress_warn(send_root);
7499 spin_unlock(&send_root->root_item_lock);
7502 send_root->send_in_progress++;
7503 spin_unlock(&send_root->root_item_lock);
7506 * Userspace tools do the checks and warn the user if it's
7509 if (!btrfs_root_readonly(send_root)) {
7515 * Check that we don't overflow at later allocations, we request
7516 * clone_sources_count + 1 items, and compare to unsigned long inside
7519 if (arg->clone_sources_count >
7520 ULONG_MAX / sizeof(struct clone_root) - 1) {
7525 if (arg->flags & ~BTRFS_SEND_FLAG_MASK) {
7530 sctx = kzalloc(sizeof(struct send_ctx), GFP_KERNEL);
7536 INIT_LIST_HEAD(&sctx->new_refs);
7537 INIT_LIST_HEAD(&sctx->deleted_refs);
7538 INIT_RADIX_TREE(&sctx->name_cache, GFP_KERNEL);
7539 INIT_LIST_HEAD(&sctx->name_cache_list);
7541 sctx->flags = arg->flags;
7543 if (arg->flags & BTRFS_SEND_FLAG_VERSION) {
7544 if (arg->version > BTRFS_SEND_STREAM_VERSION) {
7548 /* Zero means "use the highest version" */
7549 sctx->proto = arg->version ?: BTRFS_SEND_STREAM_VERSION;
7554 sctx->send_filp = fget(arg->send_fd);
7555 if (!sctx->send_filp) {
7560 sctx->send_root = send_root;
7562 * Unlikely but possible, if the subvolume is marked for deletion but
7563 * is slow to remove the directory entry, send can still be started
7565 if (btrfs_root_dead(sctx->send_root)) {
7570 sctx->clone_roots_cnt = arg->clone_sources_count;
7572 sctx->send_max_size = BTRFS_SEND_BUF_SIZE;
7573 sctx->send_buf = kvmalloc(sctx->send_max_size, GFP_KERNEL);
7574 if (!sctx->send_buf) {
7579 sctx->pending_dir_moves = RB_ROOT;
7580 sctx->waiting_dir_moves = RB_ROOT;
7581 sctx->orphan_dirs = RB_ROOT;
7583 sctx->clone_roots = kvcalloc(sizeof(*sctx->clone_roots),
7584 arg->clone_sources_count + 1,
7586 if (!sctx->clone_roots) {
7591 alloc_size = array_size(sizeof(*arg->clone_sources),
7592 arg->clone_sources_count);
7594 if (arg->clone_sources_count) {
7595 clone_sources_tmp = kvmalloc(alloc_size, GFP_KERNEL);
7596 if (!clone_sources_tmp) {
7601 ret = copy_from_user(clone_sources_tmp, arg->clone_sources,
7608 for (i = 0; i < arg->clone_sources_count; i++) {
7609 clone_root = btrfs_get_fs_root(fs_info,
7610 clone_sources_tmp[i], true);
7611 if (IS_ERR(clone_root)) {
7612 ret = PTR_ERR(clone_root);
7615 spin_lock(&clone_root->root_item_lock);
7616 if (!btrfs_root_readonly(clone_root) ||
7617 btrfs_root_dead(clone_root)) {
7618 spin_unlock(&clone_root->root_item_lock);
7619 btrfs_put_root(clone_root);
7623 if (clone_root->dedupe_in_progress) {
7624 dedupe_in_progress_warn(clone_root);
7625 spin_unlock(&clone_root->root_item_lock);
7626 btrfs_put_root(clone_root);
7630 clone_root->send_in_progress++;
7631 spin_unlock(&clone_root->root_item_lock);
7633 sctx->clone_roots[i].root = clone_root;
7634 clone_sources_to_rollback = i + 1;
7636 kvfree(clone_sources_tmp);
7637 clone_sources_tmp = NULL;
7640 if (arg->parent_root) {
7641 sctx->parent_root = btrfs_get_fs_root(fs_info, arg->parent_root,
7643 if (IS_ERR(sctx->parent_root)) {
7644 ret = PTR_ERR(sctx->parent_root);
7648 spin_lock(&sctx->parent_root->root_item_lock);
7649 sctx->parent_root->send_in_progress++;
7650 if (!btrfs_root_readonly(sctx->parent_root) ||
7651 btrfs_root_dead(sctx->parent_root)) {
7652 spin_unlock(&sctx->parent_root->root_item_lock);
7656 if (sctx->parent_root->dedupe_in_progress) {
7657 dedupe_in_progress_warn(sctx->parent_root);
7658 spin_unlock(&sctx->parent_root->root_item_lock);
7662 spin_unlock(&sctx->parent_root->root_item_lock);
7666 * Clones from send_root are allowed, but only if the clone source
7667 * is behind the current send position. This is checked while searching
7668 * for possible clone sources.
7670 sctx->clone_roots[sctx->clone_roots_cnt++].root =
7671 btrfs_grab_root(sctx->send_root);
7673 /* We do a bsearch later */
7674 sort(sctx->clone_roots, sctx->clone_roots_cnt,
7675 sizeof(*sctx->clone_roots), __clone_root_cmp_sort,
7677 sort_clone_roots = 1;
7679 ret = flush_delalloc_roots(sctx);
7683 ret = ensure_commit_roots_uptodate(sctx);
7687 ret = send_subvol(sctx);
7691 if (!(sctx->flags & BTRFS_SEND_FLAG_OMIT_END_CMD)) {
7692 ret = begin_cmd(sctx, BTRFS_SEND_C_END);
7695 ret = send_cmd(sctx);
7701 WARN_ON(sctx && !ret && !RB_EMPTY_ROOT(&sctx->pending_dir_moves));
7702 while (sctx && !RB_EMPTY_ROOT(&sctx->pending_dir_moves)) {
7704 struct pending_dir_move *pm;
7706 n = rb_first(&sctx->pending_dir_moves);
7707 pm = rb_entry(n, struct pending_dir_move, node);
7708 while (!list_empty(&pm->list)) {
7709 struct pending_dir_move *pm2;
7711 pm2 = list_first_entry(&pm->list,
7712 struct pending_dir_move, list);
7713 free_pending_move(sctx, pm2);
7715 free_pending_move(sctx, pm);
7718 WARN_ON(sctx && !ret && !RB_EMPTY_ROOT(&sctx->waiting_dir_moves));
7719 while (sctx && !RB_EMPTY_ROOT(&sctx->waiting_dir_moves)) {
7721 struct waiting_dir_move *dm;
7723 n = rb_first(&sctx->waiting_dir_moves);
7724 dm = rb_entry(n, struct waiting_dir_move, node);
7725 rb_erase(&dm->node, &sctx->waiting_dir_moves);
7729 WARN_ON(sctx && !ret && !RB_EMPTY_ROOT(&sctx->orphan_dirs));
7730 while (sctx && !RB_EMPTY_ROOT(&sctx->orphan_dirs)) {
7732 struct orphan_dir_info *odi;
7734 n = rb_first(&sctx->orphan_dirs);
7735 odi = rb_entry(n, struct orphan_dir_info, node);
7736 free_orphan_dir_info(sctx, odi);
7739 if (sort_clone_roots) {
7740 for (i = 0; i < sctx->clone_roots_cnt; i++) {
7741 btrfs_root_dec_send_in_progress(
7742 sctx->clone_roots[i].root);
7743 btrfs_put_root(sctx->clone_roots[i].root);
7746 for (i = 0; sctx && i < clone_sources_to_rollback; i++) {
7747 btrfs_root_dec_send_in_progress(
7748 sctx->clone_roots[i].root);
7749 btrfs_put_root(sctx->clone_roots[i].root);
7752 btrfs_root_dec_send_in_progress(send_root);
7754 if (sctx && !IS_ERR_OR_NULL(sctx->parent_root)) {
7755 btrfs_root_dec_send_in_progress(sctx->parent_root);
7756 btrfs_put_root(sctx->parent_root);
7759 kvfree(clone_sources_tmp);
7762 if (sctx->send_filp)
7763 fput(sctx->send_filp);
7765 kvfree(sctx->clone_roots);
7766 kvfree(sctx->send_buf);
7768 name_cache_free(sctx);