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>
18 #include <linux/fsverity.h>
25 #include "btrfs_inode.h"
26 #include "transaction.h"
27 #include "compression.h"
29 #include "print-tree.h"
30 #include "accessors.h"
34 * Maximum number of references an extent can have in order for us to attempt to
35 * issue clone operations instead of write operations. This currently exists to
36 * avoid hitting limitations of the backreference walking code (taking a lot of
37 * time and using too much memory for extents with large number of references).
39 #define SEND_MAX_EXTENT_REFS 64
42 * A fs_path is a helper to dynamically build path names with unknown size.
43 * It reallocates the internal buffer on demand.
44 * It allows fast adding of path elements on the right side (normal path) and
45 * fast adding to the left side (reversed path). A reversed path can also be
46 * unreversed if needed.
55 unsigned short buf_len:15;
56 unsigned short reversed:1;
60 * Average path length does not exceed 200 bytes, we'll have
61 * better packing in the slab and higher chance to satisfy
62 * a allocation later during send.
67 #define FS_PATH_INLINE_SIZE \
68 (sizeof(struct fs_path) - offsetof(struct fs_path, inline_buf))
71 /* reused for each extent */
73 struct btrfs_root *root;
80 #define SEND_CTX_MAX_NAME_CACHE_SIZE 128
81 #define SEND_CTX_NAME_CACHE_CLEAN_SIZE (SEND_CTX_MAX_NAME_CACHE_SIZE * 2)
84 struct file *send_filp;
90 * Whether BTRFS_SEND_A_DATA attribute was already added to current
91 * command (since protocol v2, data must be the last attribute).
94 struct page **send_buf_pages;
95 u64 flags; /* 'flags' member of btrfs_ioctl_send_args is u64 */
96 /* Protocol version compatibility requested */
99 struct btrfs_root *send_root;
100 struct btrfs_root *parent_root;
101 struct clone_root *clone_roots;
104 /* current state of the compare_tree call */
105 struct btrfs_path *left_path;
106 struct btrfs_path *right_path;
107 struct btrfs_key *cmp_key;
110 * Keep track of the generation of the last transaction that was used
111 * for relocating a block group. This is periodically checked in order
112 * to detect if a relocation happened since the last check, so that we
113 * don't operate on stale extent buffers for nodes (level >= 1) or on
114 * stale disk_bytenr values of file extent items.
116 u64 last_reloc_trans;
119 * infos of the currently processed inode. In case of deleted inodes,
120 * these are the values from the deleted inode.
127 u64 cur_inode_last_extent;
128 u64 cur_inode_next_write_offset;
130 bool cur_inode_new_gen;
131 bool cur_inode_deleted;
132 bool ignore_cur_inode;
133 bool cur_inode_needs_verity;
134 void *verity_descriptor;
138 struct list_head new_refs;
139 struct list_head deleted_refs;
141 struct radix_tree_root name_cache;
142 struct list_head name_cache_list;
146 * The inode we are currently processing. It's not NULL only when we
147 * need to issue write commands for data extents from this inode.
149 struct inode *cur_inode;
150 struct file_ra_state ra;
151 u64 page_cache_clear_start;
152 bool clean_page_cache;
155 * We process inodes by their increasing order, so if before an
156 * incremental send we reverse the parent/child relationship of
157 * directories such that a directory with a lower inode number was
158 * the parent of a directory with a higher inode number, and the one
159 * becoming the new parent got renamed too, we can't rename/move the
160 * directory with lower inode number when we finish processing it - we
161 * must process the directory with higher inode number first, then
162 * rename/move it and then rename/move the directory with lower inode
163 * number. Example follows.
165 * Tree state when the first send was performed:
177 * Tree state when the second (incremental) send is performed:
186 * The sequence of steps that lead to the second state was:
188 * mv /a/b/c/d /a/b/c2/d2
189 * mv /a/b/c /a/b/c2/d2/cc
191 * "c" has lower inode number, but we can't move it (2nd mv operation)
192 * before we move "d", which has higher inode number.
194 * So we just memorize which move/rename operations must be performed
195 * later when their respective parent is processed and moved/renamed.
198 /* Indexed by parent directory inode number. */
199 struct rb_root pending_dir_moves;
202 * Reverse index, indexed by the inode number of a directory that
203 * is waiting for the move/rename of its immediate parent before its
204 * own move/rename can be performed.
206 struct rb_root waiting_dir_moves;
209 * A directory that is going to be rm'ed might have a child directory
210 * which is in the pending directory moves index above. In this case,
211 * the directory can only be removed after the move/rename of its child
212 * is performed. Example:
232 * Sequence of steps that lead to the send snapshot:
233 * rm -f /a/b/c/foo.txt
235 * mv /a/b/c/x /a/b/YY
238 * When the child is processed, its move/rename is delayed until its
239 * parent is processed (as explained above), but all other operations
240 * like update utimes, chown, chgrp, etc, are performed and the paths
241 * that it uses for those operations must use the orphanized name of
242 * its parent (the directory we're going to rm later), so we need to
243 * memorize that name.
245 * Indexed by the inode number of the directory to be deleted.
247 struct rb_root orphan_dirs;
249 struct rb_root rbtree_new_refs;
250 struct rb_root rbtree_deleted_refs;
253 struct pending_dir_move {
255 struct list_head list;
259 struct list_head update_refs;
262 struct waiting_dir_move {
266 * There might be some directory that could not be removed because it
267 * was waiting for this directory inode to be moved first. Therefore
268 * after this directory is moved, we can try to rmdir the ino rmdir_ino.
275 struct orphan_dir_info {
279 u64 last_dir_index_offset;
282 struct name_cache_entry {
283 struct list_head list;
285 * radix_tree has only 32bit entries but we need to handle 64bit inums.
286 * We use the lower 32bit of the 64bit inum to store it in the tree. If
287 * more then one inum would fall into the same entry, we use radix_list
288 * to store the additional entries. radix_list is also used to store
289 * entries where two entries have the same inum but different
292 struct list_head radix_list;
298 int need_later_update;
304 #define ADVANCE_ONLY_NEXT -1
306 enum btrfs_compare_tree_result {
307 BTRFS_COMPARE_TREE_NEW,
308 BTRFS_COMPARE_TREE_DELETED,
309 BTRFS_COMPARE_TREE_CHANGED,
310 BTRFS_COMPARE_TREE_SAME,
314 static void inconsistent_snapshot_error(struct send_ctx *sctx,
315 enum btrfs_compare_tree_result result,
318 const char *result_string;
321 case BTRFS_COMPARE_TREE_NEW:
322 result_string = "new";
324 case BTRFS_COMPARE_TREE_DELETED:
325 result_string = "deleted";
327 case BTRFS_COMPARE_TREE_CHANGED:
328 result_string = "updated";
330 case BTRFS_COMPARE_TREE_SAME:
332 result_string = "unchanged";
336 result_string = "unexpected";
339 btrfs_err(sctx->send_root->fs_info,
340 "Send: inconsistent snapshot, found %s %s for inode %llu without updated inode item, send root is %llu, parent root is %llu",
341 result_string, what, sctx->cmp_key->objectid,
342 sctx->send_root->root_key.objectid,
344 sctx->parent_root->root_key.objectid : 0));
348 static bool proto_cmd_ok(const struct send_ctx *sctx, int cmd)
350 switch (sctx->proto) {
351 case 1: return cmd <= BTRFS_SEND_C_MAX_V1;
352 case 2: return cmd <= BTRFS_SEND_C_MAX_V2;
353 case 3: return cmd <= BTRFS_SEND_C_MAX_V3;
354 default: return false;
358 static int is_waiting_for_move(struct send_ctx *sctx, u64 ino);
360 static struct waiting_dir_move *
361 get_waiting_dir_move(struct send_ctx *sctx, u64 ino);
363 static int is_waiting_for_rm(struct send_ctx *sctx, u64 dir_ino, u64 gen);
365 static int need_send_hole(struct send_ctx *sctx)
367 return (sctx->parent_root && !sctx->cur_inode_new &&
368 !sctx->cur_inode_new_gen && !sctx->cur_inode_deleted &&
369 S_ISREG(sctx->cur_inode_mode));
372 static void fs_path_reset(struct fs_path *p)
375 p->start = p->buf + p->buf_len - 1;
385 static struct fs_path *fs_path_alloc(void)
389 p = kmalloc(sizeof(*p), GFP_KERNEL);
393 p->buf = p->inline_buf;
394 p->buf_len = FS_PATH_INLINE_SIZE;
399 static struct fs_path *fs_path_alloc_reversed(void)
411 static void fs_path_free(struct fs_path *p)
415 if (p->buf != p->inline_buf)
420 static int fs_path_len(struct fs_path *p)
422 return p->end - p->start;
425 static int fs_path_ensure_buf(struct fs_path *p, int len)
433 if (p->buf_len >= len)
436 if (len > PATH_MAX) {
441 path_len = p->end - p->start;
442 old_buf_len = p->buf_len;
445 * First time the inline_buf does not suffice
447 if (p->buf == p->inline_buf) {
448 tmp_buf = kmalloc(len, GFP_KERNEL);
450 memcpy(tmp_buf, p->buf, old_buf_len);
452 tmp_buf = krealloc(p->buf, len, GFP_KERNEL);
458 * The real size of the buffer is bigger, this will let the fast path
459 * happen most of the time
461 p->buf_len = ksize(p->buf);
464 tmp_buf = p->buf + old_buf_len - path_len - 1;
465 p->end = p->buf + p->buf_len - 1;
466 p->start = p->end - path_len;
467 memmove(p->start, tmp_buf, path_len + 1);
470 p->end = p->start + path_len;
475 static int fs_path_prepare_for_add(struct fs_path *p, int name_len,
481 new_len = p->end - p->start + name_len;
482 if (p->start != p->end)
484 ret = fs_path_ensure_buf(p, new_len);
489 if (p->start != p->end)
491 p->start -= name_len;
492 *prepared = p->start;
494 if (p->start != p->end)
505 static int fs_path_add(struct fs_path *p, const char *name, int name_len)
510 ret = fs_path_prepare_for_add(p, name_len, &prepared);
513 memcpy(prepared, name, name_len);
519 static int fs_path_add_path(struct fs_path *p, struct fs_path *p2)
524 ret = fs_path_prepare_for_add(p, p2->end - p2->start, &prepared);
527 memcpy(prepared, p2->start, p2->end - p2->start);
533 static int fs_path_add_from_extent_buffer(struct fs_path *p,
534 struct extent_buffer *eb,
535 unsigned long off, int len)
540 ret = fs_path_prepare_for_add(p, len, &prepared);
544 read_extent_buffer(eb, prepared, off, len);
550 static int fs_path_copy(struct fs_path *p, struct fs_path *from)
552 p->reversed = from->reversed;
555 return fs_path_add_path(p, from);
558 static void fs_path_unreverse(struct fs_path *p)
567 len = p->end - p->start;
569 p->end = p->start + len;
570 memmove(p->start, tmp, len + 1);
574 static struct btrfs_path *alloc_path_for_send(void)
576 struct btrfs_path *path;
578 path = btrfs_alloc_path();
581 path->search_commit_root = 1;
582 path->skip_locking = 1;
583 path->need_commit_sem = 1;
587 static int write_buf(struct file *filp, const void *buf, u32 len, loff_t *off)
593 ret = kernel_write(filp, buf + pos, len - pos, off);
604 static int tlv_put(struct send_ctx *sctx, u16 attr, const void *data, int len)
606 struct btrfs_tlv_header *hdr;
607 int total_len = sizeof(*hdr) + len;
608 int left = sctx->send_max_size - sctx->send_size;
610 if (WARN_ON_ONCE(sctx->put_data))
613 if (unlikely(left < total_len))
616 hdr = (struct btrfs_tlv_header *) (sctx->send_buf + sctx->send_size);
617 put_unaligned_le16(attr, &hdr->tlv_type);
618 put_unaligned_le16(len, &hdr->tlv_len);
619 memcpy(hdr + 1, data, len);
620 sctx->send_size += total_len;
625 #define TLV_PUT_DEFINE_INT(bits) \
626 static int tlv_put_u##bits(struct send_ctx *sctx, \
627 u##bits attr, u##bits value) \
629 __le##bits __tmp = cpu_to_le##bits(value); \
630 return tlv_put(sctx, attr, &__tmp, sizeof(__tmp)); \
633 TLV_PUT_DEFINE_INT(8)
634 TLV_PUT_DEFINE_INT(32)
635 TLV_PUT_DEFINE_INT(64)
637 static int tlv_put_string(struct send_ctx *sctx, u16 attr,
638 const char *str, int len)
642 return tlv_put(sctx, attr, str, len);
645 static int tlv_put_uuid(struct send_ctx *sctx, u16 attr,
648 return tlv_put(sctx, attr, uuid, BTRFS_UUID_SIZE);
651 static int tlv_put_btrfs_timespec(struct send_ctx *sctx, u16 attr,
652 struct extent_buffer *eb,
653 struct btrfs_timespec *ts)
655 struct btrfs_timespec bts;
656 read_extent_buffer(eb, &bts, (unsigned long)ts, sizeof(bts));
657 return tlv_put(sctx, attr, &bts, sizeof(bts));
661 #define TLV_PUT(sctx, attrtype, data, attrlen) \
663 ret = tlv_put(sctx, attrtype, data, attrlen); \
665 goto tlv_put_failure; \
668 #define TLV_PUT_INT(sctx, attrtype, bits, value) \
670 ret = tlv_put_u##bits(sctx, attrtype, value); \
672 goto tlv_put_failure; \
675 #define TLV_PUT_U8(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 8, data)
676 #define TLV_PUT_U16(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 16, data)
677 #define TLV_PUT_U32(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 32, data)
678 #define TLV_PUT_U64(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 64, data)
679 #define TLV_PUT_STRING(sctx, attrtype, str, len) \
681 ret = tlv_put_string(sctx, attrtype, str, len); \
683 goto tlv_put_failure; \
685 #define TLV_PUT_PATH(sctx, attrtype, p) \
687 ret = tlv_put_string(sctx, attrtype, p->start, \
688 p->end - p->start); \
690 goto tlv_put_failure; \
692 #define TLV_PUT_UUID(sctx, attrtype, uuid) \
694 ret = tlv_put_uuid(sctx, attrtype, uuid); \
696 goto tlv_put_failure; \
698 #define TLV_PUT_BTRFS_TIMESPEC(sctx, attrtype, eb, ts) \
700 ret = tlv_put_btrfs_timespec(sctx, attrtype, eb, ts); \
702 goto tlv_put_failure; \
705 static int send_header(struct send_ctx *sctx)
707 struct btrfs_stream_header hdr;
709 strcpy(hdr.magic, BTRFS_SEND_STREAM_MAGIC);
710 hdr.version = cpu_to_le32(sctx->proto);
711 return write_buf(sctx->send_filp, &hdr, sizeof(hdr),
716 * For each command/item we want to send to userspace, we call this function.
718 static int begin_cmd(struct send_ctx *sctx, int cmd)
720 struct btrfs_cmd_header *hdr;
722 if (WARN_ON(!sctx->send_buf))
725 BUG_ON(sctx->send_size);
727 sctx->send_size += sizeof(*hdr);
728 hdr = (struct btrfs_cmd_header *)sctx->send_buf;
729 put_unaligned_le16(cmd, &hdr->cmd);
734 static int send_cmd(struct send_ctx *sctx)
737 struct btrfs_cmd_header *hdr;
740 hdr = (struct btrfs_cmd_header *)sctx->send_buf;
741 put_unaligned_le32(sctx->send_size - sizeof(*hdr), &hdr->len);
742 put_unaligned_le32(0, &hdr->crc);
744 crc = btrfs_crc32c(0, (unsigned char *)sctx->send_buf, sctx->send_size);
745 put_unaligned_le32(crc, &hdr->crc);
747 ret = write_buf(sctx->send_filp, sctx->send_buf, sctx->send_size,
751 sctx->put_data = false;
757 * Sends a move instruction to user space
759 static int send_rename(struct send_ctx *sctx,
760 struct fs_path *from, struct fs_path *to)
762 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
765 btrfs_debug(fs_info, "send_rename %s -> %s", from->start, to->start);
767 ret = begin_cmd(sctx, BTRFS_SEND_C_RENAME);
771 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, from);
772 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH_TO, to);
774 ret = send_cmd(sctx);
782 * Sends a link instruction to user space
784 static int send_link(struct send_ctx *sctx,
785 struct fs_path *path, struct fs_path *lnk)
787 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
790 btrfs_debug(fs_info, "send_link %s -> %s", path->start, lnk->start);
792 ret = begin_cmd(sctx, BTRFS_SEND_C_LINK);
796 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
797 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH_LINK, lnk);
799 ret = send_cmd(sctx);
807 * Sends an unlink instruction to user space
809 static int send_unlink(struct send_ctx *sctx, struct fs_path *path)
811 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
814 btrfs_debug(fs_info, "send_unlink %s", path->start);
816 ret = begin_cmd(sctx, BTRFS_SEND_C_UNLINK);
820 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
822 ret = send_cmd(sctx);
830 * Sends a rmdir instruction to user space
832 static int send_rmdir(struct send_ctx *sctx, struct fs_path *path)
834 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
837 btrfs_debug(fs_info, "send_rmdir %s", path->start);
839 ret = begin_cmd(sctx, BTRFS_SEND_C_RMDIR);
843 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
845 ret = send_cmd(sctx);
852 struct btrfs_inode_info {
864 * Helper function to retrieve some fields from an inode item.
866 static int get_inode_info(struct btrfs_root *root, u64 ino,
867 struct btrfs_inode_info *info)
870 struct btrfs_path *path;
871 struct btrfs_inode_item *ii;
872 struct btrfs_key key;
874 path = alloc_path_for_send();
879 key.type = BTRFS_INODE_ITEM_KEY;
881 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
891 ii = btrfs_item_ptr(path->nodes[0], path->slots[0],
892 struct btrfs_inode_item);
893 info->size = btrfs_inode_size(path->nodes[0], ii);
894 info->gen = btrfs_inode_generation(path->nodes[0], ii);
895 info->mode = btrfs_inode_mode(path->nodes[0], ii);
896 info->uid = btrfs_inode_uid(path->nodes[0], ii);
897 info->gid = btrfs_inode_gid(path->nodes[0], ii);
898 info->rdev = btrfs_inode_rdev(path->nodes[0], ii);
899 info->nlink = btrfs_inode_nlink(path->nodes[0], ii);
901 * Transfer the unchanged u64 value of btrfs_inode_item::flags, that's
902 * otherwise logically split to 32/32 parts.
904 info->fileattr = btrfs_inode_flags(path->nodes[0], ii);
907 btrfs_free_path(path);
911 static int get_inode_gen(struct btrfs_root *root, u64 ino, u64 *gen)
914 struct btrfs_inode_info info;
919 ret = get_inode_info(root, ino, &info);
925 typedef int (*iterate_inode_ref_t)(int num, u64 dir, int index,
930 * Helper function to iterate the entries in ONE btrfs_inode_ref or
931 * btrfs_inode_extref.
932 * The iterate callback may return a non zero value to stop iteration. This can
933 * be a negative value for error codes or 1 to simply stop it.
935 * path must point to the INODE_REF or INODE_EXTREF when called.
937 static int iterate_inode_ref(struct btrfs_root *root, struct btrfs_path *path,
938 struct btrfs_key *found_key, int resolve,
939 iterate_inode_ref_t iterate, void *ctx)
941 struct extent_buffer *eb = path->nodes[0];
942 struct btrfs_inode_ref *iref;
943 struct btrfs_inode_extref *extref;
944 struct btrfs_path *tmp_path;
948 int slot = path->slots[0];
955 unsigned long name_off;
956 unsigned long elem_size;
959 p = fs_path_alloc_reversed();
963 tmp_path = alloc_path_for_send();
970 if (found_key->type == BTRFS_INODE_REF_KEY) {
971 ptr = (unsigned long)btrfs_item_ptr(eb, slot,
972 struct btrfs_inode_ref);
973 total = btrfs_item_size(eb, slot);
974 elem_size = sizeof(*iref);
976 ptr = btrfs_item_ptr_offset(eb, slot);
977 total = btrfs_item_size(eb, slot);
978 elem_size = sizeof(*extref);
981 while (cur < total) {
984 if (found_key->type == BTRFS_INODE_REF_KEY) {
985 iref = (struct btrfs_inode_ref *)(ptr + cur);
986 name_len = btrfs_inode_ref_name_len(eb, iref);
987 name_off = (unsigned long)(iref + 1);
988 index = btrfs_inode_ref_index(eb, iref);
989 dir = found_key->offset;
991 extref = (struct btrfs_inode_extref *)(ptr + cur);
992 name_len = btrfs_inode_extref_name_len(eb, extref);
993 name_off = (unsigned long)&extref->name;
994 index = btrfs_inode_extref_index(eb, extref);
995 dir = btrfs_inode_extref_parent(eb, extref);
999 start = btrfs_ref_to_path(root, tmp_path, name_len,
1001 p->buf, p->buf_len);
1002 if (IS_ERR(start)) {
1003 ret = PTR_ERR(start);
1006 if (start < p->buf) {
1007 /* overflow , try again with larger buffer */
1008 ret = fs_path_ensure_buf(p,
1009 p->buf_len + p->buf - start);
1012 start = btrfs_ref_to_path(root, tmp_path,
1015 p->buf, p->buf_len);
1016 if (IS_ERR(start)) {
1017 ret = PTR_ERR(start);
1020 BUG_ON(start < p->buf);
1024 ret = fs_path_add_from_extent_buffer(p, eb, name_off,
1030 cur += elem_size + name_len;
1031 ret = iterate(num, dir, index, p, ctx);
1038 btrfs_free_path(tmp_path);
1043 typedef int (*iterate_dir_item_t)(int num, struct btrfs_key *di_key,
1044 const char *name, int name_len,
1045 const char *data, int data_len,
1049 * Helper function to iterate the entries in ONE btrfs_dir_item.
1050 * The iterate callback may return a non zero value to stop iteration. This can
1051 * be a negative value for error codes or 1 to simply stop it.
1053 * path must point to the dir item when called.
1055 static int iterate_dir_item(struct btrfs_root *root, struct btrfs_path *path,
1056 iterate_dir_item_t iterate, void *ctx)
1059 struct extent_buffer *eb;
1060 struct btrfs_dir_item *di;
1061 struct btrfs_key di_key;
1073 * Start with a small buffer (1 page). If later we end up needing more
1074 * space, which can happen for xattrs on a fs with a leaf size greater
1075 * then the page size, attempt to increase the buffer. Typically xattr
1079 buf = kmalloc(buf_len, GFP_KERNEL);
1085 eb = path->nodes[0];
1086 slot = path->slots[0];
1087 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
1090 total = btrfs_item_size(eb, slot);
1093 while (cur < total) {
1094 name_len = btrfs_dir_name_len(eb, di);
1095 data_len = btrfs_dir_data_len(eb, di);
1096 btrfs_dir_item_key_to_cpu(eb, di, &di_key);
1098 if (btrfs_dir_ftype(eb, di) == BTRFS_FT_XATTR) {
1099 if (name_len > XATTR_NAME_MAX) {
1100 ret = -ENAMETOOLONG;
1103 if (name_len + data_len >
1104 BTRFS_MAX_XATTR_SIZE(root->fs_info)) {
1112 if (name_len + data_len > PATH_MAX) {
1113 ret = -ENAMETOOLONG;
1118 if (name_len + data_len > buf_len) {
1119 buf_len = name_len + data_len;
1120 if (is_vmalloc_addr(buf)) {
1124 char *tmp = krealloc(buf, buf_len,
1125 GFP_KERNEL | __GFP_NOWARN);
1132 buf = kvmalloc(buf_len, GFP_KERNEL);
1140 read_extent_buffer(eb, buf, (unsigned long)(di + 1),
1141 name_len + data_len);
1143 len = sizeof(*di) + name_len + data_len;
1144 di = (struct btrfs_dir_item *)((char *)di + len);
1147 ret = iterate(num, &di_key, buf, name_len, buf + name_len,
1164 static int __copy_first_ref(int num, u64 dir, int index,
1165 struct fs_path *p, void *ctx)
1168 struct fs_path *pt = ctx;
1170 ret = fs_path_copy(pt, p);
1174 /* we want the first only */
1179 * Retrieve the first path of an inode. If an inode has more then one
1180 * ref/hardlink, this is ignored.
1182 static int get_inode_path(struct btrfs_root *root,
1183 u64 ino, struct fs_path *path)
1186 struct btrfs_key key, found_key;
1187 struct btrfs_path *p;
1189 p = alloc_path_for_send();
1193 fs_path_reset(path);
1196 key.type = BTRFS_INODE_REF_KEY;
1199 ret = btrfs_search_slot_for_read(root, &key, p, 1, 0);
1206 btrfs_item_key_to_cpu(p->nodes[0], &found_key, p->slots[0]);
1207 if (found_key.objectid != ino ||
1208 (found_key.type != BTRFS_INODE_REF_KEY &&
1209 found_key.type != BTRFS_INODE_EXTREF_KEY)) {
1214 ret = iterate_inode_ref(root, p, &found_key, 1,
1215 __copy_first_ref, path);
1225 struct backref_ctx {
1226 struct send_ctx *sctx;
1228 /* number of total found references */
1232 * used for clones found in send_root. clones found behind cur_objectid
1233 * and cur_offset are not considered as allowed clones.
1238 /* may be truncated in case it's the last extent in a file */
1241 /* Just to check for bugs in backref resolving */
1245 static int __clone_root_cmp_bsearch(const void *key, const void *elt)
1247 u64 root = (u64)(uintptr_t)key;
1248 const struct clone_root *cr = elt;
1250 if (root < cr->root->root_key.objectid)
1252 if (root > cr->root->root_key.objectid)
1257 static int __clone_root_cmp_sort(const void *e1, const void *e2)
1259 const struct clone_root *cr1 = e1;
1260 const struct clone_root *cr2 = e2;
1262 if (cr1->root->root_key.objectid < cr2->root->root_key.objectid)
1264 if (cr1->root->root_key.objectid > cr2->root->root_key.objectid)
1270 * Called for every backref that is found for the current extent.
1271 * Results are collected in sctx->clone_roots->ino/offset/found_refs
1273 static int __iterate_backrefs(u64 ino, u64 offset, u64 root, void *ctx_)
1275 struct backref_ctx *bctx = ctx_;
1276 struct clone_root *found;
1278 /* First check if the root is in the list of accepted clone sources */
1279 found = bsearch((void *)(uintptr_t)root, bctx->sctx->clone_roots,
1280 bctx->sctx->clone_roots_cnt,
1281 sizeof(struct clone_root),
1282 __clone_root_cmp_bsearch);
1286 if (found->root == bctx->sctx->send_root &&
1287 ino == bctx->cur_objectid &&
1288 offset == bctx->cur_offset) {
1289 bctx->found_itself = 1;
1293 * Make sure we don't consider clones from send_root that are
1294 * behind the current inode/offset.
1296 if (found->root == bctx->sctx->send_root) {
1298 * If the source inode was not yet processed we can't issue a
1299 * clone operation, as the source extent does not exist yet at
1300 * the destination of the stream.
1302 if (ino > bctx->cur_objectid)
1305 * We clone from the inode currently being sent as long as the
1306 * source extent is already processed, otherwise we could try
1307 * to clone from an extent that does not exist yet at the
1308 * destination of the stream.
1310 if (ino == bctx->cur_objectid &&
1311 offset + bctx->extent_len >
1312 bctx->sctx->cur_inode_next_write_offset)
1317 found->found_refs++;
1318 if (ino < found->ino) {
1320 found->offset = offset;
1321 } else if (found->ino == ino) {
1323 * same extent found more then once in the same file.
1325 if (found->offset > offset + bctx->extent_len)
1326 found->offset = offset;
1333 * Given an inode, offset and extent item, it finds a good clone for a clone
1334 * instruction. Returns -ENOENT when none could be found. The function makes
1335 * sure that the returned clone is usable at the point where sending is at the
1336 * moment. This means, that no clones are accepted which lie behind the current
1339 * path must point to the extent item when called.
1341 static int find_extent_clone(struct send_ctx *sctx,
1342 struct btrfs_path *path,
1343 u64 ino, u64 data_offset,
1345 struct clone_root **found)
1347 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
1353 u64 extent_item_pos;
1355 struct btrfs_file_extent_item *fi;
1356 struct extent_buffer *eb = path->nodes[0];
1357 struct backref_ctx backref_ctx = {0};
1358 struct clone_root *cur_clone_root;
1359 struct btrfs_key found_key;
1360 struct btrfs_path *tmp_path;
1361 struct btrfs_extent_item *ei;
1365 tmp_path = alloc_path_for_send();
1369 /* We only use this path under the commit sem */
1370 tmp_path->need_commit_sem = 0;
1372 if (data_offset >= ino_size) {
1374 * There may be extents that lie behind the file's size.
1375 * I at least had this in combination with snapshotting while
1376 * writing large files.
1382 fi = btrfs_item_ptr(eb, path->slots[0],
1383 struct btrfs_file_extent_item);
1384 extent_type = btrfs_file_extent_type(eb, fi);
1385 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1389 compressed = btrfs_file_extent_compression(eb, fi);
1391 num_bytes = btrfs_file_extent_num_bytes(eb, fi);
1392 disk_byte = btrfs_file_extent_disk_bytenr(eb, fi);
1393 if (disk_byte == 0) {
1397 logical = disk_byte + btrfs_file_extent_offset(eb, fi);
1399 down_read(&fs_info->commit_root_sem);
1400 ret = extent_from_logical(fs_info, disk_byte, tmp_path,
1401 &found_key, &flags);
1402 up_read(&fs_info->commit_root_sem);
1406 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
1411 ei = btrfs_item_ptr(tmp_path->nodes[0], tmp_path->slots[0],
1412 struct btrfs_extent_item);
1414 * Backreference walking (iterate_extent_inodes() below) is currently
1415 * too expensive when an extent has a large number of references, both
1416 * in time spent and used memory. So for now just fallback to write
1417 * operations instead of clone operations when an extent has more than
1418 * a certain amount of references.
1420 if (btrfs_extent_refs(tmp_path->nodes[0], ei) > SEND_MAX_EXTENT_REFS) {
1424 btrfs_release_path(tmp_path);
1427 * Setup the clone roots.
1429 for (i = 0; i < sctx->clone_roots_cnt; i++) {
1430 cur_clone_root = sctx->clone_roots + i;
1431 cur_clone_root->ino = (u64)-1;
1432 cur_clone_root->offset = 0;
1433 cur_clone_root->found_refs = 0;
1436 backref_ctx.sctx = sctx;
1437 backref_ctx.found = 0;
1438 backref_ctx.cur_objectid = ino;
1439 backref_ctx.cur_offset = data_offset;
1440 backref_ctx.found_itself = 0;
1441 backref_ctx.extent_len = num_bytes;
1444 * The last extent of a file may be too large due to page alignment.
1445 * We need to adjust extent_len in this case so that the checks in
1446 * __iterate_backrefs work.
1448 if (data_offset + num_bytes >= ino_size)
1449 backref_ctx.extent_len = ino_size - data_offset;
1452 * Now collect all backrefs.
1454 if (compressed == BTRFS_COMPRESS_NONE)
1455 extent_item_pos = logical - found_key.objectid;
1457 extent_item_pos = 0;
1458 ret = iterate_extent_inodes(fs_info, found_key.objectid,
1459 extent_item_pos, 1, __iterate_backrefs,
1460 &backref_ctx, false);
1465 down_read(&fs_info->commit_root_sem);
1466 if (fs_info->last_reloc_trans > sctx->last_reloc_trans) {
1468 * A transaction commit for a transaction in which block group
1469 * relocation was done just happened.
1470 * The disk_bytenr of the file extent item we processed is
1471 * possibly stale, referring to the extent's location before
1472 * relocation. So act as if we haven't found any clone sources
1473 * and fallback to write commands, which will read the correct
1474 * data from the new extent location. Otherwise we will fail
1475 * below because we haven't found our own back reference or we
1476 * could be getting incorrect sources in case the old extent
1477 * was already reallocated after the relocation.
1479 up_read(&fs_info->commit_root_sem);
1483 up_read(&fs_info->commit_root_sem);
1485 if (!backref_ctx.found_itself) {
1486 /* found a bug in backref code? */
1489 "did not find backref in send_root. inode=%llu, offset=%llu, disk_byte=%llu found extent=%llu",
1490 ino, data_offset, disk_byte, found_key.objectid);
1494 btrfs_debug(fs_info,
1495 "find_extent_clone: data_offset=%llu, ino=%llu, num_bytes=%llu, logical=%llu",
1496 data_offset, ino, num_bytes, logical);
1498 if (!backref_ctx.found)
1499 btrfs_debug(fs_info, "no clones found");
1501 cur_clone_root = NULL;
1502 for (i = 0; i < sctx->clone_roots_cnt; i++) {
1503 if (sctx->clone_roots[i].found_refs) {
1504 if (!cur_clone_root)
1505 cur_clone_root = sctx->clone_roots + i;
1506 else if (sctx->clone_roots[i].root == sctx->send_root)
1507 /* prefer clones from send_root over others */
1508 cur_clone_root = sctx->clone_roots + i;
1513 if (cur_clone_root) {
1514 *found = cur_clone_root;
1521 btrfs_free_path(tmp_path);
1525 static int read_symlink(struct btrfs_root *root,
1527 struct fs_path *dest)
1530 struct btrfs_path *path;
1531 struct btrfs_key key;
1532 struct btrfs_file_extent_item *ei;
1538 path = alloc_path_for_send();
1543 key.type = BTRFS_EXTENT_DATA_KEY;
1545 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1550 * An empty symlink inode. Can happen in rare error paths when
1551 * creating a symlink (transaction committed before the inode
1552 * eviction handler removed the symlink inode items and a crash
1553 * happened in between or the subvol was snapshoted in between).
1554 * Print an informative message to dmesg/syslog so that the user
1555 * can delete the symlink.
1557 btrfs_err(root->fs_info,
1558 "Found empty symlink inode %llu at root %llu",
1559 ino, root->root_key.objectid);
1564 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
1565 struct btrfs_file_extent_item);
1566 type = btrfs_file_extent_type(path->nodes[0], ei);
1567 compression = btrfs_file_extent_compression(path->nodes[0], ei);
1568 BUG_ON(type != BTRFS_FILE_EXTENT_INLINE);
1569 BUG_ON(compression);
1571 off = btrfs_file_extent_inline_start(ei);
1572 len = btrfs_file_extent_ram_bytes(path->nodes[0], ei);
1574 ret = fs_path_add_from_extent_buffer(dest, path->nodes[0], off, len);
1577 btrfs_free_path(path);
1582 * Helper function to generate a file name that is unique in the root of
1583 * send_root and parent_root. This is used to generate names for orphan inodes.
1585 static int gen_unique_name(struct send_ctx *sctx,
1587 struct fs_path *dest)
1590 struct btrfs_path *path;
1591 struct btrfs_dir_item *di;
1596 path = alloc_path_for_send();
1601 struct fscrypt_str tmp_name;
1603 len = snprintf(tmp, sizeof(tmp), "o%llu-%llu-%llu",
1605 ASSERT(len < sizeof(tmp));
1606 tmp_name.name = tmp;
1607 tmp_name.len = strlen(tmp);
1609 di = btrfs_lookup_dir_item(NULL, sctx->send_root,
1610 path, BTRFS_FIRST_FREE_OBJECTID,
1612 btrfs_release_path(path);
1618 /* not unique, try again */
1623 if (!sctx->parent_root) {
1629 di = btrfs_lookup_dir_item(NULL, sctx->parent_root,
1630 path, BTRFS_FIRST_FREE_OBJECTID,
1632 btrfs_release_path(path);
1638 /* not unique, try again */
1646 ret = fs_path_add(dest, tmp, strlen(tmp));
1649 btrfs_free_path(path);
1654 inode_state_no_change,
1655 inode_state_will_create,
1656 inode_state_did_create,
1657 inode_state_will_delete,
1658 inode_state_did_delete,
1661 static int get_cur_inode_state(struct send_ctx *sctx, u64 ino, u64 gen)
1668 struct btrfs_inode_info info;
1670 ret = get_inode_info(sctx->send_root, ino, &info);
1671 if (ret < 0 && ret != -ENOENT)
1673 left_ret = (info.nlink == 0) ? -ENOENT : ret;
1674 left_gen = info.gen;
1676 if (!sctx->parent_root) {
1677 right_ret = -ENOENT;
1679 ret = get_inode_info(sctx->parent_root, ino, &info);
1680 if (ret < 0 && ret != -ENOENT)
1682 right_ret = (info.nlink == 0) ? -ENOENT : ret;
1683 right_gen = info.gen;
1686 if (!left_ret && !right_ret) {
1687 if (left_gen == gen && right_gen == gen) {
1688 ret = inode_state_no_change;
1689 } else if (left_gen == gen) {
1690 if (ino < sctx->send_progress)
1691 ret = inode_state_did_create;
1693 ret = inode_state_will_create;
1694 } else if (right_gen == gen) {
1695 if (ino < sctx->send_progress)
1696 ret = inode_state_did_delete;
1698 ret = inode_state_will_delete;
1702 } else if (!left_ret) {
1703 if (left_gen == gen) {
1704 if (ino < sctx->send_progress)
1705 ret = inode_state_did_create;
1707 ret = inode_state_will_create;
1711 } else if (!right_ret) {
1712 if (right_gen == gen) {
1713 if (ino < sctx->send_progress)
1714 ret = inode_state_did_delete;
1716 ret = inode_state_will_delete;
1728 static int is_inode_existent(struct send_ctx *sctx, u64 ino, u64 gen)
1732 if (ino == BTRFS_FIRST_FREE_OBJECTID)
1735 ret = get_cur_inode_state(sctx, ino, gen);
1739 if (ret == inode_state_no_change ||
1740 ret == inode_state_did_create ||
1741 ret == inode_state_will_delete)
1751 * Helper function to lookup a dir item in a dir.
1753 static int lookup_dir_item_inode(struct btrfs_root *root,
1754 u64 dir, const char *name, int name_len,
1758 struct btrfs_dir_item *di;
1759 struct btrfs_key key;
1760 struct btrfs_path *path;
1761 struct fscrypt_str name_str = FSTR_INIT((char *)name, name_len);
1763 path = alloc_path_for_send();
1767 di = btrfs_lookup_dir_item(NULL, root, path, dir, &name_str, 0);
1768 if (IS_ERR_OR_NULL(di)) {
1769 ret = di ? PTR_ERR(di) : -ENOENT;
1772 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
1773 if (key.type == BTRFS_ROOT_ITEM_KEY) {
1777 *found_inode = key.objectid;
1780 btrfs_free_path(path);
1785 * Looks up the first btrfs_inode_ref of a given ino. It returns the parent dir,
1786 * generation of the parent dir and the name of the dir entry.
1788 static int get_first_ref(struct btrfs_root *root, u64 ino,
1789 u64 *dir, u64 *dir_gen, struct fs_path *name)
1792 struct btrfs_key key;
1793 struct btrfs_key found_key;
1794 struct btrfs_path *path;
1798 path = alloc_path_for_send();
1803 key.type = BTRFS_INODE_REF_KEY;
1806 ret = btrfs_search_slot_for_read(root, &key, path, 1, 0);
1810 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1812 if (ret || found_key.objectid != ino ||
1813 (found_key.type != BTRFS_INODE_REF_KEY &&
1814 found_key.type != BTRFS_INODE_EXTREF_KEY)) {
1819 if (found_key.type == BTRFS_INODE_REF_KEY) {
1820 struct btrfs_inode_ref *iref;
1821 iref = btrfs_item_ptr(path->nodes[0], path->slots[0],
1822 struct btrfs_inode_ref);
1823 len = btrfs_inode_ref_name_len(path->nodes[0], iref);
1824 ret = fs_path_add_from_extent_buffer(name, path->nodes[0],
1825 (unsigned long)(iref + 1),
1827 parent_dir = found_key.offset;
1829 struct btrfs_inode_extref *extref;
1830 extref = btrfs_item_ptr(path->nodes[0], path->slots[0],
1831 struct btrfs_inode_extref);
1832 len = btrfs_inode_extref_name_len(path->nodes[0], extref);
1833 ret = fs_path_add_from_extent_buffer(name, path->nodes[0],
1834 (unsigned long)&extref->name, len);
1835 parent_dir = btrfs_inode_extref_parent(path->nodes[0], extref);
1839 btrfs_release_path(path);
1842 ret = get_inode_gen(root, parent_dir, dir_gen);
1850 btrfs_free_path(path);
1854 static int is_first_ref(struct btrfs_root *root,
1856 const char *name, int name_len)
1859 struct fs_path *tmp_name;
1862 tmp_name = fs_path_alloc();
1866 ret = get_first_ref(root, ino, &tmp_dir, NULL, tmp_name);
1870 if (dir != tmp_dir || name_len != fs_path_len(tmp_name)) {
1875 ret = !memcmp(tmp_name->start, name, name_len);
1878 fs_path_free(tmp_name);
1883 * Used by process_recorded_refs to determine if a new ref would overwrite an
1884 * already existing ref. In case it detects an overwrite, it returns the
1885 * inode/gen in who_ino/who_gen.
1886 * When an overwrite is detected, process_recorded_refs does proper orphanizing
1887 * to make sure later references to the overwritten inode are possible.
1888 * Orphanizing is however only required for the first ref of an inode.
1889 * process_recorded_refs does an additional is_first_ref check to see if
1890 * orphanizing is really required.
1892 static int will_overwrite_ref(struct send_ctx *sctx, u64 dir, u64 dir_gen,
1893 const char *name, int name_len,
1894 u64 *who_ino, u64 *who_gen, u64 *who_mode)
1898 u64 other_inode = 0;
1899 struct btrfs_inode_info info;
1901 if (!sctx->parent_root)
1904 ret = is_inode_existent(sctx, dir, dir_gen);
1909 * If we have a parent root we need to verify that the parent dir was
1910 * not deleted and then re-created, if it was then we have no overwrite
1911 * and we can just unlink this entry.
1913 if (sctx->parent_root && dir != BTRFS_FIRST_FREE_OBJECTID) {
1914 ret = get_inode_gen(sctx->parent_root, dir, &gen);
1915 if (ret < 0 && ret != -ENOENT)
1925 ret = lookup_dir_item_inode(sctx->parent_root, dir, name, name_len,
1927 if (ret < 0 && ret != -ENOENT)
1935 * Check if the overwritten ref was already processed. If yes, the ref
1936 * was already unlinked/moved, so we can safely assume that we will not
1937 * overwrite anything at this point in time.
1939 if (other_inode > sctx->send_progress ||
1940 is_waiting_for_move(sctx, other_inode)) {
1941 ret = get_inode_info(sctx->parent_root, other_inode, &info);
1946 *who_ino = other_inode;
1947 *who_gen = info.gen;
1948 *who_mode = info.mode;
1958 * Checks if the ref was overwritten by an already processed inode. This is
1959 * used by __get_cur_name_and_parent to find out if the ref was orphanized and
1960 * thus the orphan name needs be used.
1961 * process_recorded_refs also uses it to avoid unlinking of refs that were
1964 static int did_overwrite_ref(struct send_ctx *sctx,
1965 u64 dir, u64 dir_gen,
1966 u64 ino, u64 ino_gen,
1967 const char *name, int name_len)
1973 if (!sctx->parent_root)
1976 ret = is_inode_existent(sctx, dir, dir_gen);
1980 if (dir != BTRFS_FIRST_FREE_OBJECTID) {
1981 ret = get_inode_gen(sctx->send_root, dir, &gen);
1982 if (ret < 0 && ret != -ENOENT)
1992 /* check if the ref was overwritten by another ref */
1993 ret = lookup_dir_item_inode(sctx->send_root, dir, name, name_len,
1995 if (ret < 0 && ret != -ENOENT)
1998 /* was never and will never be overwritten */
2003 ret = get_inode_gen(sctx->send_root, ow_inode, &gen);
2007 if (ow_inode == ino && gen == ino_gen) {
2013 * We know that it is or will be overwritten. Check this now.
2014 * The current inode being processed might have been the one that caused
2015 * inode 'ino' to be orphanized, therefore check if ow_inode matches
2016 * the current inode being processed.
2018 if ((ow_inode < sctx->send_progress) ||
2019 (ino != sctx->cur_ino && ow_inode == sctx->cur_ino &&
2020 gen == sctx->cur_inode_gen))
2030 * Same as did_overwrite_ref, but also checks if it is the first ref of an inode
2031 * that got overwritten. This is used by process_recorded_refs to determine
2032 * if it has to use the path as returned by get_cur_path or the orphan name.
2034 static int did_overwrite_first_ref(struct send_ctx *sctx, u64 ino, u64 gen)
2037 struct fs_path *name = NULL;
2041 if (!sctx->parent_root)
2044 name = fs_path_alloc();
2048 ret = get_first_ref(sctx->parent_root, ino, &dir, &dir_gen, name);
2052 ret = did_overwrite_ref(sctx, dir, dir_gen, ino, gen,
2053 name->start, fs_path_len(name));
2061 * Insert a name cache entry. On 32bit kernels the radix tree index is 32bit,
2062 * so we need to do some special handling in case we have clashes. This function
2063 * takes care of this with the help of name_cache_entry::radix_list.
2064 * In case of error, nce is kfreed.
2066 static int name_cache_insert(struct send_ctx *sctx,
2067 struct name_cache_entry *nce)
2070 struct list_head *nce_head;
2072 nce_head = radix_tree_lookup(&sctx->name_cache,
2073 (unsigned long)nce->ino);
2075 nce_head = kmalloc(sizeof(*nce_head), GFP_KERNEL);
2080 INIT_LIST_HEAD(nce_head);
2082 ret = radix_tree_insert(&sctx->name_cache, nce->ino, nce_head);
2089 list_add_tail(&nce->radix_list, nce_head);
2090 list_add_tail(&nce->list, &sctx->name_cache_list);
2091 sctx->name_cache_size++;
2096 static void name_cache_delete(struct send_ctx *sctx,
2097 struct name_cache_entry *nce)
2099 struct list_head *nce_head;
2101 nce_head = radix_tree_lookup(&sctx->name_cache,
2102 (unsigned long)nce->ino);
2104 btrfs_err(sctx->send_root->fs_info,
2105 "name_cache_delete lookup failed ino %llu cache size %d, leaking memory",
2106 nce->ino, sctx->name_cache_size);
2109 list_del(&nce->radix_list);
2110 list_del(&nce->list);
2111 sctx->name_cache_size--;
2114 * We may not get to the final release of nce_head if the lookup fails
2116 if (nce_head && list_empty(nce_head)) {
2117 radix_tree_delete(&sctx->name_cache, (unsigned long)nce->ino);
2122 static struct name_cache_entry *name_cache_search(struct send_ctx *sctx,
2125 struct list_head *nce_head;
2126 struct name_cache_entry *cur;
2128 nce_head = radix_tree_lookup(&sctx->name_cache, (unsigned long)ino);
2132 list_for_each_entry(cur, nce_head, radix_list) {
2133 if (cur->ino == ino && cur->gen == gen)
2140 * Remove some entries from the beginning of name_cache_list.
2142 static void name_cache_clean_unused(struct send_ctx *sctx)
2144 struct name_cache_entry *nce;
2146 if (sctx->name_cache_size < SEND_CTX_NAME_CACHE_CLEAN_SIZE)
2149 while (sctx->name_cache_size > SEND_CTX_MAX_NAME_CACHE_SIZE) {
2150 nce = list_entry(sctx->name_cache_list.next,
2151 struct name_cache_entry, list);
2152 name_cache_delete(sctx, nce);
2157 static void name_cache_free(struct send_ctx *sctx)
2159 struct name_cache_entry *nce;
2161 while (!list_empty(&sctx->name_cache_list)) {
2162 nce = list_entry(sctx->name_cache_list.next,
2163 struct name_cache_entry, list);
2164 name_cache_delete(sctx, nce);
2170 * Used by get_cur_path for each ref up to the root.
2171 * Returns 0 if it succeeded.
2172 * Returns 1 if the inode is not existent or got overwritten. In that case, the
2173 * name is an orphan name. This instructs get_cur_path to stop iterating. If 1
2174 * is returned, parent_ino/parent_gen are not guaranteed to be valid.
2175 * Returns <0 in case of error.
2177 static int __get_cur_name_and_parent(struct send_ctx *sctx,
2181 struct fs_path *dest)
2185 struct name_cache_entry *nce = NULL;
2188 * First check if we already did a call to this function with the same
2189 * ino/gen. If yes, check if the cache entry is still up-to-date. If yes
2190 * return the cached result.
2192 nce = name_cache_search(sctx, ino, gen);
2194 if (ino < sctx->send_progress && nce->need_later_update) {
2195 name_cache_delete(sctx, nce);
2200 * Removes the entry from the list and adds it back to
2201 * the end. This marks the entry as recently used so
2202 * that name_cache_clean_unused does not remove it.
2204 list_move_tail(&nce->list, &sctx->name_cache_list);
2206 *parent_ino = nce->parent_ino;
2207 *parent_gen = nce->parent_gen;
2208 ret = fs_path_add(dest, nce->name, nce->name_len);
2217 * If the inode is not existent yet, add the orphan name and return 1.
2218 * This should only happen for the parent dir that we determine in
2219 * record_new_ref_if_needed().
2221 ret = is_inode_existent(sctx, ino, gen);
2226 ret = gen_unique_name(sctx, ino, gen, dest);
2234 * Depending on whether the inode was already processed or not, use
2235 * send_root or parent_root for ref lookup.
2237 if (ino < sctx->send_progress)
2238 ret = get_first_ref(sctx->send_root, ino,
2239 parent_ino, parent_gen, dest);
2241 ret = get_first_ref(sctx->parent_root, ino,
2242 parent_ino, parent_gen, dest);
2247 * Check if the ref was overwritten by an inode's ref that was processed
2248 * earlier. If yes, treat as orphan and return 1.
2250 ret = did_overwrite_ref(sctx, *parent_ino, *parent_gen, ino, gen,
2251 dest->start, dest->end - dest->start);
2255 fs_path_reset(dest);
2256 ret = gen_unique_name(sctx, ino, gen, dest);
2264 * Store the result of the lookup in the name cache.
2266 nce = kmalloc(sizeof(*nce) + fs_path_len(dest) + 1, GFP_KERNEL);
2274 nce->parent_ino = *parent_ino;
2275 nce->parent_gen = *parent_gen;
2276 nce->name_len = fs_path_len(dest);
2278 strcpy(nce->name, dest->start);
2280 if (ino < sctx->send_progress)
2281 nce->need_later_update = 0;
2283 nce->need_later_update = 1;
2285 nce_ret = name_cache_insert(sctx, nce);
2288 name_cache_clean_unused(sctx);
2295 * Magic happens here. This function returns the first ref to an inode as it
2296 * would look like while receiving the stream at this point in time.
2297 * We walk the path up to the root. For every inode in between, we check if it
2298 * was already processed/sent. If yes, we continue with the parent as found
2299 * in send_root. If not, we continue with the parent as found in parent_root.
2300 * If we encounter an inode that was deleted at this point in time, we use the
2301 * inodes "orphan" name instead of the real name and stop. Same with new inodes
2302 * that were not created yet and overwritten inodes/refs.
2304 * When do we have orphan inodes:
2305 * 1. When an inode is freshly created and thus no valid refs are available yet
2306 * 2. When a directory lost all it's refs (deleted) but still has dir items
2307 * inside which were not processed yet (pending for move/delete). If anyone
2308 * tried to get the path to the dir items, it would get a path inside that
2310 * 3. When an inode is moved around or gets new links, it may overwrite the ref
2311 * of an unprocessed inode. If in that case the first ref would be
2312 * overwritten, the overwritten inode gets "orphanized". Later when we
2313 * process this overwritten inode, it is restored at a new place by moving
2316 * sctx->send_progress tells this function at which point in time receiving
2319 static int get_cur_path(struct send_ctx *sctx, u64 ino, u64 gen,
2320 struct fs_path *dest)
2323 struct fs_path *name = NULL;
2324 u64 parent_inode = 0;
2328 name = fs_path_alloc();
2335 fs_path_reset(dest);
2337 while (!stop && ino != BTRFS_FIRST_FREE_OBJECTID) {
2338 struct waiting_dir_move *wdm;
2340 fs_path_reset(name);
2342 if (is_waiting_for_rm(sctx, ino, gen)) {
2343 ret = gen_unique_name(sctx, ino, gen, name);
2346 ret = fs_path_add_path(dest, name);
2350 wdm = get_waiting_dir_move(sctx, ino);
2351 if (wdm && wdm->orphanized) {
2352 ret = gen_unique_name(sctx, ino, gen, name);
2355 ret = get_first_ref(sctx->parent_root, ino,
2356 &parent_inode, &parent_gen, name);
2358 ret = __get_cur_name_and_parent(sctx, ino, gen,
2368 ret = fs_path_add_path(dest, name);
2379 fs_path_unreverse(dest);
2384 * Sends a BTRFS_SEND_C_SUBVOL command/item to userspace
2386 static int send_subvol_begin(struct send_ctx *sctx)
2389 struct btrfs_root *send_root = sctx->send_root;
2390 struct btrfs_root *parent_root = sctx->parent_root;
2391 struct btrfs_path *path;
2392 struct btrfs_key key;
2393 struct btrfs_root_ref *ref;
2394 struct extent_buffer *leaf;
2398 path = btrfs_alloc_path();
2402 name = kmalloc(BTRFS_PATH_NAME_MAX, GFP_KERNEL);
2404 btrfs_free_path(path);
2408 key.objectid = send_root->root_key.objectid;
2409 key.type = BTRFS_ROOT_BACKREF_KEY;
2412 ret = btrfs_search_slot_for_read(send_root->fs_info->tree_root,
2421 leaf = path->nodes[0];
2422 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2423 if (key.type != BTRFS_ROOT_BACKREF_KEY ||
2424 key.objectid != send_root->root_key.objectid) {
2428 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
2429 namelen = btrfs_root_ref_name_len(leaf, ref);
2430 read_extent_buffer(leaf, name, (unsigned long)(ref + 1), namelen);
2431 btrfs_release_path(path);
2434 ret = begin_cmd(sctx, BTRFS_SEND_C_SNAPSHOT);
2438 ret = begin_cmd(sctx, BTRFS_SEND_C_SUBVOL);
2443 TLV_PUT_STRING(sctx, BTRFS_SEND_A_PATH, name, namelen);
2445 if (!btrfs_is_empty_uuid(sctx->send_root->root_item.received_uuid))
2446 TLV_PUT_UUID(sctx, BTRFS_SEND_A_UUID,
2447 sctx->send_root->root_item.received_uuid);
2449 TLV_PUT_UUID(sctx, BTRFS_SEND_A_UUID,
2450 sctx->send_root->root_item.uuid);
2452 TLV_PUT_U64(sctx, BTRFS_SEND_A_CTRANSID,
2453 btrfs_root_ctransid(&sctx->send_root->root_item));
2455 if (!btrfs_is_empty_uuid(parent_root->root_item.received_uuid))
2456 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
2457 parent_root->root_item.received_uuid);
2459 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
2460 parent_root->root_item.uuid);
2461 TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_CTRANSID,
2462 btrfs_root_ctransid(&sctx->parent_root->root_item));
2465 ret = send_cmd(sctx);
2469 btrfs_free_path(path);
2474 static int send_truncate(struct send_ctx *sctx, u64 ino, u64 gen, u64 size)
2476 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2480 btrfs_debug(fs_info, "send_truncate %llu size=%llu", ino, size);
2482 p = fs_path_alloc();
2486 ret = begin_cmd(sctx, BTRFS_SEND_C_TRUNCATE);
2490 ret = get_cur_path(sctx, ino, gen, p);
2493 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2494 TLV_PUT_U64(sctx, BTRFS_SEND_A_SIZE, size);
2496 ret = send_cmd(sctx);
2504 static int send_chmod(struct send_ctx *sctx, u64 ino, u64 gen, u64 mode)
2506 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2510 btrfs_debug(fs_info, "send_chmod %llu mode=%llu", ino, mode);
2512 p = fs_path_alloc();
2516 ret = begin_cmd(sctx, BTRFS_SEND_C_CHMOD);
2520 ret = get_cur_path(sctx, ino, gen, p);
2523 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2524 TLV_PUT_U64(sctx, BTRFS_SEND_A_MODE, mode & 07777);
2526 ret = send_cmd(sctx);
2534 static int send_fileattr(struct send_ctx *sctx, u64 ino, u64 gen, u64 fileattr)
2536 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2540 if (sctx->proto < 2)
2543 btrfs_debug(fs_info, "send_fileattr %llu fileattr=%llu", ino, fileattr);
2545 p = fs_path_alloc();
2549 ret = begin_cmd(sctx, BTRFS_SEND_C_FILEATTR);
2553 ret = get_cur_path(sctx, ino, gen, p);
2556 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2557 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILEATTR, fileattr);
2559 ret = send_cmd(sctx);
2567 static int send_chown(struct send_ctx *sctx, u64 ino, u64 gen, u64 uid, u64 gid)
2569 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2573 btrfs_debug(fs_info, "send_chown %llu uid=%llu, gid=%llu",
2576 p = fs_path_alloc();
2580 ret = begin_cmd(sctx, BTRFS_SEND_C_CHOWN);
2584 ret = get_cur_path(sctx, ino, gen, p);
2587 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2588 TLV_PUT_U64(sctx, BTRFS_SEND_A_UID, uid);
2589 TLV_PUT_U64(sctx, BTRFS_SEND_A_GID, gid);
2591 ret = send_cmd(sctx);
2599 static int send_utimes(struct send_ctx *sctx, u64 ino, u64 gen)
2601 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2603 struct fs_path *p = NULL;
2604 struct btrfs_inode_item *ii;
2605 struct btrfs_path *path = NULL;
2606 struct extent_buffer *eb;
2607 struct btrfs_key key;
2610 btrfs_debug(fs_info, "send_utimes %llu", ino);
2612 p = fs_path_alloc();
2616 path = alloc_path_for_send();
2623 key.type = BTRFS_INODE_ITEM_KEY;
2625 ret = btrfs_search_slot(NULL, sctx->send_root, &key, path, 0, 0);
2631 eb = path->nodes[0];
2632 slot = path->slots[0];
2633 ii = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
2635 ret = begin_cmd(sctx, BTRFS_SEND_C_UTIMES);
2639 ret = get_cur_path(sctx, ino, gen, p);
2642 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2643 TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_ATIME, eb, &ii->atime);
2644 TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_MTIME, eb, &ii->mtime);
2645 TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_CTIME, eb, &ii->ctime);
2646 if (sctx->proto >= 2)
2647 TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_OTIME, eb, &ii->otime);
2649 ret = send_cmd(sctx);
2654 btrfs_free_path(path);
2659 * Sends a BTRFS_SEND_C_MKXXX or SYMLINK command to user space. We don't have
2660 * a valid path yet because we did not process the refs yet. So, the inode
2661 * is created as orphan.
2663 static int send_create_inode(struct send_ctx *sctx, u64 ino)
2665 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2669 struct btrfs_inode_info info;
2674 btrfs_debug(fs_info, "send_create_inode %llu", ino);
2676 p = fs_path_alloc();
2680 if (ino != sctx->cur_ino) {
2681 ret = get_inode_info(sctx->send_root, ino, &info);
2688 gen = sctx->cur_inode_gen;
2689 mode = sctx->cur_inode_mode;
2690 rdev = sctx->cur_inode_rdev;
2693 if (S_ISREG(mode)) {
2694 cmd = BTRFS_SEND_C_MKFILE;
2695 } else if (S_ISDIR(mode)) {
2696 cmd = BTRFS_SEND_C_MKDIR;
2697 } else if (S_ISLNK(mode)) {
2698 cmd = BTRFS_SEND_C_SYMLINK;
2699 } else if (S_ISCHR(mode) || S_ISBLK(mode)) {
2700 cmd = BTRFS_SEND_C_MKNOD;
2701 } else if (S_ISFIFO(mode)) {
2702 cmd = BTRFS_SEND_C_MKFIFO;
2703 } else if (S_ISSOCK(mode)) {
2704 cmd = BTRFS_SEND_C_MKSOCK;
2706 btrfs_warn(sctx->send_root->fs_info, "unexpected inode type %o",
2707 (int)(mode & S_IFMT));
2712 ret = begin_cmd(sctx, cmd);
2716 ret = gen_unique_name(sctx, ino, gen, p);
2720 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2721 TLV_PUT_U64(sctx, BTRFS_SEND_A_INO, ino);
2723 if (S_ISLNK(mode)) {
2725 ret = read_symlink(sctx->send_root, ino, p);
2728 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH_LINK, p);
2729 } else if (S_ISCHR(mode) || S_ISBLK(mode) ||
2730 S_ISFIFO(mode) || S_ISSOCK(mode)) {
2731 TLV_PUT_U64(sctx, BTRFS_SEND_A_RDEV, new_encode_dev(rdev));
2732 TLV_PUT_U64(sctx, BTRFS_SEND_A_MODE, mode);
2735 ret = send_cmd(sctx);
2747 * We need some special handling for inodes that get processed before the parent
2748 * directory got created. See process_recorded_refs for details.
2749 * This function does the check if we already created the dir out of order.
2751 static int did_create_dir(struct send_ctx *sctx, u64 dir)
2755 struct btrfs_path *path = NULL;
2756 struct btrfs_key key;
2757 struct btrfs_key found_key;
2758 struct btrfs_key di_key;
2759 struct btrfs_dir_item *di;
2761 path = alloc_path_for_send();
2766 key.type = BTRFS_DIR_INDEX_KEY;
2769 btrfs_for_each_slot(sctx->send_root, &key, &found_key, path, iter_ret) {
2770 struct extent_buffer *eb = path->nodes[0];
2772 if (found_key.objectid != key.objectid ||
2773 found_key.type != key.type) {
2778 di = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dir_item);
2779 btrfs_dir_item_key_to_cpu(eb, di, &di_key);
2781 if (di_key.type != BTRFS_ROOT_ITEM_KEY &&
2782 di_key.objectid < sctx->send_progress) {
2787 /* Catch error found during iteration */
2791 btrfs_free_path(path);
2796 * Only creates the inode if it is:
2797 * 1. Not a directory
2798 * 2. Or a directory which was not created already due to out of order
2799 * directories. See did_create_dir and process_recorded_refs for details.
2801 static int send_create_inode_if_needed(struct send_ctx *sctx)
2805 if (S_ISDIR(sctx->cur_inode_mode)) {
2806 ret = did_create_dir(sctx, sctx->cur_ino);
2813 return send_create_inode(sctx, sctx->cur_ino);
2816 struct recorded_ref {
2817 struct list_head list;
2819 struct fs_path *full_path;
2823 struct rb_node node;
2824 struct rb_root *root;
2827 static struct recorded_ref *recorded_ref_alloc(void)
2829 struct recorded_ref *ref;
2831 ref = kzalloc(sizeof(*ref), GFP_KERNEL);
2834 RB_CLEAR_NODE(&ref->node);
2835 INIT_LIST_HEAD(&ref->list);
2839 static void recorded_ref_free(struct recorded_ref *ref)
2843 if (!RB_EMPTY_NODE(&ref->node))
2844 rb_erase(&ref->node, ref->root);
2845 list_del(&ref->list);
2846 fs_path_free(ref->full_path);
2850 static void set_ref_path(struct recorded_ref *ref, struct fs_path *path)
2852 ref->full_path = path;
2853 ref->name = (char *)kbasename(ref->full_path->start);
2854 ref->name_len = ref->full_path->end - ref->name;
2857 static int dup_ref(struct recorded_ref *ref, struct list_head *list)
2859 struct recorded_ref *new;
2861 new = recorded_ref_alloc();
2865 new->dir = ref->dir;
2866 new->dir_gen = ref->dir_gen;
2867 list_add_tail(&new->list, list);
2871 static void __free_recorded_refs(struct list_head *head)
2873 struct recorded_ref *cur;
2875 while (!list_empty(head)) {
2876 cur = list_entry(head->next, struct recorded_ref, list);
2877 recorded_ref_free(cur);
2881 static void free_recorded_refs(struct send_ctx *sctx)
2883 __free_recorded_refs(&sctx->new_refs);
2884 __free_recorded_refs(&sctx->deleted_refs);
2888 * Renames/moves a file/dir to its orphan name. Used when the first
2889 * ref of an unprocessed inode gets overwritten and for all non empty
2892 static int orphanize_inode(struct send_ctx *sctx, u64 ino, u64 gen,
2893 struct fs_path *path)
2896 struct fs_path *orphan;
2898 orphan = fs_path_alloc();
2902 ret = gen_unique_name(sctx, ino, gen, orphan);
2906 ret = send_rename(sctx, path, orphan);
2909 fs_path_free(orphan);
2913 static struct orphan_dir_info *add_orphan_dir_info(struct send_ctx *sctx,
2914 u64 dir_ino, u64 dir_gen)
2916 struct rb_node **p = &sctx->orphan_dirs.rb_node;
2917 struct rb_node *parent = NULL;
2918 struct orphan_dir_info *entry, *odi;
2922 entry = rb_entry(parent, struct orphan_dir_info, node);
2923 if (dir_ino < entry->ino)
2925 else if (dir_ino > entry->ino)
2926 p = &(*p)->rb_right;
2927 else if (dir_gen < entry->gen)
2929 else if (dir_gen > entry->gen)
2930 p = &(*p)->rb_right;
2935 odi = kmalloc(sizeof(*odi), GFP_KERNEL);
2937 return ERR_PTR(-ENOMEM);
2940 odi->last_dir_index_offset = 0;
2942 rb_link_node(&odi->node, parent, p);
2943 rb_insert_color(&odi->node, &sctx->orphan_dirs);
2947 static struct orphan_dir_info *get_orphan_dir_info(struct send_ctx *sctx,
2948 u64 dir_ino, u64 gen)
2950 struct rb_node *n = sctx->orphan_dirs.rb_node;
2951 struct orphan_dir_info *entry;
2954 entry = rb_entry(n, struct orphan_dir_info, node);
2955 if (dir_ino < entry->ino)
2957 else if (dir_ino > entry->ino)
2959 else if (gen < entry->gen)
2961 else if (gen > entry->gen)
2969 static int is_waiting_for_rm(struct send_ctx *sctx, u64 dir_ino, u64 gen)
2971 struct orphan_dir_info *odi = get_orphan_dir_info(sctx, dir_ino, gen);
2976 static void free_orphan_dir_info(struct send_ctx *sctx,
2977 struct orphan_dir_info *odi)
2981 rb_erase(&odi->node, &sctx->orphan_dirs);
2986 * Returns 1 if a directory can be removed at this point in time.
2987 * We check this by iterating all dir items and checking if the inode behind
2988 * the dir item was already processed.
2990 static int can_rmdir(struct send_ctx *sctx, u64 dir, u64 dir_gen,
2995 struct btrfs_root *root = sctx->parent_root;
2996 struct btrfs_path *path;
2997 struct btrfs_key key;
2998 struct btrfs_key found_key;
2999 struct btrfs_key loc;
3000 struct btrfs_dir_item *di;
3001 struct orphan_dir_info *odi = NULL;
3004 * Don't try to rmdir the top/root subvolume dir.
3006 if (dir == BTRFS_FIRST_FREE_OBJECTID)
3009 path = alloc_path_for_send();
3014 key.type = BTRFS_DIR_INDEX_KEY;
3017 odi = get_orphan_dir_info(sctx, dir, dir_gen);
3019 key.offset = odi->last_dir_index_offset;
3021 btrfs_for_each_slot(root, &key, &found_key, path, iter_ret) {
3022 struct waiting_dir_move *dm;
3024 if (found_key.objectid != key.objectid ||
3025 found_key.type != key.type)
3028 di = btrfs_item_ptr(path->nodes[0], path->slots[0],
3029 struct btrfs_dir_item);
3030 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &loc);
3032 dm = get_waiting_dir_move(sctx, loc.objectid);
3034 odi = add_orphan_dir_info(sctx, dir, dir_gen);
3040 odi->last_dir_index_offset = found_key.offset;
3041 dm->rmdir_ino = dir;
3042 dm->rmdir_gen = dir_gen;
3047 if (loc.objectid > send_progress) {
3048 odi = add_orphan_dir_info(sctx, dir, dir_gen);
3054 odi->last_dir_index_offset = found_key.offset;
3063 free_orphan_dir_info(sctx, odi);
3068 btrfs_free_path(path);
3072 static int is_waiting_for_move(struct send_ctx *sctx, u64 ino)
3074 struct waiting_dir_move *entry = get_waiting_dir_move(sctx, ino);
3076 return entry != NULL;
3079 static int add_waiting_dir_move(struct send_ctx *sctx, u64 ino, bool orphanized)
3081 struct rb_node **p = &sctx->waiting_dir_moves.rb_node;
3082 struct rb_node *parent = NULL;
3083 struct waiting_dir_move *entry, *dm;
3085 dm = kmalloc(sizeof(*dm), GFP_KERNEL);
3091 dm->orphanized = orphanized;
3095 entry = rb_entry(parent, struct waiting_dir_move, node);
3096 if (ino < entry->ino) {
3098 } else if (ino > entry->ino) {
3099 p = &(*p)->rb_right;
3106 rb_link_node(&dm->node, parent, p);
3107 rb_insert_color(&dm->node, &sctx->waiting_dir_moves);
3111 static struct waiting_dir_move *
3112 get_waiting_dir_move(struct send_ctx *sctx, u64 ino)
3114 struct rb_node *n = sctx->waiting_dir_moves.rb_node;
3115 struct waiting_dir_move *entry;
3118 entry = rb_entry(n, struct waiting_dir_move, node);
3119 if (ino < entry->ino)
3121 else if (ino > entry->ino)
3129 static void free_waiting_dir_move(struct send_ctx *sctx,
3130 struct waiting_dir_move *dm)
3134 rb_erase(&dm->node, &sctx->waiting_dir_moves);
3138 static int add_pending_dir_move(struct send_ctx *sctx,
3142 struct list_head *new_refs,
3143 struct list_head *deleted_refs,
3144 const bool is_orphan)
3146 struct rb_node **p = &sctx->pending_dir_moves.rb_node;
3147 struct rb_node *parent = NULL;
3148 struct pending_dir_move *entry = NULL, *pm;
3149 struct recorded_ref *cur;
3153 pm = kmalloc(sizeof(*pm), GFP_KERNEL);
3156 pm->parent_ino = parent_ino;
3159 INIT_LIST_HEAD(&pm->list);
3160 INIT_LIST_HEAD(&pm->update_refs);
3161 RB_CLEAR_NODE(&pm->node);
3165 entry = rb_entry(parent, struct pending_dir_move, node);
3166 if (parent_ino < entry->parent_ino) {
3168 } else if (parent_ino > entry->parent_ino) {
3169 p = &(*p)->rb_right;
3176 list_for_each_entry(cur, deleted_refs, list) {
3177 ret = dup_ref(cur, &pm->update_refs);
3181 list_for_each_entry(cur, new_refs, list) {
3182 ret = dup_ref(cur, &pm->update_refs);
3187 ret = add_waiting_dir_move(sctx, pm->ino, is_orphan);
3192 list_add_tail(&pm->list, &entry->list);
3194 rb_link_node(&pm->node, parent, p);
3195 rb_insert_color(&pm->node, &sctx->pending_dir_moves);
3200 __free_recorded_refs(&pm->update_refs);
3206 static struct pending_dir_move *get_pending_dir_moves(struct send_ctx *sctx,
3209 struct rb_node *n = sctx->pending_dir_moves.rb_node;
3210 struct pending_dir_move *entry;
3213 entry = rb_entry(n, struct pending_dir_move, node);
3214 if (parent_ino < entry->parent_ino)
3216 else if (parent_ino > entry->parent_ino)
3224 static int path_loop(struct send_ctx *sctx, struct fs_path *name,
3225 u64 ino, u64 gen, u64 *ancestor_ino)
3228 u64 parent_inode = 0;
3230 u64 start_ino = ino;
3233 while (ino != BTRFS_FIRST_FREE_OBJECTID) {
3234 fs_path_reset(name);
3236 if (is_waiting_for_rm(sctx, ino, gen))
3238 if (is_waiting_for_move(sctx, ino)) {
3239 if (*ancestor_ino == 0)
3240 *ancestor_ino = ino;
3241 ret = get_first_ref(sctx->parent_root, ino,
3242 &parent_inode, &parent_gen, name);
3244 ret = __get_cur_name_and_parent(sctx, ino, gen,
3254 if (parent_inode == start_ino) {
3256 if (*ancestor_ino == 0)
3257 *ancestor_ino = ino;
3266 static int apply_dir_move(struct send_ctx *sctx, struct pending_dir_move *pm)
3268 struct fs_path *from_path = NULL;
3269 struct fs_path *to_path = NULL;
3270 struct fs_path *name = NULL;
3271 u64 orig_progress = sctx->send_progress;
3272 struct recorded_ref *cur;
3273 u64 parent_ino, parent_gen;
3274 struct waiting_dir_move *dm = NULL;
3281 name = fs_path_alloc();
3282 from_path = fs_path_alloc();
3283 if (!name || !from_path) {
3288 dm = get_waiting_dir_move(sctx, pm->ino);
3290 rmdir_ino = dm->rmdir_ino;
3291 rmdir_gen = dm->rmdir_gen;
3292 is_orphan = dm->orphanized;
3293 free_waiting_dir_move(sctx, dm);
3296 ret = gen_unique_name(sctx, pm->ino,
3297 pm->gen, from_path);
3299 ret = get_first_ref(sctx->parent_root, pm->ino,
3300 &parent_ino, &parent_gen, name);
3303 ret = get_cur_path(sctx, parent_ino, parent_gen,
3307 ret = fs_path_add_path(from_path, name);
3312 sctx->send_progress = sctx->cur_ino + 1;
3313 ret = path_loop(sctx, name, pm->ino, pm->gen, &ancestor);
3317 LIST_HEAD(deleted_refs);
3318 ASSERT(ancestor > BTRFS_FIRST_FREE_OBJECTID);
3319 ret = add_pending_dir_move(sctx, pm->ino, pm->gen, ancestor,
3320 &pm->update_refs, &deleted_refs,
3325 dm = get_waiting_dir_move(sctx, pm->ino);
3327 dm->rmdir_ino = rmdir_ino;
3328 dm->rmdir_gen = rmdir_gen;
3332 fs_path_reset(name);
3335 ret = get_cur_path(sctx, pm->ino, pm->gen, to_path);
3339 ret = send_rename(sctx, from_path, to_path);
3344 struct orphan_dir_info *odi;
3347 odi = get_orphan_dir_info(sctx, rmdir_ino, rmdir_gen);
3349 /* already deleted */
3354 ret = can_rmdir(sctx, rmdir_ino, gen, sctx->cur_ino);
3360 name = fs_path_alloc();
3365 ret = get_cur_path(sctx, rmdir_ino, gen, name);
3368 ret = send_rmdir(sctx, name);
3374 ret = send_utimes(sctx, pm->ino, pm->gen);
3379 * After rename/move, need to update the utimes of both new parent(s)
3380 * and old parent(s).
3382 list_for_each_entry(cur, &pm->update_refs, list) {
3384 * The parent inode might have been deleted in the send snapshot
3386 ret = get_inode_info(sctx->send_root, cur->dir, NULL);
3387 if (ret == -ENOENT) {
3394 ret = send_utimes(sctx, cur->dir, cur->dir_gen);
3401 fs_path_free(from_path);
3402 fs_path_free(to_path);
3403 sctx->send_progress = orig_progress;
3408 static void free_pending_move(struct send_ctx *sctx, struct pending_dir_move *m)
3410 if (!list_empty(&m->list))
3412 if (!RB_EMPTY_NODE(&m->node))
3413 rb_erase(&m->node, &sctx->pending_dir_moves);
3414 __free_recorded_refs(&m->update_refs);
3418 static void tail_append_pending_moves(struct send_ctx *sctx,
3419 struct pending_dir_move *moves,
3420 struct list_head *stack)
3422 if (list_empty(&moves->list)) {
3423 list_add_tail(&moves->list, stack);
3426 list_splice_init(&moves->list, &list);
3427 list_add_tail(&moves->list, stack);
3428 list_splice_tail(&list, stack);
3430 if (!RB_EMPTY_NODE(&moves->node)) {
3431 rb_erase(&moves->node, &sctx->pending_dir_moves);
3432 RB_CLEAR_NODE(&moves->node);
3436 static int apply_children_dir_moves(struct send_ctx *sctx)
3438 struct pending_dir_move *pm;
3439 struct list_head stack;
3440 u64 parent_ino = sctx->cur_ino;
3443 pm = get_pending_dir_moves(sctx, parent_ino);
3447 INIT_LIST_HEAD(&stack);
3448 tail_append_pending_moves(sctx, pm, &stack);
3450 while (!list_empty(&stack)) {
3451 pm = list_first_entry(&stack, struct pending_dir_move, list);
3452 parent_ino = pm->ino;
3453 ret = apply_dir_move(sctx, pm);
3454 free_pending_move(sctx, pm);
3457 pm = get_pending_dir_moves(sctx, parent_ino);
3459 tail_append_pending_moves(sctx, pm, &stack);
3464 while (!list_empty(&stack)) {
3465 pm = list_first_entry(&stack, struct pending_dir_move, list);
3466 free_pending_move(sctx, pm);
3472 * We might need to delay a directory rename even when no ancestor directory
3473 * (in the send root) with a higher inode number than ours (sctx->cur_ino) was
3474 * renamed. This happens when we rename a directory to the old name (the name
3475 * in the parent root) of some other unrelated directory that got its rename
3476 * delayed due to some ancestor with higher number that got renamed.
3482 * |---- a/ (ino 257)
3483 * | |---- file (ino 260)
3485 * |---- b/ (ino 258)
3486 * |---- c/ (ino 259)
3490 * |---- a/ (ino 258)
3491 * |---- x/ (ino 259)
3492 * |---- y/ (ino 257)
3493 * |----- file (ino 260)
3495 * Here we can not rename 258 from 'b' to 'a' without the rename of inode 257
3496 * from 'a' to 'x/y' happening first, which in turn depends on the rename of
3497 * inode 259 from 'c' to 'x'. So the order of rename commands the send stream
3500 * 1 - rename 259 from 'c' to 'x'
3501 * 2 - rename 257 from 'a' to 'x/y'
3502 * 3 - rename 258 from 'b' to 'a'
3504 * Returns 1 if the rename of sctx->cur_ino needs to be delayed, 0 if it can
3505 * be done right away and < 0 on error.
3507 static int wait_for_dest_dir_move(struct send_ctx *sctx,
3508 struct recorded_ref *parent_ref,
3509 const bool is_orphan)
3511 struct btrfs_fs_info *fs_info = sctx->parent_root->fs_info;
3512 struct btrfs_path *path;
3513 struct btrfs_key key;
3514 struct btrfs_key di_key;
3515 struct btrfs_dir_item *di;
3519 struct waiting_dir_move *wdm;
3521 if (RB_EMPTY_ROOT(&sctx->waiting_dir_moves))
3524 path = alloc_path_for_send();
3528 key.objectid = parent_ref->dir;
3529 key.type = BTRFS_DIR_ITEM_KEY;
3530 key.offset = btrfs_name_hash(parent_ref->name, parent_ref->name_len);
3532 ret = btrfs_search_slot(NULL, sctx->parent_root, &key, path, 0, 0);
3535 } else if (ret > 0) {
3540 di = btrfs_match_dir_item_name(fs_info, path, parent_ref->name,
3541 parent_ref->name_len);
3547 * di_key.objectid has the number of the inode that has a dentry in the
3548 * parent directory with the same name that sctx->cur_ino is being
3549 * renamed to. We need to check if that inode is in the send root as
3550 * well and if it is currently marked as an inode with a pending rename,
3551 * if it is, we need to delay the rename of sctx->cur_ino as well, so
3552 * that it happens after that other inode is renamed.
3554 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &di_key);
3555 if (di_key.type != BTRFS_INODE_ITEM_KEY) {
3560 ret = get_inode_gen(sctx->parent_root, di_key.objectid, &left_gen);
3563 ret = get_inode_gen(sctx->send_root, di_key.objectid, &right_gen);
3570 /* Different inode, no need to delay the rename of sctx->cur_ino */
3571 if (right_gen != left_gen) {
3576 wdm = get_waiting_dir_move(sctx, di_key.objectid);
3577 if (wdm && !wdm->orphanized) {
3578 ret = add_pending_dir_move(sctx,
3580 sctx->cur_inode_gen,
3583 &sctx->deleted_refs,
3589 btrfs_free_path(path);
3594 * Check if inode ino2, or any of its ancestors, is inode ino1.
3595 * Return 1 if true, 0 if false and < 0 on error.
3597 static int check_ino_in_path(struct btrfs_root *root,
3602 struct fs_path *fs_path)
3607 return ino1_gen == ino2_gen;
3609 while (ino > BTRFS_FIRST_FREE_OBJECTID) {
3614 fs_path_reset(fs_path);
3615 ret = get_first_ref(root, ino, &parent, &parent_gen, fs_path);
3619 return parent_gen == ino1_gen;
3626 * Check if inode ino1 is an ancestor of inode ino2 in the given root for any
3627 * possible path (in case ino2 is not a directory and has multiple hard links).
3628 * Return 1 if true, 0 if false and < 0 on error.
3630 static int is_ancestor(struct btrfs_root *root,
3634 struct fs_path *fs_path)
3636 bool free_fs_path = false;
3639 struct btrfs_path *path = NULL;
3640 struct btrfs_key key;
3643 fs_path = fs_path_alloc();
3646 free_fs_path = true;
3649 path = alloc_path_for_send();
3655 key.objectid = ino2;
3656 key.type = BTRFS_INODE_REF_KEY;
3659 btrfs_for_each_slot(root, &key, &key, path, iter_ret) {
3660 struct extent_buffer *leaf = path->nodes[0];
3661 int slot = path->slots[0];
3665 if (key.objectid != ino2)
3667 if (key.type != BTRFS_INODE_REF_KEY &&
3668 key.type != BTRFS_INODE_EXTREF_KEY)
3671 item_size = btrfs_item_size(leaf, slot);
3672 while (cur_offset < item_size) {
3676 if (key.type == BTRFS_INODE_EXTREF_KEY) {
3678 struct btrfs_inode_extref *extref;
3680 ptr = btrfs_item_ptr_offset(leaf, slot);
3681 extref = (struct btrfs_inode_extref *)
3683 parent = btrfs_inode_extref_parent(leaf,
3685 cur_offset += sizeof(*extref);
3686 cur_offset += btrfs_inode_extref_name_len(leaf,
3689 parent = key.offset;
3690 cur_offset = item_size;
3693 ret = get_inode_gen(root, parent, &parent_gen);
3696 ret = check_ino_in_path(root, ino1, ino1_gen,
3697 parent, parent_gen, fs_path);
3707 btrfs_free_path(path);
3709 fs_path_free(fs_path);
3713 static int wait_for_parent_move(struct send_ctx *sctx,
3714 struct recorded_ref *parent_ref,
3715 const bool is_orphan)
3718 u64 ino = parent_ref->dir;
3719 u64 ino_gen = parent_ref->dir_gen;
3720 u64 parent_ino_before, parent_ino_after;
3721 struct fs_path *path_before = NULL;
3722 struct fs_path *path_after = NULL;
3725 path_after = fs_path_alloc();
3726 path_before = fs_path_alloc();
3727 if (!path_after || !path_before) {
3733 * Our current directory inode may not yet be renamed/moved because some
3734 * ancestor (immediate or not) has to be renamed/moved first. So find if
3735 * such ancestor exists and make sure our own rename/move happens after
3736 * that ancestor is processed to avoid path build infinite loops (done
3737 * at get_cur_path()).
3739 while (ino > BTRFS_FIRST_FREE_OBJECTID) {
3740 u64 parent_ino_after_gen;
3742 if (is_waiting_for_move(sctx, ino)) {
3744 * If the current inode is an ancestor of ino in the
3745 * parent root, we need to delay the rename of the
3746 * current inode, otherwise don't delayed the rename
3747 * because we can end up with a circular dependency
3748 * of renames, resulting in some directories never
3749 * getting the respective rename operations issued in
3750 * the send stream or getting into infinite path build
3753 ret = is_ancestor(sctx->parent_root,
3754 sctx->cur_ino, sctx->cur_inode_gen,
3760 fs_path_reset(path_before);
3761 fs_path_reset(path_after);
3763 ret = get_first_ref(sctx->send_root, ino, &parent_ino_after,
3764 &parent_ino_after_gen, path_after);
3767 ret = get_first_ref(sctx->parent_root, ino, &parent_ino_before,
3769 if (ret < 0 && ret != -ENOENT) {
3771 } else if (ret == -ENOENT) {
3776 len1 = fs_path_len(path_before);
3777 len2 = fs_path_len(path_after);
3778 if (ino > sctx->cur_ino &&
3779 (parent_ino_before != parent_ino_after || len1 != len2 ||
3780 memcmp(path_before->start, path_after->start, len1))) {
3783 ret = get_inode_gen(sctx->parent_root, ino, &parent_ino_gen);
3786 if (ino_gen == parent_ino_gen) {
3791 ino = parent_ino_after;
3792 ino_gen = parent_ino_after_gen;
3796 fs_path_free(path_before);
3797 fs_path_free(path_after);
3800 ret = add_pending_dir_move(sctx,
3802 sctx->cur_inode_gen,
3805 &sctx->deleted_refs,
3814 static int update_ref_path(struct send_ctx *sctx, struct recorded_ref *ref)
3817 struct fs_path *new_path;
3820 * Our reference's name member points to its full_path member string, so
3821 * we use here a new path.
3823 new_path = fs_path_alloc();
3827 ret = get_cur_path(sctx, ref->dir, ref->dir_gen, new_path);
3829 fs_path_free(new_path);
3832 ret = fs_path_add(new_path, ref->name, ref->name_len);
3834 fs_path_free(new_path);
3838 fs_path_free(ref->full_path);
3839 set_ref_path(ref, new_path);
3845 * When processing the new references for an inode we may orphanize an existing
3846 * directory inode because its old name conflicts with one of the new references
3847 * of the current inode. Later, when processing another new reference of our
3848 * inode, we might need to orphanize another inode, but the path we have in the
3849 * reference reflects the pre-orphanization name of the directory we previously
3850 * orphanized. For example:
3852 * parent snapshot looks like:
3855 * |----- f1 (ino 257)
3856 * |----- f2 (ino 258)
3857 * |----- d1/ (ino 259)
3858 * |----- d2/ (ino 260)
3860 * send snapshot looks like:
3863 * |----- d1 (ino 258)
3864 * |----- f2/ (ino 259)
3865 * |----- f2_link/ (ino 260)
3866 * | |----- f1 (ino 257)
3868 * |----- d2 (ino 258)
3870 * When processing inode 257 we compute the name for inode 259 as "d1", and we
3871 * cache it in the name cache. Later when we start processing inode 258, when
3872 * collecting all its new references we set a full path of "d1/d2" for its new
3873 * reference with name "d2". When we start processing the new references we
3874 * start by processing the new reference with name "d1", and this results in
3875 * orphanizing inode 259, since its old reference causes a conflict. Then we
3876 * move on the next new reference, with name "d2", and we find out we must
3877 * orphanize inode 260, as its old reference conflicts with ours - but for the
3878 * orphanization we use a source path corresponding to the path we stored in the
3879 * new reference, which is "d1/d2" and not "o259-6-0/d2" - this makes the
3880 * receiver fail since the path component "d1/" no longer exists, it was renamed
3881 * to "o259-6-0/" when processing the previous new reference. So in this case we
3882 * must recompute the path in the new reference and use it for the new
3883 * orphanization operation.
3885 static int refresh_ref_path(struct send_ctx *sctx, struct recorded_ref *ref)
3890 name = kmemdup(ref->name, ref->name_len, GFP_KERNEL);
3894 fs_path_reset(ref->full_path);
3895 ret = get_cur_path(sctx, ref->dir, ref->dir_gen, ref->full_path);
3899 ret = fs_path_add(ref->full_path, name, ref->name_len);
3903 /* Update the reference's base name pointer. */
3904 set_ref_path(ref, ref->full_path);
3911 * This does all the move/link/unlink/rmdir magic.
3913 static int process_recorded_refs(struct send_ctx *sctx, int *pending_move)
3915 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
3917 struct recorded_ref *cur;
3918 struct recorded_ref *cur2;
3919 struct list_head check_dirs;
3920 struct fs_path *valid_path = NULL;
3924 int did_overwrite = 0;
3926 u64 last_dir_ino_rm = 0;
3927 bool can_rename = true;
3928 bool orphanized_dir = false;
3929 bool orphanized_ancestor = false;
3931 btrfs_debug(fs_info, "process_recorded_refs %llu", sctx->cur_ino);
3934 * This should never happen as the root dir always has the same ref
3935 * which is always '..'
3937 BUG_ON(sctx->cur_ino <= BTRFS_FIRST_FREE_OBJECTID);
3938 INIT_LIST_HEAD(&check_dirs);
3940 valid_path = fs_path_alloc();
3947 * First, check if the first ref of the current inode was overwritten
3948 * before. If yes, we know that the current inode was already orphanized
3949 * and thus use the orphan name. If not, we can use get_cur_path to
3950 * get the path of the first ref as it would like while receiving at
3951 * this point in time.
3952 * New inodes are always orphan at the beginning, so force to use the
3953 * orphan name in this case.
3954 * The first ref is stored in valid_path and will be updated if it
3955 * gets moved around.
3957 if (!sctx->cur_inode_new) {
3958 ret = did_overwrite_first_ref(sctx, sctx->cur_ino,
3959 sctx->cur_inode_gen);
3965 if (sctx->cur_inode_new || did_overwrite) {
3966 ret = gen_unique_name(sctx, sctx->cur_ino,
3967 sctx->cur_inode_gen, valid_path);
3972 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen,
3979 * Before doing any rename and link operations, do a first pass on the
3980 * new references to orphanize any unprocessed inodes that may have a
3981 * reference that conflicts with one of the new references of the current
3982 * inode. This needs to happen first because a new reference may conflict
3983 * with the old reference of a parent directory, so we must make sure
3984 * that the path used for link and rename commands don't use an
3985 * orphanized name when an ancestor was not yet orphanized.
3992 * |----- testdir/ (ino 259)
3993 * | |----- a (ino 257)
3995 * |----- b (ino 258)
4000 * |----- testdir_2/ (ino 259)
4001 * | |----- a (ino 260)
4003 * |----- testdir (ino 257)
4004 * |----- b (ino 257)
4005 * |----- b2 (ino 258)
4007 * Processing the new reference for inode 257 with name "b" may happen
4008 * before processing the new reference with name "testdir". If so, we
4009 * must make sure that by the time we send a link command to create the
4010 * hard link "b", inode 259 was already orphanized, since the generated
4011 * path in "valid_path" already contains the orphanized name for 259.
4012 * We are processing inode 257, so only later when processing 259 we do
4013 * the rename operation to change its temporary (orphanized) name to
4016 list_for_each_entry(cur, &sctx->new_refs, list) {
4017 ret = get_cur_inode_state(sctx, cur->dir, cur->dir_gen);
4020 if (ret == inode_state_will_create)
4024 * Check if this new ref would overwrite the first ref of another
4025 * unprocessed inode. If yes, orphanize the overwritten inode.
4026 * If we find an overwritten ref that is not the first ref,
4029 ret = will_overwrite_ref(sctx, cur->dir, cur->dir_gen,
4030 cur->name, cur->name_len,
4031 &ow_inode, &ow_gen, &ow_mode);
4035 ret = is_first_ref(sctx->parent_root,
4036 ow_inode, cur->dir, cur->name,
4041 struct name_cache_entry *nce;
4042 struct waiting_dir_move *wdm;
4044 if (orphanized_dir) {
4045 ret = refresh_ref_path(sctx, cur);
4050 ret = orphanize_inode(sctx, ow_inode, ow_gen,
4054 if (S_ISDIR(ow_mode))
4055 orphanized_dir = true;
4058 * If ow_inode has its rename operation delayed
4059 * make sure that its orphanized name is used in
4060 * the source path when performing its rename
4063 if (is_waiting_for_move(sctx, ow_inode)) {
4064 wdm = get_waiting_dir_move(sctx,
4067 wdm->orphanized = true;
4071 * Make sure we clear our orphanized inode's
4072 * name from the name cache. This is because the
4073 * inode ow_inode might be an ancestor of some
4074 * other inode that will be orphanized as well
4075 * later and has an inode number greater than
4076 * sctx->send_progress. We need to prevent
4077 * future name lookups from using the old name
4078 * and get instead the orphan name.
4080 nce = name_cache_search(sctx, ow_inode, ow_gen);
4082 name_cache_delete(sctx, nce);
4087 * ow_inode might currently be an ancestor of
4088 * cur_ino, therefore compute valid_path (the
4089 * current path of cur_ino) again because it
4090 * might contain the pre-orphanization name of
4091 * ow_inode, which is no longer valid.
4093 ret = is_ancestor(sctx->parent_root,
4095 sctx->cur_ino, NULL);
4097 orphanized_ancestor = true;
4098 fs_path_reset(valid_path);
4099 ret = get_cur_path(sctx, sctx->cur_ino,
4100 sctx->cur_inode_gen,
4107 * If we previously orphanized a directory that
4108 * collided with a new reference that we already
4109 * processed, recompute the current path because
4110 * that directory may be part of the path.
4112 if (orphanized_dir) {
4113 ret = refresh_ref_path(sctx, cur);
4117 ret = send_unlink(sctx, cur->full_path);
4125 list_for_each_entry(cur, &sctx->new_refs, list) {
4127 * We may have refs where the parent directory does not exist
4128 * yet. This happens if the parent directories inum is higher
4129 * than the current inum. To handle this case, we create the
4130 * parent directory out of order. But we need to check if this
4131 * did already happen before due to other refs in the same dir.
4133 ret = get_cur_inode_state(sctx, cur->dir, cur->dir_gen);
4136 if (ret == inode_state_will_create) {
4139 * First check if any of the current inodes refs did
4140 * already create the dir.
4142 list_for_each_entry(cur2, &sctx->new_refs, list) {
4145 if (cur2->dir == cur->dir) {
4152 * If that did not happen, check if a previous inode
4153 * did already create the dir.
4156 ret = did_create_dir(sctx, cur->dir);
4160 ret = send_create_inode(sctx, cur->dir);
4166 if (S_ISDIR(sctx->cur_inode_mode) && sctx->parent_root) {
4167 ret = wait_for_dest_dir_move(sctx, cur, is_orphan);
4176 if (S_ISDIR(sctx->cur_inode_mode) && sctx->parent_root &&
4178 ret = wait_for_parent_move(sctx, cur, is_orphan);
4188 * link/move the ref to the new place. If we have an orphan
4189 * inode, move it and update valid_path. If not, link or move
4190 * it depending on the inode mode.
4192 if (is_orphan && can_rename) {
4193 ret = send_rename(sctx, valid_path, cur->full_path);
4197 ret = fs_path_copy(valid_path, cur->full_path);
4200 } else if (can_rename) {
4201 if (S_ISDIR(sctx->cur_inode_mode)) {
4203 * Dirs can't be linked, so move it. For moved
4204 * dirs, we always have one new and one deleted
4205 * ref. The deleted ref is ignored later.
4207 ret = send_rename(sctx, valid_path,
4210 ret = fs_path_copy(valid_path,
4216 * We might have previously orphanized an inode
4217 * which is an ancestor of our current inode,
4218 * so our reference's full path, which was
4219 * computed before any such orphanizations, must
4222 if (orphanized_dir) {
4223 ret = update_ref_path(sctx, cur);
4227 ret = send_link(sctx, cur->full_path,
4233 ret = dup_ref(cur, &check_dirs);
4238 if (S_ISDIR(sctx->cur_inode_mode) && sctx->cur_inode_deleted) {
4240 * Check if we can already rmdir the directory. If not,
4241 * orphanize it. For every dir item inside that gets deleted
4242 * later, we do this check again and rmdir it then if possible.
4243 * See the use of check_dirs for more details.
4245 ret = can_rmdir(sctx, sctx->cur_ino, sctx->cur_inode_gen,
4250 ret = send_rmdir(sctx, valid_path);
4253 } else if (!is_orphan) {
4254 ret = orphanize_inode(sctx, sctx->cur_ino,
4255 sctx->cur_inode_gen, valid_path);
4261 list_for_each_entry(cur, &sctx->deleted_refs, list) {
4262 ret = dup_ref(cur, &check_dirs);
4266 } else if (S_ISDIR(sctx->cur_inode_mode) &&
4267 !list_empty(&sctx->deleted_refs)) {
4269 * We have a moved dir. Add the old parent to check_dirs
4271 cur = list_entry(sctx->deleted_refs.next, struct recorded_ref,
4273 ret = dup_ref(cur, &check_dirs);
4276 } else if (!S_ISDIR(sctx->cur_inode_mode)) {
4278 * We have a non dir inode. Go through all deleted refs and
4279 * unlink them if they were not already overwritten by other
4282 list_for_each_entry(cur, &sctx->deleted_refs, list) {
4283 ret = did_overwrite_ref(sctx, cur->dir, cur->dir_gen,
4284 sctx->cur_ino, sctx->cur_inode_gen,
4285 cur->name, cur->name_len);
4290 * If we orphanized any ancestor before, we need
4291 * to recompute the full path for deleted names,
4292 * since any such path was computed before we
4293 * processed any references and orphanized any
4296 if (orphanized_ancestor) {
4297 ret = update_ref_path(sctx, cur);
4301 ret = send_unlink(sctx, cur->full_path);
4305 ret = dup_ref(cur, &check_dirs);
4310 * If the inode is still orphan, unlink the orphan. This may
4311 * happen when a previous inode did overwrite the first ref
4312 * of this inode and no new refs were added for the current
4313 * inode. Unlinking does not mean that the inode is deleted in
4314 * all cases. There may still be links to this inode in other
4318 ret = send_unlink(sctx, valid_path);
4325 * We did collect all parent dirs where cur_inode was once located. We
4326 * now go through all these dirs and check if they are pending for
4327 * deletion and if it's finally possible to perform the rmdir now.
4328 * We also update the inode stats of the parent dirs here.
4330 list_for_each_entry(cur, &check_dirs, list) {
4332 * In case we had refs into dirs that were not processed yet,
4333 * we don't need to do the utime and rmdir logic for these dirs.
4334 * The dir will be processed later.
4336 if (cur->dir > sctx->cur_ino)
4339 ret = get_cur_inode_state(sctx, cur->dir, cur->dir_gen);
4343 if (ret == inode_state_did_create ||
4344 ret == inode_state_no_change) {
4345 /* TODO delayed utimes */
4346 ret = send_utimes(sctx, cur->dir, cur->dir_gen);
4349 } else if (ret == inode_state_did_delete &&
4350 cur->dir != last_dir_ino_rm) {
4351 ret = can_rmdir(sctx, cur->dir, cur->dir_gen,
4356 ret = get_cur_path(sctx, cur->dir,
4357 cur->dir_gen, valid_path);
4360 ret = send_rmdir(sctx, valid_path);
4363 last_dir_ino_rm = cur->dir;
4371 __free_recorded_refs(&check_dirs);
4372 free_recorded_refs(sctx);
4373 fs_path_free(valid_path);
4377 static int rbtree_ref_comp(const void *k, const struct rb_node *node)
4379 const struct recorded_ref *data = k;
4380 const struct recorded_ref *ref = rb_entry(node, struct recorded_ref, node);
4383 if (data->dir > ref->dir)
4385 if (data->dir < ref->dir)
4387 if (data->dir_gen > ref->dir_gen)
4389 if (data->dir_gen < ref->dir_gen)
4391 if (data->name_len > ref->name_len)
4393 if (data->name_len < ref->name_len)
4395 result = strcmp(data->name, ref->name);
4403 static bool rbtree_ref_less(struct rb_node *node, const struct rb_node *parent)
4405 const struct recorded_ref *entry = rb_entry(node, struct recorded_ref, node);
4407 return rbtree_ref_comp(entry, parent) < 0;
4410 static int record_ref_in_tree(struct rb_root *root, struct list_head *refs,
4411 struct fs_path *name, u64 dir, u64 dir_gen,
4412 struct send_ctx *sctx)
4415 struct fs_path *path = NULL;
4416 struct recorded_ref *ref = NULL;
4418 path = fs_path_alloc();
4424 ref = recorded_ref_alloc();
4430 ret = get_cur_path(sctx, dir, dir_gen, path);
4433 ret = fs_path_add_path(path, name);
4438 ref->dir_gen = dir_gen;
4439 set_ref_path(ref, path);
4440 list_add_tail(&ref->list, refs);
4441 rb_add(&ref->node, root, rbtree_ref_less);
4445 if (path && (!ref || !ref->full_path))
4447 recorded_ref_free(ref);
4452 static int record_new_ref_if_needed(int num, u64 dir, int index,
4453 struct fs_path *name, void *ctx)
4456 struct send_ctx *sctx = ctx;
4457 struct rb_node *node = NULL;
4458 struct recorded_ref data;
4459 struct recorded_ref *ref;
4462 ret = get_inode_gen(sctx->send_root, dir, &dir_gen);
4467 data.dir_gen = dir_gen;
4468 set_ref_path(&data, name);
4469 node = rb_find(&data, &sctx->rbtree_deleted_refs, rbtree_ref_comp);
4471 ref = rb_entry(node, struct recorded_ref, node);
4472 recorded_ref_free(ref);
4474 ret = record_ref_in_tree(&sctx->rbtree_new_refs,
4475 &sctx->new_refs, name, dir, dir_gen,
4482 static int record_deleted_ref_if_needed(int num, u64 dir, int index,
4483 struct fs_path *name, void *ctx)
4486 struct send_ctx *sctx = ctx;
4487 struct rb_node *node = NULL;
4488 struct recorded_ref data;
4489 struct recorded_ref *ref;
4492 ret = get_inode_gen(sctx->parent_root, dir, &dir_gen);
4497 data.dir_gen = dir_gen;
4498 set_ref_path(&data, name);
4499 node = rb_find(&data, &sctx->rbtree_new_refs, rbtree_ref_comp);
4501 ref = rb_entry(node, struct recorded_ref, node);
4502 recorded_ref_free(ref);
4504 ret = record_ref_in_tree(&sctx->rbtree_deleted_refs,
4505 &sctx->deleted_refs, name, dir,
4512 static int record_new_ref(struct send_ctx *sctx)
4516 ret = iterate_inode_ref(sctx->send_root, sctx->left_path,
4517 sctx->cmp_key, 0, record_new_ref_if_needed, sctx);
4526 static int record_deleted_ref(struct send_ctx *sctx)
4530 ret = iterate_inode_ref(sctx->parent_root, sctx->right_path,
4531 sctx->cmp_key, 0, record_deleted_ref_if_needed,
4541 static int record_changed_ref(struct send_ctx *sctx)
4545 ret = iterate_inode_ref(sctx->send_root, sctx->left_path,
4546 sctx->cmp_key, 0, record_new_ref_if_needed, sctx);
4549 ret = iterate_inode_ref(sctx->parent_root, sctx->right_path,
4550 sctx->cmp_key, 0, record_deleted_ref_if_needed, sctx);
4560 * Record and process all refs at once. Needed when an inode changes the
4561 * generation number, which means that it was deleted and recreated.
4563 static int process_all_refs(struct send_ctx *sctx,
4564 enum btrfs_compare_tree_result cmd)
4568 struct btrfs_root *root;
4569 struct btrfs_path *path;
4570 struct btrfs_key key;
4571 struct btrfs_key found_key;
4572 iterate_inode_ref_t cb;
4573 int pending_move = 0;
4575 path = alloc_path_for_send();
4579 if (cmd == BTRFS_COMPARE_TREE_NEW) {
4580 root = sctx->send_root;
4581 cb = record_new_ref_if_needed;
4582 } else if (cmd == BTRFS_COMPARE_TREE_DELETED) {
4583 root = sctx->parent_root;
4584 cb = record_deleted_ref_if_needed;
4586 btrfs_err(sctx->send_root->fs_info,
4587 "Wrong command %d in process_all_refs", cmd);
4592 key.objectid = sctx->cmp_key->objectid;
4593 key.type = BTRFS_INODE_REF_KEY;
4595 btrfs_for_each_slot(root, &key, &found_key, path, iter_ret) {
4596 if (found_key.objectid != key.objectid ||
4597 (found_key.type != BTRFS_INODE_REF_KEY &&
4598 found_key.type != BTRFS_INODE_EXTREF_KEY))
4601 ret = iterate_inode_ref(root, path, &found_key, 0, cb, sctx);
4605 /* Catch error found during iteration */
4610 btrfs_release_path(path);
4613 * We don't actually care about pending_move as we are simply
4614 * re-creating this inode and will be rename'ing it into place once we
4615 * rename the parent directory.
4617 ret = process_recorded_refs(sctx, &pending_move);
4619 btrfs_free_path(path);
4623 static int send_set_xattr(struct send_ctx *sctx,
4624 struct fs_path *path,
4625 const char *name, int name_len,
4626 const char *data, int data_len)
4630 ret = begin_cmd(sctx, BTRFS_SEND_C_SET_XATTR);
4634 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
4635 TLV_PUT_STRING(sctx, BTRFS_SEND_A_XATTR_NAME, name, name_len);
4636 TLV_PUT(sctx, BTRFS_SEND_A_XATTR_DATA, data, data_len);
4638 ret = send_cmd(sctx);
4645 static int send_remove_xattr(struct send_ctx *sctx,
4646 struct fs_path *path,
4647 const char *name, int name_len)
4651 ret = begin_cmd(sctx, BTRFS_SEND_C_REMOVE_XATTR);
4655 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
4656 TLV_PUT_STRING(sctx, BTRFS_SEND_A_XATTR_NAME, name, name_len);
4658 ret = send_cmd(sctx);
4665 static int __process_new_xattr(int num, struct btrfs_key *di_key,
4666 const char *name, int name_len, const char *data,
4667 int data_len, void *ctx)
4670 struct send_ctx *sctx = ctx;
4672 struct posix_acl_xattr_header dummy_acl;
4674 /* Capabilities are emitted by finish_inode_if_needed */
4675 if (!strncmp(name, XATTR_NAME_CAPS, name_len))
4678 p = fs_path_alloc();
4683 * This hack is needed because empty acls are stored as zero byte
4684 * data in xattrs. Problem with that is, that receiving these zero byte
4685 * acls will fail later. To fix this, we send a dummy acl list that
4686 * only contains the version number and no entries.
4688 if (!strncmp(name, XATTR_NAME_POSIX_ACL_ACCESS, name_len) ||
4689 !strncmp(name, XATTR_NAME_POSIX_ACL_DEFAULT, name_len)) {
4690 if (data_len == 0) {
4691 dummy_acl.a_version =
4692 cpu_to_le32(POSIX_ACL_XATTR_VERSION);
4693 data = (char *)&dummy_acl;
4694 data_len = sizeof(dummy_acl);
4698 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
4702 ret = send_set_xattr(sctx, p, name, name_len, data, data_len);
4709 static int __process_deleted_xattr(int num, struct btrfs_key *di_key,
4710 const char *name, int name_len,
4711 const char *data, int data_len, void *ctx)
4714 struct send_ctx *sctx = ctx;
4717 p = fs_path_alloc();
4721 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
4725 ret = send_remove_xattr(sctx, p, name, name_len);
4732 static int process_new_xattr(struct send_ctx *sctx)
4736 ret = iterate_dir_item(sctx->send_root, sctx->left_path,
4737 __process_new_xattr, sctx);
4742 static int process_deleted_xattr(struct send_ctx *sctx)
4744 return iterate_dir_item(sctx->parent_root, sctx->right_path,
4745 __process_deleted_xattr, sctx);
4748 struct find_xattr_ctx {
4756 static int __find_xattr(int num, struct btrfs_key *di_key, const char *name,
4757 int name_len, const char *data, int data_len, void *vctx)
4759 struct find_xattr_ctx *ctx = vctx;
4761 if (name_len == ctx->name_len &&
4762 strncmp(name, ctx->name, name_len) == 0) {
4763 ctx->found_idx = num;
4764 ctx->found_data_len = data_len;
4765 ctx->found_data = kmemdup(data, data_len, GFP_KERNEL);
4766 if (!ctx->found_data)
4773 static int find_xattr(struct btrfs_root *root,
4774 struct btrfs_path *path,
4775 struct btrfs_key *key,
4776 const char *name, int name_len,
4777 char **data, int *data_len)
4780 struct find_xattr_ctx ctx;
4783 ctx.name_len = name_len;
4785 ctx.found_data = NULL;
4786 ctx.found_data_len = 0;
4788 ret = iterate_dir_item(root, path, __find_xattr, &ctx);
4792 if (ctx.found_idx == -1)
4795 *data = ctx.found_data;
4796 *data_len = ctx.found_data_len;
4798 kfree(ctx.found_data);
4800 return ctx.found_idx;
4804 static int __process_changed_new_xattr(int num, struct btrfs_key *di_key,
4805 const char *name, int name_len,
4806 const char *data, int data_len,
4810 struct send_ctx *sctx = ctx;
4811 char *found_data = NULL;
4812 int found_data_len = 0;
4814 ret = find_xattr(sctx->parent_root, sctx->right_path,
4815 sctx->cmp_key, name, name_len, &found_data,
4817 if (ret == -ENOENT) {
4818 ret = __process_new_xattr(num, di_key, name, name_len, data,
4820 } else if (ret >= 0) {
4821 if (data_len != found_data_len ||
4822 memcmp(data, found_data, data_len)) {
4823 ret = __process_new_xattr(num, di_key, name, name_len,
4824 data, data_len, ctx);
4834 static int __process_changed_deleted_xattr(int num, struct btrfs_key *di_key,
4835 const char *name, int name_len,
4836 const char *data, int data_len,
4840 struct send_ctx *sctx = ctx;
4842 ret = find_xattr(sctx->send_root, sctx->left_path, sctx->cmp_key,
4843 name, name_len, NULL, NULL);
4845 ret = __process_deleted_xattr(num, di_key, name, name_len, data,
4853 static int process_changed_xattr(struct send_ctx *sctx)
4857 ret = iterate_dir_item(sctx->send_root, sctx->left_path,
4858 __process_changed_new_xattr, sctx);
4861 ret = iterate_dir_item(sctx->parent_root, sctx->right_path,
4862 __process_changed_deleted_xattr, sctx);
4868 static int process_all_new_xattrs(struct send_ctx *sctx)
4872 struct btrfs_root *root;
4873 struct btrfs_path *path;
4874 struct btrfs_key key;
4875 struct btrfs_key found_key;
4877 path = alloc_path_for_send();
4881 root = sctx->send_root;
4883 key.objectid = sctx->cmp_key->objectid;
4884 key.type = BTRFS_XATTR_ITEM_KEY;
4886 btrfs_for_each_slot(root, &key, &found_key, path, iter_ret) {
4887 if (found_key.objectid != key.objectid ||
4888 found_key.type != key.type) {
4893 ret = iterate_dir_item(root, path, __process_new_xattr, sctx);
4897 /* Catch error found during iteration */
4901 btrfs_free_path(path);
4905 static int send_verity(struct send_ctx *sctx, struct fs_path *path,
4906 struct fsverity_descriptor *desc)
4910 ret = begin_cmd(sctx, BTRFS_SEND_C_ENABLE_VERITY);
4914 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
4915 TLV_PUT_U8(sctx, BTRFS_SEND_A_VERITY_ALGORITHM,
4916 le8_to_cpu(desc->hash_algorithm));
4917 TLV_PUT_U32(sctx, BTRFS_SEND_A_VERITY_BLOCK_SIZE,
4918 1U << le8_to_cpu(desc->log_blocksize));
4919 TLV_PUT(sctx, BTRFS_SEND_A_VERITY_SALT_DATA, desc->salt,
4920 le8_to_cpu(desc->salt_size));
4921 TLV_PUT(sctx, BTRFS_SEND_A_VERITY_SIG_DATA, desc->signature,
4922 le32_to_cpu(desc->sig_size));
4924 ret = send_cmd(sctx);
4931 static int process_verity(struct send_ctx *sctx)
4934 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
4935 struct inode *inode;
4938 inode = btrfs_iget(fs_info->sb, sctx->cur_ino, sctx->send_root);
4940 return PTR_ERR(inode);
4942 ret = btrfs_get_verity_descriptor(inode, NULL, 0);
4946 if (ret > FS_VERITY_MAX_DESCRIPTOR_SIZE) {
4950 if (!sctx->verity_descriptor) {
4951 sctx->verity_descriptor = kvmalloc(FS_VERITY_MAX_DESCRIPTOR_SIZE,
4953 if (!sctx->verity_descriptor) {
4959 ret = btrfs_get_verity_descriptor(inode, sctx->verity_descriptor, ret);
4963 p = fs_path_alloc();
4968 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
4972 ret = send_verity(sctx, p, sctx->verity_descriptor);
4983 static inline u64 max_send_read_size(const struct send_ctx *sctx)
4985 return sctx->send_max_size - SZ_16K;
4988 static int put_data_header(struct send_ctx *sctx, u32 len)
4990 if (WARN_ON_ONCE(sctx->put_data))
4992 sctx->put_data = true;
4993 if (sctx->proto >= 2) {
4995 * Since v2, the data attribute header doesn't include a length,
4996 * it is implicitly to the end of the command.
4998 if (sctx->send_max_size - sctx->send_size < sizeof(__le16) + len)
5000 put_unaligned_le16(BTRFS_SEND_A_DATA, sctx->send_buf + sctx->send_size);
5001 sctx->send_size += sizeof(__le16);
5003 struct btrfs_tlv_header *hdr;
5005 if (sctx->send_max_size - sctx->send_size < sizeof(*hdr) + len)
5007 hdr = (struct btrfs_tlv_header *)(sctx->send_buf + sctx->send_size);
5008 put_unaligned_le16(BTRFS_SEND_A_DATA, &hdr->tlv_type);
5009 put_unaligned_le16(len, &hdr->tlv_len);
5010 sctx->send_size += sizeof(*hdr);
5015 static int put_file_data(struct send_ctx *sctx, u64 offset, u32 len)
5017 struct btrfs_root *root = sctx->send_root;
5018 struct btrfs_fs_info *fs_info = root->fs_info;
5020 pgoff_t index = offset >> PAGE_SHIFT;
5022 unsigned pg_offset = offset_in_page(offset);
5025 ret = put_data_header(sctx, len);
5029 last_index = (offset + len - 1) >> PAGE_SHIFT;
5031 while (index <= last_index) {
5032 unsigned cur_len = min_t(unsigned, len,
5033 PAGE_SIZE - pg_offset);
5035 page = find_lock_page(sctx->cur_inode->i_mapping, index);
5037 page_cache_sync_readahead(sctx->cur_inode->i_mapping,
5038 &sctx->ra, NULL, index,
5039 last_index + 1 - index);
5041 page = find_or_create_page(sctx->cur_inode->i_mapping,
5049 if (PageReadahead(page))
5050 page_cache_async_readahead(sctx->cur_inode->i_mapping,
5051 &sctx->ra, NULL, page_folio(page),
5052 index, last_index + 1 - index);
5054 if (!PageUptodate(page)) {
5055 btrfs_read_folio(NULL, page_folio(page));
5057 if (!PageUptodate(page)) {
5060 "send: IO error at offset %llu for inode %llu root %llu",
5061 page_offset(page), sctx->cur_ino,
5062 sctx->send_root->root_key.objectid);
5069 memcpy_from_page(sctx->send_buf + sctx->send_size, page,
5070 pg_offset, cur_len);
5076 sctx->send_size += cur_len;
5083 * Read some bytes from the current inode/file and send a write command to
5086 static int send_write(struct send_ctx *sctx, u64 offset, u32 len)
5088 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
5092 p = fs_path_alloc();
5096 btrfs_debug(fs_info, "send_write offset=%llu, len=%d", offset, len);
5098 ret = begin_cmd(sctx, BTRFS_SEND_C_WRITE);
5102 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5106 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5107 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5108 ret = put_file_data(sctx, offset, len);
5112 ret = send_cmd(sctx);
5121 * Send a clone command to user space.
5123 static int send_clone(struct send_ctx *sctx,
5124 u64 offset, u32 len,
5125 struct clone_root *clone_root)
5131 btrfs_debug(sctx->send_root->fs_info,
5132 "send_clone offset=%llu, len=%d, clone_root=%llu, clone_inode=%llu, clone_offset=%llu",
5133 offset, len, clone_root->root->root_key.objectid,
5134 clone_root->ino, clone_root->offset);
5136 p = fs_path_alloc();
5140 ret = begin_cmd(sctx, BTRFS_SEND_C_CLONE);
5144 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5148 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5149 TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_LEN, len);
5150 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5152 if (clone_root->root == sctx->send_root) {
5153 ret = get_inode_gen(sctx->send_root, clone_root->ino, &gen);
5156 ret = get_cur_path(sctx, clone_root->ino, gen, p);
5158 ret = get_inode_path(clone_root->root, clone_root->ino, p);
5164 * If the parent we're using has a received_uuid set then use that as
5165 * our clone source as that is what we will look for when doing a
5168 * This covers the case that we create a snapshot off of a received
5169 * subvolume and then use that as the parent and try to receive on a
5172 if (!btrfs_is_empty_uuid(clone_root->root->root_item.received_uuid))
5173 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
5174 clone_root->root->root_item.received_uuid);
5176 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
5177 clone_root->root->root_item.uuid);
5178 TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_CTRANSID,
5179 btrfs_root_ctransid(&clone_root->root->root_item));
5180 TLV_PUT_PATH(sctx, BTRFS_SEND_A_CLONE_PATH, p);
5181 TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_OFFSET,
5182 clone_root->offset);
5184 ret = send_cmd(sctx);
5193 * Send an update extent command to user space.
5195 static int send_update_extent(struct send_ctx *sctx,
5196 u64 offset, u32 len)
5201 p = fs_path_alloc();
5205 ret = begin_cmd(sctx, BTRFS_SEND_C_UPDATE_EXTENT);
5209 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5213 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5214 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5215 TLV_PUT_U64(sctx, BTRFS_SEND_A_SIZE, len);
5217 ret = send_cmd(sctx);
5225 static int send_hole(struct send_ctx *sctx, u64 end)
5227 struct fs_path *p = NULL;
5228 u64 read_size = max_send_read_size(sctx);
5229 u64 offset = sctx->cur_inode_last_extent;
5233 * A hole that starts at EOF or beyond it. Since we do not yet support
5234 * fallocate (for extent preallocation and hole punching), sending a
5235 * write of zeroes starting at EOF or beyond would later require issuing
5236 * a truncate operation which would undo the write and achieve nothing.
5238 if (offset >= sctx->cur_inode_size)
5242 * Don't go beyond the inode's i_size due to prealloc extents that start
5245 end = min_t(u64, end, sctx->cur_inode_size);
5247 if (sctx->flags & BTRFS_SEND_FLAG_NO_FILE_DATA)
5248 return send_update_extent(sctx, offset, end - offset);
5250 p = fs_path_alloc();
5253 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5255 goto tlv_put_failure;
5256 while (offset < end) {
5257 u64 len = min(end - offset, read_size);
5259 ret = begin_cmd(sctx, BTRFS_SEND_C_WRITE);
5262 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5263 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5264 ret = put_data_header(sctx, len);
5267 memset(sctx->send_buf + sctx->send_size, 0, len);
5268 sctx->send_size += len;
5269 ret = send_cmd(sctx);
5274 sctx->cur_inode_next_write_offset = offset;
5280 static int send_encoded_inline_extent(struct send_ctx *sctx,
5281 struct btrfs_path *path, u64 offset,
5284 struct btrfs_root *root = sctx->send_root;
5285 struct btrfs_fs_info *fs_info = root->fs_info;
5286 struct inode *inode;
5287 struct fs_path *fspath;
5288 struct extent_buffer *leaf = path->nodes[0];
5289 struct btrfs_key key;
5290 struct btrfs_file_extent_item *ei;
5295 inode = btrfs_iget(fs_info->sb, sctx->cur_ino, root);
5297 return PTR_ERR(inode);
5299 fspath = fs_path_alloc();
5305 ret = begin_cmd(sctx, BTRFS_SEND_C_ENCODED_WRITE);
5309 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, fspath);
5313 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5314 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
5315 ram_bytes = btrfs_file_extent_ram_bytes(leaf, ei);
5316 inline_size = btrfs_file_extent_inline_item_len(leaf, path->slots[0]);
5318 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, fspath);
5319 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5320 TLV_PUT_U64(sctx, BTRFS_SEND_A_UNENCODED_FILE_LEN,
5321 min(key.offset + ram_bytes - offset, len));
5322 TLV_PUT_U64(sctx, BTRFS_SEND_A_UNENCODED_LEN, ram_bytes);
5323 TLV_PUT_U64(sctx, BTRFS_SEND_A_UNENCODED_OFFSET, offset - key.offset);
5324 ret = btrfs_encoded_io_compression_from_extent(fs_info,
5325 btrfs_file_extent_compression(leaf, ei));
5328 TLV_PUT_U32(sctx, BTRFS_SEND_A_COMPRESSION, ret);
5330 ret = put_data_header(sctx, inline_size);
5333 read_extent_buffer(leaf, sctx->send_buf + sctx->send_size,
5334 btrfs_file_extent_inline_start(ei), inline_size);
5335 sctx->send_size += inline_size;
5337 ret = send_cmd(sctx);
5341 fs_path_free(fspath);
5346 static int send_encoded_extent(struct send_ctx *sctx, struct btrfs_path *path,
5347 u64 offset, u64 len)
5349 struct btrfs_root *root = sctx->send_root;
5350 struct btrfs_fs_info *fs_info = root->fs_info;
5351 struct inode *inode;
5352 struct fs_path *fspath;
5353 struct extent_buffer *leaf = path->nodes[0];
5354 struct btrfs_key key;
5355 struct btrfs_file_extent_item *ei;
5356 u64 disk_bytenr, disk_num_bytes;
5358 struct btrfs_cmd_header *hdr;
5362 inode = btrfs_iget(fs_info->sb, sctx->cur_ino, root);
5364 return PTR_ERR(inode);
5366 fspath = fs_path_alloc();
5372 ret = begin_cmd(sctx, BTRFS_SEND_C_ENCODED_WRITE);
5376 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, fspath);
5380 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5381 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
5382 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
5383 disk_num_bytes = btrfs_file_extent_disk_num_bytes(leaf, ei);
5385 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, fspath);
5386 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5387 TLV_PUT_U64(sctx, BTRFS_SEND_A_UNENCODED_FILE_LEN,
5388 min(key.offset + btrfs_file_extent_num_bytes(leaf, ei) - offset,
5390 TLV_PUT_U64(sctx, BTRFS_SEND_A_UNENCODED_LEN,
5391 btrfs_file_extent_ram_bytes(leaf, ei));
5392 TLV_PUT_U64(sctx, BTRFS_SEND_A_UNENCODED_OFFSET,
5393 offset - key.offset + btrfs_file_extent_offset(leaf, ei));
5394 ret = btrfs_encoded_io_compression_from_extent(fs_info,
5395 btrfs_file_extent_compression(leaf, ei));
5398 TLV_PUT_U32(sctx, BTRFS_SEND_A_COMPRESSION, ret);
5399 TLV_PUT_U32(sctx, BTRFS_SEND_A_ENCRYPTION, 0);
5401 ret = put_data_header(sctx, disk_num_bytes);
5406 * We want to do I/O directly into the send buffer, so get the next page
5407 * boundary in the send buffer. This means that there may be a gap
5408 * between the beginning of the command and the file data.
5410 data_offset = ALIGN(sctx->send_size, PAGE_SIZE);
5411 if (data_offset > sctx->send_max_size ||
5412 sctx->send_max_size - data_offset < disk_num_bytes) {
5418 * Note that send_buf is a mapping of send_buf_pages, so this is really
5419 * reading into send_buf.
5421 ret = btrfs_encoded_read_regular_fill_pages(BTRFS_I(inode), offset,
5422 disk_bytenr, disk_num_bytes,
5423 sctx->send_buf_pages +
5424 (data_offset >> PAGE_SHIFT));
5428 hdr = (struct btrfs_cmd_header *)sctx->send_buf;
5429 hdr->len = cpu_to_le32(sctx->send_size + disk_num_bytes - sizeof(*hdr));
5431 crc = btrfs_crc32c(0, sctx->send_buf, sctx->send_size);
5432 crc = btrfs_crc32c(crc, sctx->send_buf + data_offset, disk_num_bytes);
5433 hdr->crc = cpu_to_le32(crc);
5435 ret = write_buf(sctx->send_filp, sctx->send_buf, sctx->send_size,
5438 ret = write_buf(sctx->send_filp, sctx->send_buf + data_offset,
5439 disk_num_bytes, &sctx->send_off);
5441 sctx->send_size = 0;
5442 sctx->put_data = false;
5446 fs_path_free(fspath);
5451 static int send_extent_data(struct send_ctx *sctx, struct btrfs_path *path,
5452 const u64 offset, const u64 len)
5454 const u64 end = offset + len;
5455 struct extent_buffer *leaf = path->nodes[0];
5456 struct btrfs_file_extent_item *ei;
5457 u64 read_size = max_send_read_size(sctx);
5460 if (sctx->flags & BTRFS_SEND_FLAG_NO_FILE_DATA)
5461 return send_update_extent(sctx, offset, len);
5463 ei = btrfs_item_ptr(leaf, path->slots[0],
5464 struct btrfs_file_extent_item);
5465 if ((sctx->flags & BTRFS_SEND_FLAG_COMPRESSED) &&
5466 btrfs_file_extent_compression(leaf, ei) != BTRFS_COMPRESS_NONE) {
5467 bool is_inline = (btrfs_file_extent_type(leaf, ei) ==
5468 BTRFS_FILE_EXTENT_INLINE);
5471 * Send the compressed extent unless the compressed data is
5472 * larger than the decompressed data. This can happen if we're
5473 * not sending the entire extent, either because it has been
5474 * partially overwritten/truncated or because this is a part of
5475 * the extent that we couldn't clone in clone_range().
5478 btrfs_file_extent_inline_item_len(leaf,
5479 path->slots[0]) <= len) {
5480 return send_encoded_inline_extent(sctx, path, offset,
5482 } else if (!is_inline &&
5483 btrfs_file_extent_disk_num_bytes(leaf, ei) <= len) {
5484 return send_encoded_extent(sctx, path, offset, len);
5488 if (sctx->cur_inode == NULL) {
5489 struct btrfs_root *root = sctx->send_root;
5491 sctx->cur_inode = btrfs_iget(root->fs_info->sb, sctx->cur_ino, root);
5492 if (IS_ERR(sctx->cur_inode)) {
5493 int err = PTR_ERR(sctx->cur_inode);
5495 sctx->cur_inode = NULL;
5498 memset(&sctx->ra, 0, sizeof(struct file_ra_state));
5499 file_ra_state_init(&sctx->ra, sctx->cur_inode->i_mapping);
5502 * It's very likely there are no pages from this inode in the page
5503 * cache, so after reading extents and sending their data, we clean
5504 * the page cache to avoid trashing the page cache (adding pressure
5505 * to the page cache and forcing eviction of other data more useful
5506 * for applications).
5508 * We decide if we should clean the page cache simply by checking
5509 * if the inode's mapping nrpages is 0 when we first open it, and
5510 * not by using something like filemap_range_has_page() before
5511 * reading an extent because when we ask the readahead code to
5512 * read a given file range, it may (and almost always does) read
5513 * pages from beyond that range (see the documentation for
5514 * page_cache_sync_readahead()), so it would not be reliable,
5515 * because after reading the first extent future calls to
5516 * filemap_range_has_page() would return true because the readahead
5517 * on the previous extent resulted in reading pages of the current
5520 sctx->clean_page_cache = (sctx->cur_inode->i_mapping->nrpages == 0);
5521 sctx->page_cache_clear_start = round_down(offset, PAGE_SIZE);
5524 while (sent < len) {
5525 u64 size = min(len - sent, read_size);
5528 ret = send_write(sctx, offset + sent, size);
5534 if (sctx->clean_page_cache && IS_ALIGNED(end, PAGE_SIZE)) {
5536 * Always operate only on ranges that are a multiple of the page
5537 * size. This is not only to prevent zeroing parts of a page in
5538 * the case of subpage sector size, but also to guarantee we evict
5539 * pages, as passing a range that is smaller than page size does
5540 * not evict the respective page (only zeroes part of its content).
5542 * Always start from the end offset of the last range cleared.
5543 * This is because the readahead code may (and very often does)
5544 * reads pages beyond the range we request for readahead. So if
5545 * we have an extent layout like this:
5547 * [ extent A ] [ extent B ] [ extent C ]
5549 * When we ask page_cache_sync_readahead() to read extent A, it
5550 * may also trigger reads for pages of extent B. If we are doing
5551 * an incremental send and extent B has not changed between the
5552 * parent and send snapshots, some or all of its pages may end
5553 * up being read and placed in the page cache. So when truncating
5554 * the page cache we always start from the end offset of the
5555 * previously processed extent up to the end of the current
5558 truncate_inode_pages_range(&sctx->cur_inode->i_data,
5559 sctx->page_cache_clear_start,
5561 sctx->page_cache_clear_start = end;
5568 * Search for a capability xattr related to sctx->cur_ino. If the capability is
5569 * found, call send_set_xattr function to emit it.
5571 * Return 0 if there isn't a capability, or when the capability was emitted
5572 * successfully, or < 0 if an error occurred.
5574 static int send_capabilities(struct send_ctx *sctx)
5576 struct fs_path *fspath = NULL;
5577 struct btrfs_path *path;
5578 struct btrfs_dir_item *di;
5579 struct extent_buffer *leaf;
5580 unsigned long data_ptr;
5585 path = alloc_path_for_send();
5589 di = btrfs_lookup_xattr(NULL, sctx->send_root, path, sctx->cur_ino,
5590 XATTR_NAME_CAPS, strlen(XATTR_NAME_CAPS), 0);
5592 /* There is no xattr for this inode */
5594 } else if (IS_ERR(di)) {
5599 leaf = path->nodes[0];
5600 buf_len = btrfs_dir_data_len(leaf, di);
5602 fspath = fs_path_alloc();
5603 buf = kmalloc(buf_len, GFP_KERNEL);
5604 if (!fspath || !buf) {
5609 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, fspath);
5613 data_ptr = (unsigned long)(di + 1) + btrfs_dir_name_len(leaf, di);
5614 read_extent_buffer(leaf, buf, data_ptr, buf_len);
5616 ret = send_set_xattr(sctx, fspath, XATTR_NAME_CAPS,
5617 strlen(XATTR_NAME_CAPS), buf, buf_len);
5620 fs_path_free(fspath);
5621 btrfs_free_path(path);
5625 static int clone_range(struct send_ctx *sctx, struct btrfs_path *dst_path,
5626 struct clone_root *clone_root, const u64 disk_byte,
5627 u64 data_offset, u64 offset, u64 len)
5629 struct btrfs_path *path;
5630 struct btrfs_key key;
5632 struct btrfs_inode_info info;
5633 u64 clone_src_i_size = 0;
5636 * Prevent cloning from a zero offset with a length matching the sector
5637 * size because in some scenarios this will make the receiver fail.
5639 * For example, if in the source filesystem the extent at offset 0
5640 * has a length of sectorsize and it was written using direct IO, then
5641 * it can never be an inline extent (even if compression is enabled).
5642 * Then this extent can be cloned in the original filesystem to a non
5643 * zero file offset, but it may not be possible to clone in the
5644 * destination filesystem because it can be inlined due to compression
5645 * on the destination filesystem (as the receiver's write operations are
5646 * always done using buffered IO). The same happens when the original
5647 * filesystem does not have compression enabled but the destination
5650 if (clone_root->offset == 0 &&
5651 len == sctx->send_root->fs_info->sectorsize)
5652 return send_extent_data(sctx, dst_path, offset, len);
5654 path = alloc_path_for_send();
5659 * There are inodes that have extents that lie behind its i_size. Don't
5660 * accept clones from these extents.
5662 ret = get_inode_info(clone_root->root, clone_root->ino, &info);
5663 btrfs_release_path(path);
5666 clone_src_i_size = info.size;
5669 * We can't send a clone operation for the entire range if we find
5670 * extent items in the respective range in the source file that
5671 * refer to different extents or if we find holes.
5672 * So check for that and do a mix of clone and regular write/copy
5673 * operations if needed.
5677 * mkfs.btrfs -f /dev/sda
5678 * mount /dev/sda /mnt
5679 * xfs_io -f -c "pwrite -S 0xaa 0K 100K" /mnt/foo
5680 * cp --reflink=always /mnt/foo /mnt/bar
5681 * xfs_io -c "pwrite -S 0xbb 50K 50K" /mnt/foo
5682 * btrfs subvolume snapshot -r /mnt /mnt/snap
5684 * If when we send the snapshot and we are processing file bar (which
5685 * has a higher inode number than foo) we blindly send a clone operation
5686 * for the [0, 100K[ range from foo to bar, the receiver ends up getting
5687 * a file bar that matches the content of file foo - iow, doesn't match
5688 * the content from bar in the original filesystem.
5690 key.objectid = clone_root->ino;
5691 key.type = BTRFS_EXTENT_DATA_KEY;
5692 key.offset = clone_root->offset;
5693 ret = btrfs_search_slot(NULL, clone_root->root, &key, path, 0, 0);
5696 if (ret > 0 && path->slots[0] > 0) {
5697 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1);
5698 if (key.objectid == clone_root->ino &&
5699 key.type == BTRFS_EXTENT_DATA_KEY)
5704 struct extent_buffer *leaf = path->nodes[0];
5705 int slot = path->slots[0];
5706 struct btrfs_file_extent_item *ei;
5710 u64 clone_data_offset;
5711 bool crossed_src_i_size = false;
5713 if (slot >= btrfs_header_nritems(leaf)) {
5714 ret = btrfs_next_leaf(clone_root->root, path);
5722 btrfs_item_key_to_cpu(leaf, &key, slot);
5725 * We might have an implicit trailing hole (NO_HOLES feature
5726 * enabled). We deal with it after leaving this loop.
5728 if (key.objectid != clone_root->ino ||
5729 key.type != BTRFS_EXTENT_DATA_KEY)
5732 ei = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5733 type = btrfs_file_extent_type(leaf, ei);
5734 if (type == BTRFS_FILE_EXTENT_INLINE) {
5735 ext_len = btrfs_file_extent_ram_bytes(leaf, ei);
5736 ext_len = PAGE_ALIGN(ext_len);
5738 ext_len = btrfs_file_extent_num_bytes(leaf, ei);
5741 if (key.offset + ext_len <= clone_root->offset)
5744 if (key.offset > clone_root->offset) {
5745 /* Implicit hole, NO_HOLES feature enabled. */
5746 u64 hole_len = key.offset - clone_root->offset;
5750 ret = send_extent_data(sctx, dst_path, offset,
5759 clone_root->offset += hole_len;
5760 data_offset += hole_len;
5763 if (key.offset >= clone_root->offset + len)
5766 if (key.offset >= clone_src_i_size)
5769 if (key.offset + ext_len > clone_src_i_size) {
5770 ext_len = clone_src_i_size - key.offset;
5771 crossed_src_i_size = true;
5774 clone_data_offset = btrfs_file_extent_offset(leaf, ei);
5775 if (btrfs_file_extent_disk_bytenr(leaf, ei) == disk_byte) {
5776 clone_root->offset = key.offset;
5777 if (clone_data_offset < data_offset &&
5778 clone_data_offset + ext_len > data_offset) {
5781 extent_offset = data_offset - clone_data_offset;
5782 ext_len -= extent_offset;
5783 clone_data_offset += extent_offset;
5784 clone_root->offset += extent_offset;
5788 clone_len = min_t(u64, ext_len, len);
5790 if (btrfs_file_extent_disk_bytenr(leaf, ei) == disk_byte &&
5791 clone_data_offset == data_offset) {
5792 const u64 src_end = clone_root->offset + clone_len;
5793 const u64 sectorsize = SZ_64K;
5796 * We can't clone the last block, when its size is not
5797 * sector size aligned, into the middle of a file. If we
5798 * do so, the receiver will get a failure (-EINVAL) when
5799 * trying to clone or will silently corrupt the data in
5800 * the destination file if it's on a kernel without the
5801 * fix introduced by commit ac765f83f1397646
5802 * ("Btrfs: fix data corruption due to cloning of eof
5805 * So issue a clone of the aligned down range plus a
5806 * regular write for the eof block, if we hit that case.
5808 * Also, we use the maximum possible sector size, 64K,
5809 * because we don't know what's the sector size of the
5810 * filesystem that receives the stream, so we have to
5811 * assume the largest possible sector size.
5813 if (src_end == clone_src_i_size &&
5814 !IS_ALIGNED(src_end, sectorsize) &&
5815 offset + clone_len < sctx->cur_inode_size) {
5818 slen = ALIGN_DOWN(src_end - clone_root->offset,
5821 ret = send_clone(sctx, offset, slen,
5826 ret = send_extent_data(sctx, dst_path,
5830 ret = send_clone(sctx, offset, clone_len,
5833 } else if (crossed_src_i_size && clone_len < len) {
5835 * If we are at i_size of the clone source inode and we
5836 * can not clone from it, terminate the loop. This is
5837 * to avoid sending two write operations, one with a
5838 * length matching clone_len and the final one after
5839 * this loop with a length of len - clone_len.
5841 * When using encoded writes (BTRFS_SEND_FLAG_COMPRESSED
5842 * was passed to the send ioctl), this helps avoid
5843 * sending an encoded write for an offset that is not
5844 * sector size aligned, in case the i_size of the source
5845 * inode is not sector size aligned. That will make the
5846 * receiver fallback to decompression of the data and
5847 * writing it using regular buffered IO, therefore while
5848 * not incorrect, it's not optimal due decompression and
5849 * possible re-compression at the receiver.
5853 ret = send_extent_data(sctx, dst_path, offset,
5863 offset += clone_len;
5864 clone_root->offset += clone_len;
5867 * If we are cloning from the file we are currently processing,
5868 * and using the send root as the clone root, we must stop once
5869 * the current clone offset reaches the current eof of the file
5870 * at the receiver, otherwise we would issue an invalid clone
5871 * operation (source range going beyond eof) and cause the
5872 * receiver to fail. So if we reach the current eof, bail out
5873 * and fallback to a regular write.
5875 if (clone_root->root == sctx->send_root &&
5876 clone_root->ino == sctx->cur_ino &&
5877 clone_root->offset >= sctx->cur_inode_next_write_offset)
5880 data_offset += clone_len;
5886 ret = send_extent_data(sctx, dst_path, offset, len);
5890 btrfs_free_path(path);
5894 static int send_write_or_clone(struct send_ctx *sctx,
5895 struct btrfs_path *path,
5896 struct btrfs_key *key,
5897 struct clone_root *clone_root)
5900 u64 offset = key->offset;
5902 u64 bs = sctx->send_root->fs_info->sb->s_blocksize;
5904 end = min_t(u64, btrfs_file_extent_end(path), sctx->cur_inode_size);
5908 if (clone_root && IS_ALIGNED(end, bs)) {
5909 struct btrfs_file_extent_item *ei;
5913 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
5914 struct btrfs_file_extent_item);
5915 disk_byte = btrfs_file_extent_disk_bytenr(path->nodes[0], ei);
5916 data_offset = btrfs_file_extent_offset(path->nodes[0], ei);
5917 ret = clone_range(sctx, path, clone_root, disk_byte,
5918 data_offset, offset, end - offset);
5920 ret = send_extent_data(sctx, path, offset, end - offset);
5922 sctx->cur_inode_next_write_offset = end;
5926 static int is_extent_unchanged(struct send_ctx *sctx,
5927 struct btrfs_path *left_path,
5928 struct btrfs_key *ekey)
5931 struct btrfs_key key;
5932 struct btrfs_path *path = NULL;
5933 struct extent_buffer *eb;
5935 struct btrfs_key found_key;
5936 struct btrfs_file_extent_item *ei;
5941 u64 left_offset_fixed;
5949 path = alloc_path_for_send();
5953 eb = left_path->nodes[0];
5954 slot = left_path->slots[0];
5955 ei = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
5956 left_type = btrfs_file_extent_type(eb, ei);
5958 if (left_type != BTRFS_FILE_EXTENT_REG) {
5962 left_disknr = btrfs_file_extent_disk_bytenr(eb, ei);
5963 left_len = btrfs_file_extent_num_bytes(eb, ei);
5964 left_offset = btrfs_file_extent_offset(eb, ei);
5965 left_gen = btrfs_file_extent_generation(eb, ei);
5968 * Following comments will refer to these graphics. L is the left
5969 * extents which we are checking at the moment. 1-8 are the right
5970 * extents that we iterate.
5973 * |-1-|-2a-|-3-|-4-|-5-|-6-|
5976 * |--1--|-2b-|...(same as above)
5978 * Alternative situation. Happens on files where extents got split.
5980 * |-----------7-----------|-6-|
5982 * Alternative situation. Happens on files which got larger.
5985 * Nothing follows after 8.
5988 key.objectid = ekey->objectid;
5989 key.type = BTRFS_EXTENT_DATA_KEY;
5990 key.offset = ekey->offset;
5991 ret = btrfs_search_slot_for_read(sctx->parent_root, &key, path, 0, 0);
6000 * Handle special case where the right side has no extents at all.
6002 eb = path->nodes[0];
6003 slot = path->slots[0];
6004 btrfs_item_key_to_cpu(eb, &found_key, slot);
6005 if (found_key.objectid != key.objectid ||
6006 found_key.type != key.type) {
6007 /* If we're a hole then just pretend nothing changed */
6008 ret = (left_disknr) ? 0 : 1;
6013 * We're now on 2a, 2b or 7.
6016 while (key.offset < ekey->offset + left_len) {
6017 ei = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
6018 right_type = btrfs_file_extent_type(eb, ei);
6019 if (right_type != BTRFS_FILE_EXTENT_REG &&
6020 right_type != BTRFS_FILE_EXTENT_INLINE) {
6025 if (right_type == BTRFS_FILE_EXTENT_INLINE) {
6026 right_len = btrfs_file_extent_ram_bytes(eb, ei);
6027 right_len = PAGE_ALIGN(right_len);
6029 right_len = btrfs_file_extent_num_bytes(eb, ei);
6033 * Are we at extent 8? If yes, we know the extent is changed.
6034 * This may only happen on the first iteration.
6036 if (found_key.offset + right_len <= ekey->offset) {
6037 /* If we're a hole just pretend nothing changed */
6038 ret = (left_disknr) ? 0 : 1;
6043 * We just wanted to see if when we have an inline extent, what
6044 * follows it is a regular extent (wanted to check the above
6045 * condition for inline extents too). This should normally not
6046 * happen but it's possible for example when we have an inline
6047 * compressed extent representing data with a size matching
6048 * the page size (currently the same as sector size).
6050 if (right_type == BTRFS_FILE_EXTENT_INLINE) {
6055 right_disknr = btrfs_file_extent_disk_bytenr(eb, ei);
6056 right_offset = btrfs_file_extent_offset(eb, ei);
6057 right_gen = btrfs_file_extent_generation(eb, ei);
6059 left_offset_fixed = left_offset;
6060 if (key.offset < ekey->offset) {
6061 /* Fix the right offset for 2a and 7. */
6062 right_offset += ekey->offset - key.offset;
6064 /* Fix the left offset for all behind 2a and 2b */
6065 left_offset_fixed += key.offset - ekey->offset;
6069 * Check if we have the same extent.
6071 if (left_disknr != right_disknr ||
6072 left_offset_fixed != right_offset ||
6073 left_gen != right_gen) {
6079 * Go to the next extent.
6081 ret = btrfs_next_item(sctx->parent_root, path);
6085 eb = path->nodes[0];
6086 slot = path->slots[0];
6087 btrfs_item_key_to_cpu(eb, &found_key, slot);
6089 if (ret || found_key.objectid != key.objectid ||
6090 found_key.type != key.type) {
6091 key.offset += right_len;
6094 if (found_key.offset != key.offset + right_len) {
6102 * We're now behind the left extent (treat as unchanged) or at the end
6103 * of the right side (treat as changed).
6105 if (key.offset >= ekey->offset + left_len)
6112 btrfs_free_path(path);
6116 static int get_last_extent(struct send_ctx *sctx, u64 offset)
6118 struct btrfs_path *path;
6119 struct btrfs_root *root = sctx->send_root;
6120 struct btrfs_key key;
6123 path = alloc_path_for_send();
6127 sctx->cur_inode_last_extent = 0;
6129 key.objectid = sctx->cur_ino;
6130 key.type = BTRFS_EXTENT_DATA_KEY;
6131 key.offset = offset;
6132 ret = btrfs_search_slot_for_read(root, &key, path, 0, 1);
6136 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
6137 if (key.objectid != sctx->cur_ino || key.type != BTRFS_EXTENT_DATA_KEY)
6140 sctx->cur_inode_last_extent = btrfs_file_extent_end(path);
6142 btrfs_free_path(path);
6146 static int range_is_hole_in_parent(struct send_ctx *sctx,
6150 struct btrfs_path *path;
6151 struct btrfs_key key;
6152 struct btrfs_root *root = sctx->parent_root;
6153 u64 search_start = start;
6156 path = alloc_path_for_send();
6160 key.objectid = sctx->cur_ino;
6161 key.type = BTRFS_EXTENT_DATA_KEY;
6162 key.offset = search_start;
6163 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6166 if (ret > 0 && path->slots[0] > 0)
6169 while (search_start < end) {
6170 struct extent_buffer *leaf = path->nodes[0];
6171 int slot = path->slots[0];
6172 struct btrfs_file_extent_item *fi;
6175 if (slot >= btrfs_header_nritems(leaf)) {
6176 ret = btrfs_next_leaf(root, path);
6184 btrfs_item_key_to_cpu(leaf, &key, slot);
6185 if (key.objectid < sctx->cur_ino ||
6186 key.type < BTRFS_EXTENT_DATA_KEY)
6188 if (key.objectid > sctx->cur_ino ||
6189 key.type > BTRFS_EXTENT_DATA_KEY ||
6193 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6194 extent_end = btrfs_file_extent_end(path);
6195 if (extent_end <= start)
6197 if (btrfs_file_extent_disk_bytenr(leaf, fi) == 0) {
6198 search_start = extent_end;
6208 btrfs_free_path(path);
6212 static int maybe_send_hole(struct send_ctx *sctx, struct btrfs_path *path,
6213 struct btrfs_key *key)
6217 if (sctx->cur_ino != key->objectid || !need_send_hole(sctx))
6220 if (sctx->cur_inode_last_extent == (u64)-1) {
6221 ret = get_last_extent(sctx, key->offset - 1);
6226 if (path->slots[0] == 0 &&
6227 sctx->cur_inode_last_extent < key->offset) {
6229 * We might have skipped entire leafs that contained only
6230 * file extent items for our current inode. These leafs have
6231 * a generation number smaller (older) than the one in the
6232 * current leaf and the leaf our last extent came from, and
6233 * are located between these 2 leafs.
6235 ret = get_last_extent(sctx, key->offset - 1);
6240 if (sctx->cur_inode_last_extent < key->offset) {
6241 ret = range_is_hole_in_parent(sctx,
6242 sctx->cur_inode_last_extent,
6247 ret = send_hole(sctx, key->offset);
6251 sctx->cur_inode_last_extent = btrfs_file_extent_end(path);
6255 static int process_extent(struct send_ctx *sctx,
6256 struct btrfs_path *path,
6257 struct btrfs_key *key)
6259 struct clone_root *found_clone = NULL;
6262 if (S_ISLNK(sctx->cur_inode_mode))
6265 if (sctx->parent_root && !sctx->cur_inode_new) {
6266 ret = is_extent_unchanged(sctx, path, key);
6274 struct btrfs_file_extent_item *ei;
6277 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
6278 struct btrfs_file_extent_item);
6279 type = btrfs_file_extent_type(path->nodes[0], ei);
6280 if (type == BTRFS_FILE_EXTENT_PREALLOC ||
6281 type == BTRFS_FILE_EXTENT_REG) {
6283 * The send spec does not have a prealloc command yet,
6284 * so just leave a hole for prealloc'ed extents until
6285 * we have enough commands queued up to justify rev'ing
6288 if (type == BTRFS_FILE_EXTENT_PREALLOC) {
6293 /* Have a hole, just skip it. */
6294 if (btrfs_file_extent_disk_bytenr(path->nodes[0], ei) == 0) {
6301 ret = find_extent_clone(sctx, path, key->objectid, key->offset,
6302 sctx->cur_inode_size, &found_clone);
6303 if (ret != -ENOENT && ret < 0)
6306 ret = send_write_or_clone(sctx, path, key, found_clone);
6310 ret = maybe_send_hole(sctx, path, key);
6315 static int process_all_extents(struct send_ctx *sctx)
6319 struct btrfs_root *root;
6320 struct btrfs_path *path;
6321 struct btrfs_key key;
6322 struct btrfs_key found_key;
6324 root = sctx->send_root;
6325 path = alloc_path_for_send();
6329 key.objectid = sctx->cmp_key->objectid;
6330 key.type = BTRFS_EXTENT_DATA_KEY;
6332 btrfs_for_each_slot(root, &key, &found_key, path, iter_ret) {
6333 if (found_key.objectid != key.objectid ||
6334 found_key.type != key.type) {
6339 ret = process_extent(sctx, path, &found_key);
6343 /* Catch error found during iteration */
6347 btrfs_free_path(path);
6351 static int process_recorded_refs_if_needed(struct send_ctx *sctx, int at_end,
6353 int *refs_processed)
6357 if (sctx->cur_ino == 0)
6359 if (!at_end && sctx->cur_ino == sctx->cmp_key->objectid &&
6360 sctx->cmp_key->type <= BTRFS_INODE_EXTREF_KEY)
6362 if (list_empty(&sctx->new_refs) && list_empty(&sctx->deleted_refs))
6365 ret = process_recorded_refs(sctx, pending_move);
6369 *refs_processed = 1;
6374 static int finish_inode_if_needed(struct send_ctx *sctx, int at_end)
6377 struct btrfs_inode_info info;
6388 bool need_fileattr = false;
6389 int need_truncate = 1;
6390 int pending_move = 0;
6391 int refs_processed = 0;
6393 if (sctx->ignore_cur_inode)
6396 ret = process_recorded_refs_if_needed(sctx, at_end, &pending_move,
6402 * We have processed the refs and thus need to advance send_progress.
6403 * Now, calls to get_cur_xxx will take the updated refs of the current
6404 * inode into account.
6406 * On the other hand, if our current inode is a directory and couldn't
6407 * be moved/renamed because its parent was renamed/moved too and it has
6408 * a higher inode number, we can only move/rename our current inode
6409 * after we moved/renamed its parent. Therefore in this case operate on
6410 * the old path (pre move/rename) of our current inode, and the
6411 * move/rename will be performed later.
6413 if (refs_processed && !pending_move)
6414 sctx->send_progress = sctx->cur_ino + 1;
6416 if (sctx->cur_ino == 0 || sctx->cur_inode_deleted)
6418 if (!at_end && sctx->cmp_key->objectid == sctx->cur_ino)
6420 ret = get_inode_info(sctx->send_root, sctx->cur_ino, &info);
6423 left_mode = info.mode;
6424 left_uid = info.uid;
6425 left_gid = info.gid;
6426 left_fileattr = info.fileattr;
6428 if (!sctx->parent_root || sctx->cur_inode_new) {
6430 if (!S_ISLNK(sctx->cur_inode_mode))
6432 if (sctx->cur_inode_next_write_offset == sctx->cur_inode_size)
6437 ret = get_inode_info(sctx->parent_root, sctx->cur_ino, &info);
6440 old_size = info.size;
6441 right_mode = info.mode;
6442 right_uid = info.uid;
6443 right_gid = info.gid;
6444 right_fileattr = info.fileattr;
6446 if (left_uid != right_uid || left_gid != right_gid)
6448 if (!S_ISLNK(sctx->cur_inode_mode) && left_mode != right_mode)
6450 if (!S_ISLNK(sctx->cur_inode_mode) && left_fileattr != right_fileattr)
6451 need_fileattr = true;
6452 if ((old_size == sctx->cur_inode_size) ||
6453 (sctx->cur_inode_size > old_size &&
6454 sctx->cur_inode_next_write_offset == sctx->cur_inode_size))
6458 if (S_ISREG(sctx->cur_inode_mode)) {
6459 if (need_send_hole(sctx)) {
6460 if (sctx->cur_inode_last_extent == (u64)-1 ||
6461 sctx->cur_inode_last_extent <
6462 sctx->cur_inode_size) {
6463 ret = get_last_extent(sctx, (u64)-1);
6467 if (sctx->cur_inode_last_extent <
6468 sctx->cur_inode_size) {
6469 ret = send_hole(sctx, sctx->cur_inode_size);
6474 if (need_truncate) {
6475 ret = send_truncate(sctx, sctx->cur_ino,
6476 sctx->cur_inode_gen,
6477 sctx->cur_inode_size);
6484 ret = send_chown(sctx, sctx->cur_ino, sctx->cur_inode_gen,
6485 left_uid, left_gid);
6490 ret = send_chmod(sctx, sctx->cur_ino, sctx->cur_inode_gen,
6495 if (need_fileattr) {
6496 ret = send_fileattr(sctx, sctx->cur_ino, sctx->cur_inode_gen,
6502 if (proto_cmd_ok(sctx, BTRFS_SEND_C_ENABLE_VERITY)
6503 && sctx->cur_inode_needs_verity) {
6504 ret = process_verity(sctx);
6509 ret = send_capabilities(sctx);
6514 * If other directory inodes depended on our current directory
6515 * inode's move/rename, now do their move/rename operations.
6517 if (!is_waiting_for_move(sctx, sctx->cur_ino)) {
6518 ret = apply_children_dir_moves(sctx);
6522 * Need to send that every time, no matter if it actually
6523 * changed between the two trees as we have done changes to
6524 * the inode before. If our inode is a directory and it's
6525 * waiting to be moved/renamed, we will send its utimes when
6526 * it's moved/renamed, therefore we don't need to do it here.
6528 sctx->send_progress = sctx->cur_ino + 1;
6529 ret = send_utimes(sctx, sctx->cur_ino, sctx->cur_inode_gen);
6538 static void close_current_inode(struct send_ctx *sctx)
6542 if (sctx->cur_inode == NULL)
6545 i_size = i_size_read(sctx->cur_inode);
6548 * If we are doing an incremental send, we may have extents between the
6549 * last processed extent and the i_size that have not been processed
6550 * because they haven't changed but we may have read some of their pages
6551 * through readahead, see the comments at send_extent_data().
6553 if (sctx->clean_page_cache && sctx->page_cache_clear_start < i_size)
6554 truncate_inode_pages_range(&sctx->cur_inode->i_data,
6555 sctx->page_cache_clear_start,
6556 round_up(i_size, PAGE_SIZE) - 1);
6558 iput(sctx->cur_inode);
6559 sctx->cur_inode = NULL;
6562 static int changed_inode(struct send_ctx *sctx,
6563 enum btrfs_compare_tree_result result)
6566 struct btrfs_key *key = sctx->cmp_key;
6567 struct btrfs_inode_item *left_ii = NULL;
6568 struct btrfs_inode_item *right_ii = NULL;
6572 close_current_inode(sctx);
6574 sctx->cur_ino = key->objectid;
6575 sctx->cur_inode_new_gen = false;
6576 sctx->cur_inode_last_extent = (u64)-1;
6577 sctx->cur_inode_next_write_offset = 0;
6578 sctx->ignore_cur_inode = false;
6581 * Set send_progress to current inode. This will tell all get_cur_xxx
6582 * functions that the current inode's refs are not updated yet. Later,
6583 * when process_recorded_refs is finished, it is set to cur_ino + 1.
6585 sctx->send_progress = sctx->cur_ino;
6587 if (result == BTRFS_COMPARE_TREE_NEW ||
6588 result == BTRFS_COMPARE_TREE_CHANGED) {
6589 left_ii = btrfs_item_ptr(sctx->left_path->nodes[0],
6590 sctx->left_path->slots[0],
6591 struct btrfs_inode_item);
6592 left_gen = btrfs_inode_generation(sctx->left_path->nodes[0],
6595 right_ii = btrfs_item_ptr(sctx->right_path->nodes[0],
6596 sctx->right_path->slots[0],
6597 struct btrfs_inode_item);
6598 right_gen = btrfs_inode_generation(sctx->right_path->nodes[0],
6601 if (result == BTRFS_COMPARE_TREE_CHANGED) {
6602 right_ii = btrfs_item_ptr(sctx->right_path->nodes[0],
6603 sctx->right_path->slots[0],
6604 struct btrfs_inode_item);
6606 right_gen = btrfs_inode_generation(sctx->right_path->nodes[0],
6610 * The cur_ino = root dir case is special here. We can't treat
6611 * the inode as deleted+reused because it would generate a
6612 * stream that tries to delete/mkdir the root dir.
6614 if (left_gen != right_gen &&
6615 sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID)
6616 sctx->cur_inode_new_gen = true;
6620 * Normally we do not find inodes with a link count of zero (orphans)
6621 * because the most common case is to create a snapshot and use it
6622 * for a send operation. However other less common use cases involve
6623 * using a subvolume and send it after turning it to RO mode just
6624 * after deleting all hard links of a file while holding an open
6625 * file descriptor against it or turning a RO snapshot into RW mode,
6626 * keep an open file descriptor against a file, delete it and then
6627 * turn the snapshot back to RO mode before using it for a send
6628 * operation. The former is what the receiver operation does.
6629 * Therefore, if we want to send these snapshots soon after they're
6630 * received, we need to handle orphan inodes as well. Moreover, orphans
6631 * can appear not only in the send snapshot but also in the parent
6632 * snapshot. Here are several cases:
6634 * Case 1: BTRFS_COMPARE_TREE_NEW
6635 * | send snapshot | action
6636 * --------------------------------
6637 * nlink | 0 | ignore
6639 * Case 2: BTRFS_COMPARE_TREE_DELETED
6640 * | parent snapshot | action
6641 * ----------------------------------
6642 * nlink | 0 | as usual
6643 * Note: No unlinks will be sent because there're no paths for it.
6645 * Case 3: BTRFS_COMPARE_TREE_CHANGED
6646 * | | parent snapshot | send snapshot | action
6647 * -----------------------------------------------------------------------
6648 * subcase 1 | nlink | 0 | 0 | ignore
6649 * subcase 2 | nlink | >0 | 0 | new_gen(deletion)
6650 * subcase 3 | nlink | 0 | >0 | new_gen(creation)
6653 if (result == BTRFS_COMPARE_TREE_NEW) {
6654 if (btrfs_inode_nlink(sctx->left_path->nodes[0], left_ii) == 0) {
6655 sctx->ignore_cur_inode = true;
6658 sctx->cur_inode_gen = left_gen;
6659 sctx->cur_inode_new = true;
6660 sctx->cur_inode_deleted = false;
6661 sctx->cur_inode_size = btrfs_inode_size(
6662 sctx->left_path->nodes[0], left_ii);
6663 sctx->cur_inode_mode = btrfs_inode_mode(
6664 sctx->left_path->nodes[0], left_ii);
6665 sctx->cur_inode_rdev = btrfs_inode_rdev(
6666 sctx->left_path->nodes[0], left_ii);
6667 if (sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID)
6668 ret = send_create_inode_if_needed(sctx);
6669 } else if (result == BTRFS_COMPARE_TREE_DELETED) {
6670 sctx->cur_inode_gen = right_gen;
6671 sctx->cur_inode_new = false;
6672 sctx->cur_inode_deleted = true;
6673 sctx->cur_inode_size = btrfs_inode_size(
6674 sctx->right_path->nodes[0], right_ii);
6675 sctx->cur_inode_mode = btrfs_inode_mode(
6676 sctx->right_path->nodes[0], right_ii);
6677 } else if (result == BTRFS_COMPARE_TREE_CHANGED) {
6678 u32 new_nlinks, old_nlinks;
6680 new_nlinks = btrfs_inode_nlink(sctx->left_path->nodes[0], left_ii);
6681 old_nlinks = btrfs_inode_nlink(sctx->right_path->nodes[0], right_ii);
6682 if (new_nlinks == 0 && old_nlinks == 0) {
6683 sctx->ignore_cur_inode = true;
6685 } else if (new_nlinks == 0 || old_nlinks == 0) {
6686 sctx->cur_inode_new_gen = 1;
6689 * We need to do some special handling in case the inode was
6690 * reported as changed with a changed generation number. This
6691 * means that the original inode was deleted and new inode
6692 * reused the same inum. So we have to treat the old inode as
6693 * deleted and the new one as new.
6695 if (sctx->cur_inode_new_gen) {
6697 * First, process the inode as if it was deleted.
6699 if (old_nlinks > 0) {
6700 sctx->cur_inode_gen = right_gen;
6701 sctx->cur_inode_new = false;
6702 sctx->cur_inode_deleted = true;
6703 sctx->cur_inode_size = btrfs_inode_size(
6704 sctx->right_path->nodes[0], right_ii);
6705 sctx->cur_inode_mode = btrfs_inode_mode(
6706 sctx->right_path->nodes[0], right_ii);
6707 ret = process_all_refs(sctx,
6708 BTRFS_COMPARE_TREE_DELETED);
6714 * Now process the inode as if it was new.
6716 if (new_nlinks > 0) {
6717 sctx->cur_inode_gen = left_gen;
6718 sctx->cur_inode_new = true;
6719 sctx->cur_inode_deleted = false;
6720 sctx->cur_inode_size = btrfs_inode_size(
6721 sctx->left_path->nodes[0],
6723 sctx->cur_inode_mode = btrfs_inode_mode(
6724 sctx->left_path->nodes[0],
6726 sctx->cur_inode_rdev = btrfs_inode_rdev(
6727 sctx->left_path->nodes[0],
6729 ret = send_create_inode_if_needed(sctx);
6733 ret = process_all_refs(sctx, BTRFS_COMPARE_TREE_NEW);
6737 * Advance send_progress now as we did not get
6738 * into process_recorded_refs_if_needed in the
6741 sctx->send_progress = sctx->cur_ino + 1;
6744 * Now process all extents and xattrs of the
6745 * inode as if they were all new.
6747 ret = process_all_extents(sctx);
6750 ret = process_all_new_xattrs(sctx);
6755 sctx->cur_inode_gen = left_gen;
6756 sctx->cur_inode_new = false;
6757 sctx->cur_inode_new_gen = false;
6758 sctx->cur_inode_deleted = false;
6759 sctx->cur_inode_size = btrfs_inode_size(
6760 sctx->left_path->nodes[0], left_ii);
6761 sctx->cur_inode_mode = btrfs_inode_mode(
6762 sctx->left_path->nodes[0], left_ii);
6771 * We have to process new refs before deleted refs, but compare_trees gives us
6772 * the new and deleted refs mixed. To fix this, we record the new/deleted refs
6773 * first and later process them in process_recorded_refs.
6774 * For the cur_inode_new_gen case, we skip recording completely because
6775 * changed_inode did already initiate processing of refs. The reason for this is
6776 * that in this case, compare_tree actually compares the refs of 2 different
6777 * inodes. To fix this, process_all_refs is used in changed_inode to handle all
6778 * refs of the right tree as deleted and all refs of the left tree as new.
6780 static int changed_ref(struct send_ctx *sctx,
6781 enum btrfs_compare_tree_result result)
6785 if (sctx->cur_ino != sctx->cmp_key->objectid) {
6786 inconsistent_snapshot_error(sctx, result, "reference");
6790 if (!sctx->cur_inode_new_gen &&
6791 sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID) {
6792 if (result == BTRFS_COMPARE_TREE_NEW)
6793 ret = record_new_ref(sctx);
6794 else if (result == BTRFS_COMPARE_TREE_DELETED)
6795 ret = record_deleted_ref(sctx);
6796 else if (result == BTRFS_COMPARE_TREE_CHANGED)
6797 ret = record_changed_ref(sctx);
6804 * Process new/deleted/changed xattrs. We skip processing in the
6805 * cur_inode_new_gen case because changed_inode did already initiate processing
6806 * of xattrs. The reason is the same as in changed_ref
6808 static int changed_xattr(struct send_ctx *sctx,
6809 enum btrfs_compare_tree_result result)
6813 if (sctx->cur_ino != sctx->cmp_key->objectid) {
6814 inconsistent_snapshot_error(sctx, result, "xattr");
6818 if (!sctx->cur_inode_new_gen && !sctx->cur_inode_deleted) {
6819 if (result == BTRFS_COMPARE_TREE_NEW)
6820 ret = process_new_xattr(sctx);
6821 else if (result == BTRFS_COMPARE_TREE_DELETED)
6822 ret = process_deleted_xattr(sctx);
6823 else if (result == BTRFS_COMPARE_TREE_CHANGED)
6824 ret = process_changed_xattr(sctx);
6831 * Process new/deleted/changed extents. We skip processing in the
6832 * cur_inode_new_gen case because changed_inode did already initiate processing
6833 * of extents. The reason is the same as in changed_ref
6835 static int changed_extent(struct send_ctx *sctx,
6836 enum btrfs_compare_tree_result result)
6841 * We have found an extent item that changed without the inode item
6842 * having changed. This can happen either after relocation (where the
6843 * disk_bytenr of an extent item is replaced at
6844 * relocation.c:replace_file_extents()) or after deduplication into a
6845 * file in both the parent and send snapshots (where an extent item can
6846 * get modified or replaced with a new one). Note that deduplication
6847 * updates the inode item, but it only changes the iversion (sequence
6848 * field in the inode item) of the inode, so if a file is deduplicated
6849 * the same amount of times in both the parent and send snapshots, its
6850 * iversion becomes the same in both snapshots, whence the inode item is
6851 * the same on both snapshots.
6853 if (sctx->cur_ino != sctx->cmp_key->objectid)
6856 if (!sctx->cur_inode_new_gen && !sctx->cur_inode_deleted) {
6857 if (result != BTRFS_COMPARE_TREE_DELETED)
6858 ret = process_extent(sctx, sctx->left_path,
6865 static int changed_verity(struct send_ctx *sctx, enum btrfs_compare_tree_result result)
6869 if (!sctx->cur_inode_new_gen && !sctx->cur_inode_deleted) {
6870 if (result == BTRFS_COMPARE_TREE_NEW)
6871 sctx->cur_inode_needs_verity = true;
6876 static int dir_changed(struct send_ctx *sctx, u64 dir)
6878 u64 orig_gen, new_gen;
6881 ret = get_inode_gen(sctx->send_root, dir, &new_gen);
6885 ret = get_inode_gen(sctx->parent_root, dir, &orig_gen);
6889 return (orig_gen != new_gen) ? 1 : 0;
6892 static int compare_refs(struct send_ctx *sctx, struct btrfs_path *path,
6893 struct btrfs_key *key)
6895 struct btrfs_inode_extref *extref;
6896 struct extent_buffer *leaf;
6897 u64 dirid = 0, last_dirid = 0;
6904 /* Easy case, just check this one dirid */
6905 if (key->type == BTRFS_INODE_REF_KEY) {
6906 dirid = key->offset;
6908 ret = dir_changed(sctx, dirid);
6912 leaf = path->nodes[0];
6913 item_size = btrfs_item_size(leaf, path->slots[0]);
6914 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
6915 while (cur_offset < item_size) {
6916 extref = (struct btrfs_inode_extref *)(ptr +
6918 dirid = btrfs_inode_extref_parent(leaf, extref);
6919 ref_name_len = btrfs_inode_extref_name_len(leaf, extref);
6920 cur_offset += ref_name_len + sizeof(*extref);
6921 if (dirid == last_dirid)
6923 ret = dir_changed(sctx, dirid);
6933 * Updates compare related fields in sctx and simply forwards to the actual
6934 * changed_xxx functions.
6936 static int changed_cb(struct btrfs_path *left_path,
6937 struct btrfs_path *right_path,
6938 struct btrfs_key *key,
6939 enum btrfs_compare_tree_result result,
6940 struct send_ctx *sctx)
6945 * We can not hold the commit root semaphore here. This is because in
6946 * the case of sending and receiving to the same filesystem, using a
6947 * pipe, could result in a deadlock:
6949 * 1) The task running send blocks on the pipe because it's full;
6951 * 2) The task running receive, which is the only consumer of the pipe,
6952 * is waiting for a transaction commit (for example due to a space
6953 * reservation when doing a write or triggering a transaction commit
6954 * when creating a subvolume);
6956 * 3) The transaction is waiting to write lock the commit root semaphore,
6957 * but can not acquire it since it's being held at 1).
6959 * Down this call chain we write to the pipe through kernel_write().
6960 * The same type of problem can also happen when sending to a file that
6961 * is stored in the same filesystem - when reserving space for a write
6962 * into the file, we can trigger a transaction commit.
6964 * Our caller has supplied us with clones of leaves from the send and
6965 * parent roots, so we're safe here from a concurrent relocation and
6966 * further reallocation of metadata extents while we are here. Below we
6967 * also assert that the leaves are clones.
6969 lockdep_assert_not_held(&sctx->send_root->fs_info->commit_root_sem);
6972 * We always have a send root, so left_path is never NULL. We will not
6973 * have a leaf when we have reached the end of the send root but have
6974 * not yet reached the end of the parent root.
6976 if (left_path->nodes[0])
6977 ASSERT(test_bit(EXTENT_BUFFER_UNMAPPED,
6978 &left_path->nodes[0]->bflags));
6980 * When doing a full send we don't have a parent root, so right_path is
6981 * NULL. When doing an incremental send, we may have reached the end of
6982 * the parent root already, so we don't have a leaf at right_path.
6984 if (right_path && right_path->nodes[0])
6985 ASSERT(test_bit(EXTENT_BUFFER_UNMAPPED,
6986 &right_path->nodes[0]->bflags));
6988 if (result == BTRFS_COMPARE_TREE_SAME) {
6989 if (key->type == BTRFS_INODE_REF_KEY ||
6990 key->type == BTRFS_INODE_EXTREF_KEY) {
6991 ret = compare_refs(sctx, left_path, key);
6996 } else if (key->type == BTRFS_EXTENT_DATA_KEY) {
6997 return maybe_send_hole(sctx, left_path, key);
7001 result = BTRFS_COMPARE_TREE_CHANGED;
7005 sctx->left_path = left_path;
7006 sctx->right_path = right_path;
7007 sctx->cmp_key = key;
7009 ret = finish_inode_if_needed(sctx, 0);
7013 /* Ignore non-FS objects */
7014 if (key->objectid == BTRFS_FREE_INO_OBJECTID ||
7015 key->objectid == BTRFS_FREE_SPACE_OBJECTID)
7018 if (key->type == BTRFS_INODE_ITEM_KEY) {
7019 ret = changed_inode(sctx, result);
7020 } else if (!sctx->ignore_cur_inode) {
7021 if (key->type == BTRFS_INODE_REF_KEY ||
7022 key->type == BTRFS_INODE_EXTREF_KEY)
7023 ret = changed_ref(sctx, result);
7024 else if (key->type == BTRFS_XATTR_ITEM_KEY)
7025 ret = changed_xattr(sctx, result);
7026 else if (key->type == BTRFS_EXTENT_DATA_KEY)
7027 ret = changed_extent(sctx, result);
7028 else if (key->type == BTRFS_VERITY_DESC_ITEM_KEY &&
7030 ret = changed_verity(sctx, result);
7037 static int search_key_again(const struct send_ctx *sctx,
7038 struct btrfs_root *root,
7039 struct btrfs_path *path,
7040 const struct btrfs_key *key)
7044 if (!path->need_commit_sem)
7045 lockdep_assert_held_read(&root->fs_info->commit_root_sem);
7048 * Roots used for send operations are readonly and no one can add,
7049 * update or remove keys from them, so we should be able to find our
7050 * key again. The only exception is deduplication, which can operate on
7051 * readonly roots and add, update or remove keys to/from them - but at
7052 * the moment we don't allow it to run in parallel with send.
7054 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
7057 btrfs_print_tree(path->nodes[path->lowest_level], false);
7058 btrfs_err(root->fs_info,
7059 "send: key (%llu %u %llu) not found in %s root %llu, lowest_level %d, slot %d",
7060 key->objectid, key->type, key->offset,
7061 (root == sctx->parent_root ? "parent" : "send"),
7062 root->root_key.objectid, path->lowest_level,
7063 path->slots[path->lowest_level]);
7070 static int full_send_tree(struct send_ctx *sctx)
7073 struct btrfs_root *send_root = sctx->send_root;
7074 struct btrfs_key key;
7075 struct btrfs_fs_info *fs_info = send_root->fs_info;
7076 struct btrfs_path *path;
7078 path = alloc_path_for_send();
7081 path->reada = READA_FORWARD_ALWAYS;
7083 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
7084 key.type = BTRFS_INODE_ITEM_KEY;
7087 down_read(&fs_info->commit_root_sem);
7088 sctx->last_reloc_trans = fs_info->last_reloc_trans;
7089 up_read(&fs_info->commit_root_sem);
7091 ret = btrfs_search_slot_for_read(send_root, &key, path, 1, 0);
7098 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
7100 ret = changed_cb(path, NULL, &key,
7101 BTRFS_COMPARE_TREE_NEW, sctx);
7105 down_read(&fs_info->commit_root_sem);
7106 if (fs_info->last_reloc_trans > sctx->last_reloc_trans) {
7107 sctx->last_reloc_trans = fs_info->last_reloc_trans;
7108 up_read(&fs_info->commit_root_sem);
7110 * A transaction used for relocating a block group was
7111 * committed or is about to finish its commit. Release
7112 * our path (leaf) and restart the search, so that we
7113 * avoid operating on any file extent items that are
7114 * stale, with a disk_bytenr that reflects a pre
7115 * relocation value. This way we avoid as much as
7116 * possible to fallback to regular writes when checking
7117 * if we can clone file ranges.
7119 btrfs_release_path(path);
7120 ret = search_key_again(sctx, send_root, path, &key);
7124 up_read(&fs_info->commit_root_sem);
7127 ret = btrfs_next_item(send_root, path);
7137 ret = finish_inode_if_needed(sctx, 1);
7140 btrfs_free_path(path);
7144 static int replace_node_with_clone(struct btrfs_path *path, int level)
7146 struct extent_buffer *clone;
7148 clone = btrfs_clone_extent_buffer(path->nodes[level]);
7152 free_extent_buffer(path->nodes[level]);
7153 path->nodes[level] = clone;
7158 static int tree_move_down(struct btrfs_path *path, int *level, u64 reada_min_gen)
7160 struct extent_buffer *eb;
7161 struct extent_buffer *parent = path->nodes[*level];
7162 int slot = path->slots[*level];
7163 const int nritems = btrfs_header_nritems(parent);
7167 lockdep_assert_held_read(&parent->fs_info->commit_root_sem);
7169 BUG_ON(*level == 0);
7170 eb = btrfs_read_node_slot(parent, slot);
7175 * Trigger readahead for the next leaves we will process, so that it is
7176 * very likely that when we need them they are already in memory and we
7177 * will not block on disk IO. For nodes we only do readahead for one,
7178 * since the time window between processing nodes is typically larger.
7180 reada_max = (*level == 1 ? SZ_128K : eb->fs_info->nodesize);
7182 for (slot++; slot < nritems && reada_done < reada_max; slot++) {
7183 if (btrfs_node_ptr_generation(parent, slot) > reada_min_gen) {
7184 btrfs_readahead_node_child(parent, slot);
7185 reada_done += eb->fs_info->nodesize;
7189 path->nodes[*level - 1] = eb;
7190 path->slots[*level - 1] = 0;
7194 return replace_node_with_clone(path, 0);
7199 static int tree_move_next_or_upnext(struct btrfs_path *path,
7200 int *level, int root_level)
7204 nritems = btrfs_header_nritems(path->nodes[*level]);
7206 path->slots[*level]++;
7208 while (path->slots[*level] >= nritems) {
7209 if (*level == root_level) {
7210 path->slots[*level] = nritems - 1;
7215 path->slots[*level] = 0;
7216 free_extent_buffer(path->nodes[*level]);
7217 path->nodes[*level] = NULL;
7219 path->slots[*level]++;
7221 nritems = btrfs_header_nritems(path->nodes[*level]);
7228 * Returns 1 if it had to move up and next. 0 is returned if it moved only next
7231 static int tree_advance(struct btrfs_path *path,
7232 int *level, int root_level,
7234 struct btrfs_key *key,
7239 if (*level == 0 || !allow_down) {
7240 ret = tree_move_next_or_upnext(path, level, root_level);
7242 ret = tree_move_down(path, level, reada_min_gen);
7246 * Even if we have reached the end of a tree, ret is -1, update the key
7247 * anyway, so that in case we need to restart due to a block group
7248 * relocation, we can assert that the last key of the root node still
7249 * exists in the tree.
7252 btrfs_item_key_to_cpu(path->nodes[*level], key,
7253 path->slots[*level]);
7255 btrfs_node_key_to_cpu(path->nodes[*level], key,
7256 path->slots[*level]);
7261 static int tree_compare_item(struct btrfs_path *left_path,
7262 struct btrfs_path *right_path,
7267 unsigned long off1, off2;
7269 len1 = btrfs_item_size(left_path->nodes[0], left_path->slots[0]);
7270 len2 = btrfs_item_size(right_path->nodes[0], right_path->slots[0]);
7274 off1 = btrfs_item_ptr_offset(left_path->nodes[0], left_path->slots[0]);
7275 off2 = btrfs_item_ptr_offset(right_path->nodes[0],
7276 right_path->slots[0]);
7278 read_extent_buffer(left_path->nodes[0], tmp_buf, off1, len1);
7280 cmp = memcmp_extent_buffer(right_path->nodes[0], tmp_buf, off2, len1);
7287 * A transaction used for relocating a block group was committed or is about to
7288 * finish its commit. Release our paths and restart the search, so that we are
7289 * not using stale extent buffers:
7291 * 1) For levels > 0, we are only holding references of extent buffers, without
7292 * any locks on them, which does not prevent them from having been relocated
7293 * and reallocated after the last time we released the commit root semaphore.
7294 * The exception are the root nodes, for which we always have a clone, see
7295 * the comment at btrfs_compare_trees();
7297 * 2) For leaves, level 0, we are holding copies (clones) of extent buffers, so
7298 * we are safe from the concurrent relocation and reallocation. However they
7299 * can have file extent items with a pre relocation disk_bytenr value, so we
7300 * restart the start from the current commit roots and clone the new leaves so
7301 * that we get the post relocation disk_bytenr values. Not doing so, could
7302 * make us clone the wrong data in case there are new extents using the old
7303 * disk_bytenr that happen to be shared.
7305 static int restart_after_relocation(struct btrfs_path *left_path,
7306 struct btrfs_path *right_path,
7307 const struct btrfs_key *left_key,
7308 const struct btrfs_key *right_key,
7311 const struct send_ctx *sctx)
7316 lockdep_assert_held_read(&sctx->send_root->fs_info->commit_root_sem);
7318 btrfs_release_path(left_path);
7319 btrfs_release_path(right_path);
7322 * Since keys can not be added or removed to/from our roots because they
7323 * are readonly and we do not allow deduplication to run in parallel
7324 * (which can add, remove or change keys), the layout of the trees should
7327 left_path->lowest_level = left_level;
7328 ret = search_key_again(sctx, sctx->send_root, left_path, left_key);
7332 right_path->lowest_level = right_level;
7333 ret = search_key_again(sctx, sctx->parent_root, right_path, right_key);
7338 * If the lowest level nodes are leaves, clone them so that they can be
7339 * safely used by changed_cb() while not under the protection of the
7340 * commit root semaphore, even if relocation and reallocation happens in
7343 if (left_level == 0) {
7344 ret = replace_node_with_clone(left_path, 0);
7349 if (right_level == 0) {
7350 ret = replace_node_with_clone(right_path, 0);
7356 * Now clone the root nodes (unless they happen to be the leaves we have
7357 * already cloned). This is to protect against concurrent snapshotting of
7358 * the send and parent roots (see the comment at btrfs_compare_trees()).
7360 root_level = btrfs_header_level(sctx->send_root->commit_root);
7361 if (root_level > 0) {
7362 ret = replace_node_with_clone(left_path, root_level);
7367 root_level = btrfs_header_level(sctx->parent_root->commit_root);
7368 if (root_level > 0) {
7369 ret = replace_node_with_clone(right_path, root_level);
7378 * This function compares two trees and calls the provided callback for
7379 * every changed/new/deleted item it finds.
7380 * If shared tree blocks are encountered, whole subtrees are skipped, making
7381 * the compare pretty fast on snapshotted subvolumes.
7383 * This currently works on commit roots only. As commit roots are read only,
7384 * we don't do any locking. The commit roots are protected with transactions.
7385 * Transactions are ended and rejoined when a commit is tried in between.
7387 * This function checks for modifications done to the trees while comparing.
7388 * If it detects a change, it aborts immediately.
7390 static int btrfs_compare_trees(struct btrfs_root *left_root,
7391 struct btrfs_root *right_root, struct send_ctx *sctx)
7393 struct btrfs_fs_info *fs_info = left_root->fs_info;
7396 struct btrfs_path *left_path = NULL;
7397 struct btrfs_path *right_path = NULL;
7398 struct btrfs_key left_key;
7399 struct btrfs_key right_key;
7400 char *tmp_buf = NULL;
7401 int left_root_level;
7402 int right_root_level;
7405 int left_end_reached = 0;
7406 int right_end_reached = 0;
7407 int advance_left = 0;
7408 int advance_right = 0;
7415 left_path = btrfs_alloc_path();
7420 right_path = btrfs_alloc_path();
7426 tmp_buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
7432 left_path->search_commit_root = 1;
7433 left_path->skip_locking = 1;
7434 right_path->search_commit_root = 1;
7435 right_path->skip_locking = 1;
7438 * Strategy: Go to the first items of both trees. Then do
7440 * If both trees are at level 0
7441 * Compare keys of current items
7442 * If left < right treat left item as new, advance left tree
7444 * If left > right treat right item as deleted, advance right tree
7446 * If left == right do deep compare of items, treat as changed if
7447 * needed, advance both trees and repeat
7448 * If both trees are at the same level but not at level 0
7449 * Compare keys of current nodes/leafs
7450 * If left < right advance left tree and repeat
7451 * If left > right advance right tree and repeat
7452 * If left == right compare blockptrs of the next nodes/leafs
7453 * If they match advance both trees but stay at the same level
7455 * If they don't match advance both trees while allowing to go
7457 * If tree levels are different
7458 * Advance the tree that needs it and repeat
7460 * Advancing a tree means:
7461 * If we are at level 0, try to go to the next slot. If that's not
7462 * possible, go one level up and repeat. Stop when we found a level
7463 * where we could go to the next slot. We may at this point be on a
7466 * If we are not at level 0 and not on shared tree blocks, go one
7469 * If we are not at level 0 and on shared tree blocks, go one slot to
7470 * the right if possible or go up and right.
7473 down_read(&fs_info->commit_root_sem);
7474 left_level = btrfs_header_level(left_root->commit_root);
7475 left_root_level = left_level;
7477 * We clone the root node of the send and parent roots to prevent races
7478 * with snapshot creation of these roots. Snapshot creation COWs the
7479 * root node of a tree, so after the transaction is committed the old
7480 * extent can be reallocated while this send operation is still ongoing.
7481 * So we clone them, under the commit root semaphore, to be race free.
7483 left_path->nodes[left_level] =
7484 btrfs_clone_extent_buffer(left_root->commit_root);
7485 if (!left_path->nodes[left_level]) {
7490 right_level = btrfs_header_level(right_root->commit_root);
7491 right_root_level = right_level;
7492 right_path->nodes[right_level] =
7493 btrfs_clone_extent_buffer(right_root->commit_root);
7494 if (!right_path->nodes[right_level]) {
7499 * Our right root is the parent root, while the left root is the "send"
7500 * root. We know that all new nodes/leaves in the left root must have
7501 * a generation greater than the right root's generation, so we trigger
7502 * readahead for those nodes and leaves of the left root, as we know we
7503 * will need to read them at some point.
7505 reada_min_gen = btrfs_header_generation(right_root->commit_root);
7507 if (left_level == 0)
7508 btrfs_item_key_to_cpu(left_path->nodes[left_level],
7509 &left_key, left_path->slots[left_level]);
7511 btrfs_node_key_to_cpu(left_path->nodes[left_level],
7512 &left_key, left_path->slots[left_level]);
7513 if (right_level == 0)
7514 btrfs_item_key_to_cpu(right_path->nodes[right_level],
7515 &right_key, right_path->slots[right_level]);
7517 btrfs_node_key_to_cpu(right_path->nodes[right_level],
7518 &right_key, right_path->slots[right_level]);
7520 sctx->last_reloc_trans = fs_info->last_reloc_trans;
7523 if (need_resched() ||
7524 rwsem_is_contended(&fs_info->commit_root_sem)) {
7525 up_read(&fs_info->commit_root_sem);
7527 down_read(&fs_info->commit_root_sem);
7530 if (fs_info->last_reloc_trans > sctx->last_reloc_trans) {
7531 ret = restart_after_relocation(left_path, right_path,
7532 &left_key, &right_key,
7533 left_level, right_level,
7537 sctx->last_reloc_trans = fs_info->last_reloc_trans;
7540 if (advance_left && !left_end_reached) {
7541 ret = tree_advance(left_path, &left_level,
7543 advance_left != ADVANCE_ONLY_NEXT,
7544 &left_key, reada_min_gen);
7546 left_end_reached = ADVANCE;
7551 if (advance_right && !right_end_reached) {
7552 ret = tree_advance(right_path, &right_level,
7554 advance_right != ADVANCE_ONLY_NEXT,
7555 &right_key, reada_min_gen);
7557 right_end_reached = ADVANCE;
7563 if (left_end_reached && right_end_reached) {
7566 } else if (left_end_reached) {
7567 if (right_level == 0) {
7568 up_read(&fs_info->commit_root_sem);
7569 ret = changed_cb(left_path, right_path,
7571 BTRFS_COMPARE_TREE_DELETED,
7575 down_read(&fs_info->commit_root_sem);
7577 advance_right = ADVANCE;
7579 } else if (right_end_reached) {
7580 if (left_level == 0) {
7581 up_read(&fs_info->commit_root_sem);
7582 ret = changed_cb(left_path, right_path,
7584 BTRFS_COMPARE_TREE_NEW,
7588 down_read(&fs_info->commit_root_sem);
7590 advance_left = ADVANCE;
7594 if (left_level == 0 && right_level == 0) {
7595 up_read(&fs_info->commit_root_sem);
7596 cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
7598 ret = changed_cb(left_path, right_path,
7600 BTRFS_COMPARE_TREE_NEW,
7602 advance_left = ADVANCE;
7603 } else if (cmp > 0) {
7604 ret = changed_cb(left_path, right_path,
7606 BTRFS_COMPARE_TREE_DELETED,
7608 advance_right = ADVANCE;
7610 enum btrfs_compare_tree_result result;
7612 WARN_ON(!extent_buffer_uptodate(left_path->nodes[0]));
7613 ret = tree_compare_item(left_path, right_path,
7616 result = BTRFS_COMPARE_TREE_CHANGED;
7618 result = BTRFS_COMPARE_TREE_SAME;
7619 ret = changed_cb(left_path, right_path,
7620 &left_key, result, sctx);
7621 advance_left = ADVANCE;
7622 advance_right = ADVANCE;
7627 down_read(&fs_info->commit_root_sem);
7628 } else if (left_level == right_level) {
7629 cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
7631 advance_left = ADVANCE;
7632 } else if (cmp > 0) {
7633 advance_right = ADVANCE;
7635 left_blockptr = btrfs_node_blockptr(
7636 left_path->nodes[left_level],
7637 left_path->slots[left_level]);
7638 right_blockptr = btrfs_node_blockptr(
7639 right_path->nodes[right_level],
7640 right_path->slots[right_level]);
7641 left_gen = btrfs_node_ptr_generation(
7642 left_path->nodes[left_level],
7643 left_path->slots[left_level]);
7644 right_gen = btrfs_node_ptr_generation(
7645 right_path->nodes[right_level],
7646 right_path->slots[right_level]);
7647 if (left_blockptr == right_blockptr &&
7648 left_gen == right_gen) {
7650 * As we're on a shared block, don't
7651 * allow to go deeper.
7653 advance_left = ADVANCE_ONLY_NEXT;
7654 advance_right = ADVANCE_ONLY_NEXT;
7656 advance_left = ADVANCE;
7657 advance_right = ADVANCE;
7660 } else if (left_level < right_level) {
7661 advance_right = ADVANCE;
7663 advance_left = ADVANCE;
7668 up_read(&fs_info->commit_root_sem);
7670 btrfs_free_path(left_path);
7671 btrfs_free_path(right_path);
7676 static int send_subvol(struct send_ctx *sctx)
7680 if (!(sctx->flags & BTRFS_SEND_FLAG_OMIT_STREAM_HEADER)) {
7681 ret = send_header(sctx);
7686 ret = send_subvol_begin(sctx);
7690 if (sctx->parent_root) {
7691 ret = btrfs_compare_trees(sctx->send_root, sctx->parent_root, sctx);
7694 ret = finish_inode_if_needed(sctx, 1);
7698 ret = full_send_tree(sctx);
7704 free_recorded_refs(sctx);
7709 * If orphan cleanup did remove any orphans from a root, it means the tree
7710 * was modified and therefore the commit root is not the same as the current
7711 * root anymore. This is a problem, because send uses the commit root and
7712 * therefore can see inode items that don't exist in the current root anymore,
7713 * and for example make calls to btrfs_iget, which will do tree lookups based
7714 * on the current root and not on the commit root. Those lookups will fail,
7715 * returning a -ESTALE error, and making send fail with that error. So make
7716 * sure a send does not see any orphans we have just removed, and that it will
7717 * see the same inodes regardless of whether a transaction commit happened
7718 * before it started (meaning that the commit root will be the same as the
7719 * current root) or not.
7721 static int ensure_commit_roots_uptodate(struct send_ctx *sctx)
7724 struct btrfs_trans_handle *trans = NULL;
7727 if (sctx->parent_root &&
7728 sctx->parent_root->node != sctx->parent_root->commit_root)
7731 for (i = 0; i < sctx->clone_roots_cnt; i++)
7732 if (sctx->clone_roots[i].root->node !=
7733 sctx->clone_roots[i].root->commit_root)
7737 return btrfs_end_transaction(trans);
7742 /* Use any root, all fs roots will get their commit roots updated. */
7744 trans = btrfs_join_transaction(sctx->send_root);
7746 return PTR_ERR(trans);
7750 return btrfs_commit_transaction(trans);
7754 * Make sure any existing dellaloc is flushed for any root used by a send
7755 * operation so that we do not miss any data and we do not race with writeback
7756 * finishing and changing a tree while send is using the tree. This could
7757 * happen if a subvolume is in RW mode, has delalloc, is turned to RO mode and
7758 * a send operation then uses the subvolume.
7759 * After flushing delalloc ensure_commit_roots_uptodate() must be called.
7761 static int flush_delalloc_roots(struct send_ctx *sctx)
7763 struct btrfs_root *root = sctx->parent_root;
7768 ret = btrfs_start_delalloc_snapshot(root, false);
7771 btrfs_wait_ordered_extents(root, U64_MAX, 0, U64_MAX);
7774 for (i = 0; i < sctx->clone_roots_cnt; i++) {
7775 root = sctx->clone_roots[i].root;
7776 ret = btrfs_start_delalloc_snapshot(root, false);
7779 btrfs_wait_ordered_extents(root, U64_MAX, 0, U64_MAX);
7785 static void btrfs_root_dec_send_in_progress(struct btrfs_root* root)
7787 spin_lock(&root->root_item_lock);
7788 root->send_in_progress--;
7790 * Not much left to do, we don't know why it's unbalanced and
7791 * can't blindly reset it to 0.
7793 if (root->send_in_progress < 0)
7794 btrfs_err(root->fs_info,
7795 "send_in_progress unbalanced %d root %llu",
7796 root->send_in_progress, root->root_key.objectid);
7797 spin_unlock(&root->root_item_lock);
7800 static void dedupe_in_progress_warn(const struct btrfs_root *root)
7802 btrfs_warn_rl(root->fs_info,
7803 "cannot use root %llu for send while deduplications on it are in progress (%d in progress)",
7804 root->root_key.objectid, root->dedupe_in_progress);
7807 long btrfs_ioctl_send(struct inode *inode, struct btrfs_ioctl_send_args *arg)
7810 struct btrfs_root *send_root = BTRFS_I(inode)->root;
7811 struct btrfs_fs_info *fs_info = send_root->fs_info;
7812 struct btrfs_root *clone_root;
7813 struct send_ctx *sctx = NULL;
7815 u64 *clone_sources_tmp = NULL;
7816 int clone_sources_to_rollback = 0;
7818 int sort_clone_roots = 0;
7820 if (!capable(CAP_SYS_ADMIN))
7824 * The subvolume must remain read-only during send, protect against
7825 * making it RW. This also protects against deletion.
7827 spin_lock(&send_root->root_item_lock);
7828 if (btrfs_root_readonly(send_root) && send_root->dedupe_in_progress) {
7829 dedupe_in_progress_warn(send_root);
7830 spin_unlock(&send_root->root_item_lock);
7833 send_root->send_in_progress++;
7834 spin_unlock(&send_root->root_item_lock);
7837 * Userspace tools do the checks and warn the user if it's
7840 if (!btrfs_root_readonly(send_root)) {
7846 * Check that we don't overflow at later allocations, we request
7847 * clone_sources_count + 1 items, and compare to unsigned long inside
7850 if (arg->clone_sources_count >
7851 ULONG_MAX / sizeof(struct clone_root) - 1) {
7856 if (arg->flags & ~BTRFS_SEND_FLAG_MASK) {
7861 sctx = kzalloc(sizeof(struct send_ctx), GFP_KERNEL);
7867 INIT_LIST_HEAD(&sctx->new_refs);
7868 INIT_LIST_HEAD(&sctx->deleted_refs);
7869 INIT_RADIX_TREE(&sctx->name_cache, GFP_KERNEL);
7870 INIT_LIST_HEAD(&sctx->name_cache_list);
7872 sctx->flags = arg->flags;
7874 if (arg->flags & BTRFS_SEND_FLAG_VERSION) {
7875 if (arg->version > BTRFS_SEND_STREAM_VERSION) {
7879 /* Zero means "use the highest version" */
7880 sctx->proto = arg->version ?: BTRFS_SEND_STREAM_VERSION;
7884 if ((arg->flags & BTRFS_SEND_FLAG_COMPRESSED) && sctx->proto < 2) {
7889 sctx->send_filp = fget(arg->send_fd);
7890 if (!sctx->send_filp) {
7895 sctx->send_root = send_root;
7897 * Unlikely but possible, if the subvolume is marked for deletion but
7898 * is slow to remove the directory entry, send can still be started
7900 if (btrfs_root_dead(sctx->send_root)) {
7905 sctx->clone_roots_cnt = arg->clone_sources_count;
7907 if (sctx->proto >= 2) {
7908 u32 send_buf_num_pages;
7910 sctx->send_max_size = BTRFS_SEND_BUF_SIZE_V2;
7911 sctx->send_buf = vmalloc(sctx->send_max_size);
7912 if (!sctx->send_buf) {
7916 send_buf_num_pages = sctx->send_max_size >> PAGE_SHIFT;
7917 sctx->send_buf_pages = kcalloc(send_buf_num_pages,
7918 sizeof(*sctx->send_buf_pages),
7920 if (!sctx->send_buf_pages) {
7924 for (i = 0; i < send_buf_num_pages; i++) {
7925 sctx->send_buf_pages[i] =
7926 vmalloc_to_page(sctx->send_buf + (i << PAGE_SHIFT));
7929 sctx->send_max_size = BTRFS_SEND_BUF_SIZE_V1;
7930 sctx->send_buf = kvmalloc(sctx->send_max_size, GFP_KERNEL);
7932 if (!sctx->send_buf) {
7937 sctx->pending_dir_moves = RB_ROOT;
7938 sctx->waiting_dir_moves = RB_ROOT;
7939 sctx->orphan_dirs = RB_ROOT;
7940 sctx->rbtree_new_refs = RB_ROOT;
7941 sctx->rbtree_deleted_refs = RB_ROOT;
7943 sctx->clone_roots = kvcalloc(sizeof(*sctx->clone_roots),
7944 arg->clone_sources_count + 1,
7946 if (!sctx->clone_roots) {
7951 alloc_size = array_size(sizeof(*arg->clone_sources),
7952 arg->clone_sources_count);
7954 if (arg->clone_sources_count) {
7955 clone_sources_tmp = kvmalloc(alloc_size, GFP_KERNEL);
7956 if (!clone_sources_tmp) {
7961 ret = copy_from_user(clone_sources_tmp, arg->clone_sources,
7968 for (i = 0; i < arg->clone_sources_count; i++) {
7969 clone_root = btrfs_get_fs_root(fs_info,
7970 clone_sources_tmp[i], true);
7971 if (IS_ERR(clone_root)) {
7972 ret = PTR_ERR(clone_root);
7975 spin_lock(&clone_root->root_item_lock);
7976 if (!btrfs_root_readonly(clone_root) ||
7977 btrfs_root_dead(clone_root)) {
7978 spin_unlock(&clone_root->root_item_lock);
7979 btrfs_put_root(clone_root);
7983 if (clone_root->dedupe_in_progress) {
7984 dedupe_in_progress_warn(clone_root);
7985 spin_unlock(&clone_root->root_item_lock);
7986 btrfs_put_root(clone_root);
7990 clone_root->send_in_progress++;
7991 spin_unlock(&clone_root->root_item_lock);
7993 sctx->clone_roots[i].root = clone_root;
7994 clone_sources_to_rollback = i + 1;
7996 kvfree(clone_sources_tmp);
7997 clone_sources_tmp = NULL;
8000 if (arg->parent_root) {
8001 sctx->parent_root = btrfs_get_fs_root(fs_info, arg->parent_root,
8003 if (IS_ERR(sctx->parent_root)) {
8004 ret = PTR_ERR(sctx->parent_root);
8008 spin_lock(&sctx->parent_root->root_item_lock);
8009 sctx->parent_root->send_in_progress++;
8010 if (!btrfs_root_readonly(sctx->parent_root) ||
8011 btrfs_root_dead(sctx->parent_root)) {
8012 spin_unlock(&sctx->parent_root->root_item_lock);
8016 if (sctx->parent_root->dedupe_in_progress) {
8017 dedupe_in_progress_warn(sctx->parent_root);
8018 spin_unlock(&sctx->parent_root->root_item_lock);
8022 spin_unlock(&sctx->parent_root->root_item_lock);
8026 * Clones from send_root are allowed, but only if the clone source
8027 * is behind the current send position. This is checked while searching
8028 * for possible clone sources.
8030 sctx->clone_roots[sctx->clone_roots_cnt++].root =
8031 btrfs_grab_root(sctx->send_root);
8033 /* We do a bsearch later */
8034 sort(sctx->clone_roots, sctx->clone_roots_cnt,
8035 sizeof(*sctx->clone_roots), __clone_root_cmp_sort,
8037 sort_clone_roots = 1;
8039 ret = flush_delalloc_roots(sctx);
8043 ret = ensure_commit_roots_uptodate(sctx);
8047 ret = send_subvol(sctx);
8051 if (!(sctx->flags & BTRFS_SEND_FLAG_OMIT_END_CMD)) {
8052 ret = begin_cmd(sctx, BTRFS_SEND_C_END);
8055 ret = send_cmd(sctx);
8061 WARN_ON(sctx && !ret && !RB_EMPTY_ROOT(&sctx->pending_dir_moves));
8062 while (sctx && !RB_EMPTY_ROOT(&sctx->pending_dir_moves)) {
8064 struct pending_dir_move *pm;
8066 n = rb_first(&sctx->pending_dir_moves);
8067 pm = rb_entry(n, struct pending_dir_move, node);
8068 while (!list_empty(&pm->list)) {
8069 struct pending_dir_move *pm2;
8071 pm2 = list_first_entry(&pm->list,
8072 struct pending_dir_move, list);
8073 free_pending_move(sctx, pm2);
8075 free_pending_move(sctx, pm);
8078 WARN_ON(sctx && !ret && !RB_EMPTY_ROOT(&sctx->waiting_dir_moves));
8079 while (sctx && !RB_EMPTY_ROOT(&sctx->waiting_dir_moves)) {
8081 struct waiting_dir_move *dm;
8083 n = rb_first(&sctx->waiting_dir_moves);
8084 dm = rb_entry(n, struct waiting_dir_move, node);
8085 rb_erase(&dm->node, &sctx->waiting_dir_moves);
8089 WARN_ON(sctx && !ret && !RB_EMPTY_ROOT(&sctx->orphan_dirs));
8090 while (sctx && !RB_EMPTY_ROOT(&sctx->orphan_dirs)) {
8092 struct orphan_dir_info *odi;
8094 n = rb_first(&sctx->orphan_dirs);
8095 odi = rb_entry(n, struct orphan_dir_info, node);
8096 free_orphan_dir_info(sctx, odi);
8099 if (sort_clone_roots) {
8100 for (i = 0; i < sctx->clone_roots_cnt; i++) {
8101 btrfs_root_dec_send_in_progress(
8102 sctx->clone_roots[i].root);
8103 btrfs_put_root(sctx->clone_roots[i].root);
8106 for (i = 0; sctx && i < clone_sources_to_rollback; i++) {
8107 btrfs_root_dec_send_in_progress(
8108 sctx->clone_roots[i].root);
8109 btrfs_put_root(sctx->clone_roots[i].root);
8112 btrfs_root_dec_send_in_progress(send_root);
8114 if (sctx && !IS_ERR_OR_NULL(sctx->parent_root)) {
8115 btrfs_root_dec_send_in_progress(sctx->parent_root);
8116 btrfs_put_root(sctx->parent_root);
8119 kvfree(clone_sources_tmp);
8122 if (sctx->send_filp)
8123 fput(sctx->send_filp);
8125 kvfree(sctx->clone_roots);
8126 kfree(sctx->send_buf_pages);
8127 kvfree(sctx->send_buf);
8128 kvfree(sctx->verity_descriptor);
8130 name_cache_free(sctx);
8132 close_current_inode(sctx);