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>
24 #include "btrfs_inode.h"
25 #include "transaction.h"
26 #include "compression.h"
28 #include "print-tree.h"
31 * Maximum number of references an extent can have in order for us to attempt to
32 * issue clone operations instead of write operations. This currently exists to
33 * avoid hitting limitations of the backreference walking code (taking a lot of
34 * time and using too much memory for extents with large number of references).
36 #define SEND_MAX_EXTENT_REFS 64
39 * A fs_path is a helper to dynamically build path names with unknown size.
40 * It reallocates the internal buffer on demand.
41 * It allows fast adding of path elements on the right side (normal path) and
42 * fast adding to the left side (reversed path). A reversed path can also be
43 * unreversed if needed.
52 unsigned short buf_len:15;
53 unsigned short reversed:1;
57 * Average path length does not exceed 200 bytes, we'll have
58 * better packing in the slab and higher chance to satisfy
59 * a allocation later during send.
64 #define FS_PATH_INLINE_SIZE \
65 (sizeof(struct fs_path) - offsetof(struct fs_path, inline_buf))
68 /* reused for each extent */
70 struct btrfs_root *root;
77 #define SEND_CTX_MAX_NAME_CACHE_SIZE 128
78 #define SEND_CTX_NAME_CACHE_CLEAN_SIZE (SEND_CTX_MAX_NAME_CACHE_SIZE * 2)
81 struct file *send_filp;
87 * Whether BTRFS_SEND_A_DATA attribute was already added to current
88 * command (since protocol v2, data must be the last attribute).
91 struct page **send_buf_pages;
92 u64 flags; /* 'flags' member of btrfs_ioctl_send_args is u64 */
93 /* Protocol version compatibility requested */
96 struct btrfs_root *send_root;
97 struct btrfs_root *parent_root;
98 struct clone_root *clone_roots;
101 /* current state of the compare_tree call */
102 struct btrfs_path *left_path;
103 struct btrfs_path *right_path;
104 struct btrfs_key *cmp_key;
107 * Keep track of the generation of the last transaction that was used
108 * for relocating a block group. This is periodically checked in order
109 * to detect if a relocation happened since the last check, so that we
110 * don't operate on stale extent buffers for nodes (level >= 1) or on
111 * stale disk_bytenr values of file extent items.
113 u64 last_reloc_trans;
116 * infos of the currently processed inode. In case of deleted inodes,
117 * these are the values from the deleted inode.
124 u64 cur_inode_last_extent;
125 u64 cur_inode_next_write_offset;
127 bool cur_inode_new_gen;
128 bool cur_inode_deleted;
129 bool ignore_cur_inode;
133 struct list_head new_refs;
134 struct list_head deleted_refs;
136 struct radix_tree_root name_cache;
137 struct list_head name_cache_list;
141 * The inode we are currently processing. It's not NULL only when we
142 * need to issue write commands for data extents from this inode.
144 struct inode *cur_inode;
145 struct file_ra_state ra;
146 u64 page_cache_clear_start;
147 bool clean_page_cache;
150 * We process inodes by their increasing order, so if before an
151 * incremental send we reverse the parent/child relationship of
152 * directories such that a directory with a lower inode number was
153 * the parent of a directory with a higher inode number, and the one
154 * becoming the new parent got renamed too, we can't rename/move the
155 * directory with lower inode number when we finish processing it - we
156 * must process the directory with higher inode number first, then
157 * rename/move it and then rename/move the directory with lower inode
158 * number. Example follows.
160 * Tree state when the first send was performed:
172 * Tree state when the second (incremental) send is performed:
181 * The sequence of steps that lead to the second state was:
183 * mv /a/b/c/d /a/b/c2/d2
184 * mv /a/b/c /a/b/c2/d2/cc
186 * "c" has lower inode number, but we can't move it (2nd mv operation)
187 * before we move "d", which has higher inode number.
189 * So we just memorize which move/rename operations must be performed
190 * later when their respective parent is processed and moved/renamed.
193 /* Indexed by parent directory inode number. */
194 struct rb_root pending_dir_moves;
197 * Reverse index, indexed by the inode number of a directory that
198 * is waiting for the move/rename of its immediate parent before its
199 * own move/rename can be performed.
201 struct rb_root waiting_dir_moves;
204 * A directory that is going to be rm'ed might have a child directory
205 * which is in the pending directory moves index above. In this case,
206 * the directory can only be removed after the move/rename of its child
207 * is performed. Example:
227 * Sequence of steps that lead to the send snapshot:
228 * rm -f /a/b/c/foo.txt
230 * mv /a/b/c/x /a/b/YY
233 * When the child is processed, its move/rename is delayed until its
234 * parent is processed (as explained above), but all other operations
235 * like update utimes, chown, chgrp, etc, are performed and the paths
236 * that it uses for those operations must use the orphanized name of
237 * its parent (the directory we're going to rm later), so we need to
238 * memorize that name.
240 * Indexed by the inode number of the directory to be deleted.
242 struct rb_root orphan_dirs;
244 struct rb_root rbtree_new_refs;
245 struct rb_root rbtree_deleted_refs;
248 struct pending_dir_move {
250 struct list_head list;
254 struct list_head update_refs;
257 struct waiting_dir_move {
261 * There might be some directory that could not be removed because it
262 * was waiting for this directory inode to be moved first. Therefore
263 * after this directory is moved, we can try to rmdir the ino rmdir_ino.
270 struct orphan_dir_info {
274 u64 last_dir_index_offset;
277 struct name_cache_entry {
278 struct list_head list;
280 * radix_tree has only 32bit entries but we need to handle 64bit inums.
281 * We use the lower 32bit of the 64bit inum to store it in the tree. If
282 * more then one inum would fall into the same entry, we use radix_list
283 * to store the additional entries. radix_list is also used to store
284 * entries where two entries have the same inum but different
287 struct list_head radix_list;
293 int need_later_update;
299 #define ADVANCE_ONLY_NEXT -1
301 enum btrfs_compare_tree_result {
302 BTRFS_COMPARE_TREE_NEW,
303 BTRFS_COMPARE_TREE_DELETED,
304 BTRFS_COMPARE_TREE_CHANGED,
305 BTRFS_COMPARE_TREE_SAME,
309 static void inconsistent_snapshot_error(struct send_ctx *sctx,
310 enum btrfs_compare_tree_result result,
313 const char *result_string;
316 case BTRFS_COMPARE_TREE_NEW:
317 result_string = "new";
319 case BTRFS_COMPARE_TREE_DELETED:
320 result_string = "deleted";
322 case BTRFS_COMPARE_TREE_CHANGED:
323 result_string = "updated";
325 case BTRFS_COMPARE_TREE_SAME:
327 result_string = "unchanged";
331 result_string = "unexpected";
334 btrfs_err(sctx->send_root->fs_info,
335 "Send: inconsistent snapshot, found %s %s for inode %llu without updated inode item, send root is %llu, parent root is %llu",
336 result_string, what, sctx->cmp_key->objectid,
337 sctx->send_root->root_key.objectid,
339 sctx->parent_root->root_key.objectid : 0));
343 static bool proto_cmd_ok(const struct send_ctx *sctx, int cmd)
345 switch (sctx->proto) {
346 case 1: return cmd <= BTRFS_SEND_C_MAX_V1;
347 case 2: return cmd <= BTRFS_SEND_C_MAX_V2;
348 default: return false;
352 static int is_waiting_for_move(struct send_ctx *sctx, u64 ino);
354 static struct waiting_dir_move *
355 get_waiting_dir_move(struct send_ctx *sctx, u64 ino);
357 static int is_waiting_for_rm(struct send_ctx *sctx, u64 dir_ino, u64 gen);
359 static int need_send_hole(struct send_ctx *sctx)
361 return (sctx->parent_root && !sctx->cur_inode_new &&
362 !sctx->cur_inode_new_gen && !sctx->cur_inode_deleted &&
363 S_ISREG(sctx->cur_inode_mode));
366 static void fs_path_reset(struct fs_path *p)
369 p->start = p->buf + p->buf_len - 1;
379 static struct fs_path *fs_path_alloc(void)
383 p = kmalloc(sizeof(*p), GFP_KERNEL);
387 p->buf = p->inline_buf;
388 p->buf_len = FS_PATH_INLINE_SIZE;
393 static struct fs_path *fs_path_alloc_reversed(void)
405 static void fs_path_free(struct fs_path *p)
409 if (p->buf != p->inline_buf)
414 static int fs_path_len(struct fs_path *p)
416 return p->end - p->start;
419 static int fs_path_ensure_buf(struct fs_path *p, int len)
427 if (p->buf_len >= len)
430 if (len > PATH_MAX) {
435 path_len = p->end - p->start;
436 old_buf_len = p->buf_len;
439 * First time the inline_buf does not suffice
441 if (p->buf == p->inline_buf) {
442 tmp_buf = kmalloc(len, GFP_KERNEL);
444 memcpy(tmp_buf, p->buf, old_buf_len);
446 tmp_buf = krealloc(p->buf, len, GFP_KERNEL);
452 * The real size of the buffer is bigger, this will let the fast path
453 * happen most of the time
455 p->buf_len = ksize(p->buf);
458 tmp_buf = p->buf + old_buf_len - path_len - 1;
459 p->end = p->buf + p->buf_len - 1;
460 p->start = p->end - path_len;
461 memmove(p->start, tmp_buf, path_len + 1);
464 p->end = p->start + path_len;
469 static int fs_path_prepare_for_add(struct fs_path *p, int name_len,
475 new_len = p->end - p->start + name_len;
476 if (p->start != p->end)
478 ret = fs_path_ensure_buf(p, new_len);
483 if (p->start != p->end)
485 p->start -= name_len;
486 *prepared = p->start;
488 if (p->start != p->end)
499 static int fs_path_add(struct fs_path *p, const char *name, int name_len)
504 ret = fs_path_prepare_for_add(p, name_len, &prepared);
507 memcpy(prepared, name, name_len);
513 static int fs_path_add_path(struct fs_path *p, struct fs_path *p2)
518 ret = fs_path_prepare_for_add(p, p2->end - p2->start, &prepared);
521 memcpy(prepared, p2->start, p2->end - p2->start);
527 static int fs_path_add_from_extent_buffer(struct fs_path *p,
528 struct extent_buffer *eb,
529 unsigned long off, int len)
534 ret = fs_path_prepare_for_add(p, len, &prepared);
538 read_extent_buffer(eb, prepared, off, len);
544 static int fs_path_copy(struct fs_path *p, struct fs_path *from)
546 p->reversed = from->reversed;
549 return fs_path_add_path(p, from);
552 static void fs_path_unreverse(struct fs_path *p)
561 len = p->end - p->start;
563 p->end = p->start + len;
564 memmove(p->start, tmp, len + 1);
568 static struct btrfs_path *alloc_path_for_send(void)
570 struct btrfs_path *path;
572 path = btrfs_alloc_path();
575 path->search_commit_root = 1;
576 path->skip_locking = 1;
577 path->need_commit_sem = 1;
581 static int write_buf(struct file *filp, const void *buf, u32 len, loff_t *off)
587 ret = kernel_write(filp, buf + pos, len - pos, off);
598 static int tlv_put(struct send_ctx *sctx, u16 attr, const void *data, int len)
600 struct btrfs_tlv_header *hdr;
601 int total_len = sizeof(*hdr) + len;
602 int left = sctx->send_max_size - sctx->send_size;
604 if (WARN_ON_ONCE(sctx->put_data))
607 if (unlikely(left < total_len))
610 hdr = (struct btrfs_tlv_header *) (sctx->send_buf + sctx->send_size);
611 put_unaligned_le16(attr, &hdr->tlv_type);
612 put_unaligned_le16(len, &hdr->tlv_len);
613 memcpy(hdr + 1, data, len);
614 sctx->send_size += total_len;
619 #define TLV_PUT_DEFINE_INT(bits) \
620 static int tlv_put_u##bits(struct send_ctx *sctx, \
621 u##bits attr, u##bits value) \
623 __le##bits __tmp = cpu_to_le##bits(value); \
624 return tlv_put(sctx, attr, &__tmp, sizeof(__tmp)); \
627 TLV_PUT_DEFINE_INT(32)
628 TLV_PUT_DEFINE_INT(64)
630 static int tlv_put_string(struct send_ctx *sctx, u16 attr,
631 const char *str, int len)
635 return tlv_put(sctx, attr, str, len);
638 static int tlv_put_uuid(struct send_ctx *sctx, u16 attr,
641 return tlv_put(sctx, attr, uuid, BTRFS_UUID_SIZE);
644 static int tlv_put_btrfs_timespec(struct send_ctx *sctx, u16 attr,
645 struct extent_buffer *eb,
646 struct btrfs_timespec *ts)
648 struct btrfs_timespec bts;
649 read_extent_buffer(eb, &bts, (unsigned long)ts, sizeof(bts));
650 return tlv_put(sctx, attr, &bts, sizeof(bts));
654 #define TLV_PUT(sctx, attrtype, data, attrlen) \
656 ret = tlv_put(sctx, attrtype, data, attrlen); \
658 goto tlv_put_failure; \
661 #define TLV_PUT_INT(sctx, attrtype, bits, value) \
663 ret = tlv_put_u##bits(sctx, attrtype, value); \
665 goto tlv_put_failure; \
668 #define TLV_PUT_U8(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 8, data)
669 #define TLV_PUT_U16(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 16, data)
670 #define TLV_PUT_U32(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 32, data)
671 #define TLV_PUT_U64(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 64, data)
672 #define TLV_PUT_STRING(sctx, attrtype, str, len) \
674 ret = tlv_put_string(sctx, attrtype, str, len); \
676 goto tlv_put_failure; \
678 #define TLV_PUT_PATH(sctx, attrtype, p) \
680 ret = tlv_put_string(sctx, attrtype, p->start, \
681 p->end - p->start); \
683 goto tlv_put_failure; \
685 #define TLV_PUT_UUID(sctx, attrtype, uuid) \
687 ret = tlv_put_uuid(sctx, attrtype, uuid); \
689 goto tlv_put_failure; \
691 #define TLV_PUT_BTRFS_TIMESPEC(sctx, attrtype, eb, ts) \
693 ret = tlv_put_btrfs_timespec(sctx, attrtype, eb, ts); \
695 goto tlv_put_failure; \
698 static int send_header(struct send_ctx *sctx)
700 struct btrfs_stream_header hdr;
702 strcpy(hdr.magic, BTRFS_SEND_STREAM_MAGIC);
703 hdr.version = cpu_to_le32(sctx->proto);
704 return write_buf(sctx->send_filp, &hdr, sizeof(hdr),
709 * For each command/item we want to send to userspace, we call this function.
711 static int begin_cmd(struct send_ctx *sctx, int cmd)
713 struct btrfs_cmd_header *hdr;
715 if (WARN_ON(!sctx->send_buf))
718 BUG_ON(sctx->send_size);
720 sctx->send_size += sizeof(*hdr);
721 hdr = (struct btrfs_cmd_header *)sctx->send_buf;
722 put_unaligned_le16(cmd, &hdr->cmd);
727 static int send_cmd(struct send_ctx *sctx)
730 struct btrfs_cmd_header *hdr;
733 hdr = (struct btrfs_cmd_header *)sctx->send_buf;
734 put_unaligned_le32(sctx->send_size - sizeof(*hdr), &hdr->len);
735 put_unaligned_le32(0, &hdr->crc);
737 crc = btrfs_crc32c(0, (unsigned char *)sctx->send_buf, sctx->send_size);
738 put_unaligned_le32(crc, &hdr->crc);
740 ret = write_buf(sctx->send_filp, sctx->send_buf, sctx->send_size,
744 sctx->put_data = false;
750 * Sends a move instruction to user space
752 static int send_rename(struct send_ctx *sctx,
753 struct fs_path *from, struct fs_path *to)
755 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
758 btrfs_debug(fs_info, "send_rename %s -> %s", from->start, to->start);
760 ret = begin_cmd(sctx, BTRFS_SEND_C_RENAME);
764 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, from);
765 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH_TO, to);
767 ret = send_cmd(sctx);
775 * Sends a link instruction to user space
777 static int send_link(struct send_ctx *sctx,
778 struct fs_path *path, struct fs_path *lnk)
780 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
783 btrfs_debug(fs_info, "send_link %s -> %s", path->start, lnk->start);
785 ret = begin_cmd(sctx, BTRFS_SEND_C_LINK);
789 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
790 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH_LINK, lnk);
792 ret = send_cmd(sctx);
800 * Sends an unlink instruction to user space
802 static int send_unlink(struct send_ctx *sctx, struct fs_path *path)
804 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
807 btrfs_debug(fs_info, "send_unlink %s", path->start);
809 ret = begin_cmd(sctx, BTRFS_SEND_C_UNLINK);
813 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
815 ret = send_cmd(sctx);
823 * Sends a rmdir instruction to user space
825 static int send_rmdir(struct send_ctx *sctx, struct fs_path *path)
827 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
830 btrfs_debug(fs_info, "send_rmdir %s", path->start);
832 ret = begin_cmd(sctx, BTRFS_SEND_C_RMDIR);
836 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
838 ret = send_cmd(sctx);
846 * Helper function to retrieve some fields from an inode item.
848 static int __get_inode_info(struct btrfs_root *root, struct btrfs_path *path,
849 u64 ino, u64 *size, u64 *gen, u64 *mode, u64 *uid,
850 u64 *gid, u64 *rdev, u64 *fileattr)
853 struct btrfs_inode_item *ii;
854 struct btrfs_key key;
857 key.type = BTRFS_INODE_ITEM_KEY;
859 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
866 ii = btrfs_item_ptr(path->nodes[0], path->slots[0],
867 struct btrfs_inode_item);
869 *size = btrfs_inode_size(path->nodes[0], ii);
871 *gen = btrfs_inode_generation(path->nodes[0], ii);
873 *mode = btrfs_inode_mode(path->nodes[0], ii);
875 *uid = btrfs_inode_uid(path->nodes[0], ii);
877 *gid = btrfs_inode_gid(path->nodes[0], ii);
879 *rdev = btrfs_inode_rdev(path->nodes[0], ii);
881 * Transfer the unchanged u64 value of btrfs_inode_item::flags, that's
882 * otherwise logically split to 32/32 parts.
885 *fileattr = btrfs_inode_flags(path->nodes[0], ii);
890 static int get_inode_info(struct btrfs_root *root,
891 u64 ino, u64 *size, u64 *gen,
892 u64 *mode, u64 *uid, u64 *gid,
893 u64 *rdev, u64 *fileattr)
895 struct btrfs_path *path;
898 path = alloc_path_for_send();
901 ret = __get_inode_info(root, path, ino, size, gen, mode, uid, gid,
903 btrfs_free_path(path);
907 typedef int (*iterate_inode_ref_t)(int num, u64 dir, int index,
912 * Helper function to iterate the entries in ONE btrfs_inode_ref or
913 * btrfs_inode_extref.
914 * The iterate callback may return a non zero value to stop iteration. This can
915 * be a negative value for error codes or 1 to simply stop it.
917 * path must point to the INODE_REF or INODE_EXTREF when called.
919 static int iterate_inode_ref(struct btrfs_root *root, struct btrfs_path *path,
920 struct btrfs_key *found_key, int resolve,
921 iterate_inode_ref_t iterate, void *ctx)
923 struct extent_buffer *eb = path->nodes[0];
924 struct btrfs_inode_ref *iref;
925 struct btrfs_inode_extref *extref;
926 struct btrfs_path *tmp_path;
930 int slot = path->slots[0];
937 unsigned long name_off;
938 unsigned long elem_size;
941 p = fs_path_alloc_reversed();
945 tmp_path = alloc_path_for_send();
952 if (found_key->type == BTRFS_INODE_REF_KEY) {
953 ptr = (unsigned long)btrfs_item_ptr(eb, slot,
954 struct btrfs_inode_ref);
955 total = btrfs_item_size(eb, slot);
956 elem_size = sizeof(*iref);
958 ptr = btrfs_item_ptr_offset(eb, slot);
959 total = btrfs_item_size(eb, slot);
960 elem_size = sizeof(*extref);
963 while (cur < total) {
966 if (found_key->type == BTRFS_INODE_REF_KEY) {
967 iref = (struct btrfs_inode_ref *)(ptr + cur);
968 name_len = btrfs_inode_ref_name_len(eb, iref);
969 name_off = (unsigned long)(iref + 1);
970 index = btrfs_inode_ref_index(eb, iref);
971 dir = found_key->offset;
973 extref = (struct btrfs_inode_extref *)(ptr + cur);
974 name_len = btrfs_inode_extref_name_len(eb, extref);
975 name_off = (unsigned long)&extref->name;
976 index = btrfs_inode_extref_index(eb, extref);
977 dir = btrfs_inode_extref_parent(eb, extref);
981 start = btrfs_ref_to_path(root, tmp_path, name_len,
985 ret = PTR_ERR(start);
988 if (start < p->buf) {
989 /* overflow , try again with larger buffer */
990 ret = fs_path_ensure_buf(p,
991 p->buf_len + p->buf - start);
994 start = btrfs_ref_to_path(root, tmp_path,
999 ret = PTR_ERR(start);
1002 BUG_ON(start < p->buf);
1006 ret = fs_path_add_from_extent_buffer(p, eb, name_off,
1012 cur += elem_size + name_len;
1013 ret = iterate(num, dir, index, p, ctx);
1020 btrfs_free_path(tmp_path);
1025 typedef int (*iterate_dir_item_t)(int num, struct btrfs_key *di_key,
1026 const char *name, int name_len,
1027 const char *data, int data_len,
1031 * Helper function to iterate the entries in ONE btrfs_dir_item.
1032 * The iterate callback may return a non zero value to stop iteration. This can
1033 * be a negative value for error codes or 1 to simply stop it.
1035 * path must point to the dir item when called.
1037 static int iterate_dir_item(struct btrfs_root *root, struct btrfs_path *path,
1038 iterate_dir_item_t iterate, void *ctx)
1041 struct extent_buffer *eb;
1042 struct btrfs_dir_item *di;
1043 struct btrfs_key di_key;
1055 * Start with a small buffer (1 page). If later we end up needing more
1056 * space, which can happen for xattrs on a fs with a leaf size greater
1057 * then the page size, attempt to increase the buffer. Typically xattr
1061 buf = kmalloc(buf_len, GFP_KERNEL);
1067 eb = path->nodes[0];
1068 slot = path->slots[0];
1069 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
1072 total = btrfs_item_size(eb, slot);
1075 while (cur < total) {
1076 name_len = btrfs_dir_name_len(eb, di);
1077 data_len = btrfs_dir_data_len(eb, di);
1078 btrfs_dir_item_key_to_cpu(eb, di, &di_key);
1080 if (btrfs_dir_type(eb, di) == BTRFS_FT_XATTR) {
1081 if (name_len > XATTR_NAME_MAX) {
1082 ret = -ENAMETOOLONG;
1085 if (name_len + data_len >
1086 BTRFS_MAX_XATTR_SIZE(root->fs_info)) {
1094 if (name_len + data_len > PATH_MAX) {
1095 ret = -ENAMETOOLONG;
1100 if (name_len + data_len > buf_len) {
1101 buf_len = name_len + data_len;
1102 if (is_vmalloc_addr(buf)) {
1106 char *tmp = krealloc(buf, buf_len,
1107 GFP_KERNEL | __GFP_NOWARN);
1114 buf = kvmalloc(buf_len, GFP_KERNEL);
1122 read_extent_buffer(eb, buf, (unsigned long)(di + 1),
1123 name_len + data_len);
1125 len = sizeof(*di) + name_len + data_len;
1126 di = (struct btrfs_dir_item *)((char *)di + len);
1129 ret = iterate(num, &di_key, buf, name_len, buf + name_len,
1146 static int __copy_first_ref(int num, u64 dir, int index,
1147 struct fs_path *p, void *ctx)
1150 struct fs_path *pt = ctx;
1152 ret = fs_path_copy(pt, p);
1156 /* we want the first only */
1161 * Retrieve the first path of an inode. If an inode has more then one
1162 * ref/hardlink, this is ignored.
1164 static int get_inode_path(struct btrfs_root *root,
1165 u64 ino, struct fs_path *path)
1168 struct btrfs_key key, found_key;
1169 struct btrfs_path *p;
1171 p = alloc_path_for_send();
1175 fs_path_reset(path);
1178 key.type = BTRFS_INODE_REF_KEY;
1181 ret = btrfs_search_slot_for_read(root, &key, p, 1, 0);
1188 btrfs_item_key_to_cpu(p->nodes[0], &found_key, p->slots[0]);
1189 if (found_key.objectid != ino ||
1190 (found_key.type != BTRFS_INODE_REF_KEY &&
1191 found_key.type != BTRFS_INODE_EXTREF_KEY)) {
1196 ret = iterate_inode_ref(root, p, &found_key, 1,
1197 __copy_first_ref, path);
1207 struct backref_ctx {
1208 struct send_ctx *sctx;
1210 /* number of total found references */
1214 * used for clones found in send_root. clones found behind cur_objectid
1215 * and cur_offset are not considered as allowed clones.
1220 /* may be truncated in case it's the last extent in a file */
1223 /* Just to check for bugs in backref resolving */
1227 static int __clone_root_cmp_bsearch(const void *key, const void *elt)
1229 u64 root = (u64)(uintptr_t)key;
1230 const struct clone_root *cr = elt;
1232 if (root < cr->root->root_key.objectid)
1234 if (root > cr->root->root_key.objectid)
1239 static int __clone_root_cmp_sort(const void *e1, const void *e2)
1241 const struct clone_root *cr1 = e1;
1242 const struct clone_root *cr2 = e2;
1244 if (cr1->root->root_key.objectid < cr2->root->root_key.objectid)
1246 if (cr1->root->root_key.objectid > cr2->root->root_key.objectid)
1252 * Called for every backref that is found for the current extent.
1253 * Results are collected in sctx->clone_roots->ino/offset/found_refs
1255 static int __iterate_backrefs(u64 ino, u64 offset, u64 root, void *ctx_)
1257 struct backref_ctx *bctx = ctx_;
1258 struct clone_root *found;
1260 /* First check if the root is in the list of accepted clone sources */
1261 found = bsearch((void *)(uintptr_t)root, bctx->sctx->clone_roots,
1262 bctx->sctx->clone_roots_cnt,
1263 sizeof(struct clone_root),
1264 __clone_root_cmp_bsearch);
1268 if (found->root == bctx->sctx->send_root &&
1269 ino == bctx->cur_objectid &&
1270 offset == bctx->cur_offset) {
1271 bctx->found_itself = 1;
1275 * Make sure we don't consider clones from send_root that are
1276 * behind the current inode/offset.
1278 if (found->root == bctx->sctx->send_root) {
1280 * If the source inode was not yet processed we can't issue a
1281 * clone operation, as the source extent does not exist yet at
1282 * the destination of the stream.
1284 if (ino > bctx->cur_objectid)
1287 * We clone from the inode currently being sent as long as the
1288 * source extent is already processed, otherwise we could try
1289 * to clone from an extent that does not exist yet at the
1290 * destination of the stream.
1292 if (ino == bctx->cur_objectid &&
1293 offset + bctx->extent_len >
1294 bctx->sctx->cur_inode_next_write_offset)
1299 found->found_refs++;
1300 if (ino < found->ino) {
1302 found->offset = offset;
1303 } else if (found->ino == ino) {
1305 * same extent found more then once in the same file.
1307 if (found->offset > offset + bctx->extent_len)
1308 found->offset = offset;
1315 * Given an inode, offset and extent item, it finds a good clone for a clone
1316 * instruction. Returns -ENOENT when none could be found. The function makes
1317 * sure that the returned clone is usable at the point where sending is at the
1318 * moment. This means, that no clones are accepted which lie behind the current
1321 * path must point to the extent item when called.
1323 static int find_extent_clone(struct send_ctx *sctx,
1324 struct btrfs_path *path,
1325 u64 ino, u64 data_offset,
1327 struct clone_root **found)
1329 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
1335 u64 extent_item_pos;
1337 struct btrfs_file_extent_item *fi;
1338 struct extent_buffer *eb = path->nodes[0];
1339 struct backref_ctx backref_ctx = {0};
1340 struct clone_root *cur_clone_root;
1341 struct btrfs_key found_key;
1342 struct btrfs_path *tmp_path;
1343 struct btrfs_extent_item *ei;
1347 tmp_path = alloc_path_for_send();
1351 /* We only use this path under the commit sem */
1352 tmp_path->need_commit_sem = 0;
1354 if (data_offset >= ino_size) {
1356 * There may be extents that lie behind the file's size.
1357 * I at least had this in combination with snapshotting while
1358 * writing large files.
1364 fi = btrfs_item_ptr(eb, path->slots[0],
1365 struct btrfs_file_extent_item);
1366 extent_type = btrfs_file_extent_type(eb, fi);
1367 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1371 compressed = btrfs_file_extent_compression(eb, fi);
1373 num_bytes = btrfs_file_extent_num_bytes(eb, fi);
1374 disk_byte = btrfs_file_extent_disk_bytenr(eb, fi);
1375 if (disk_byte == 0) {
1379 logical = disk_byte + btrfs_file_extent_offset(eb, fi);
1381 down_read(&fs_info->commit_root_sem);
1382 ret = extent_from_logical(fs_info, disk_byte, tmp_path,
1383 &found_key, &flags);
1384 up_read(&fs_info->commit_root_sem);
1388 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
1393 ei = btrfs_item_ptr(tmp_path->nodes[0], tmp_path->slots[0],
1394 struct btrfs_extent_item);
1396 * Backreference walking (iterate_extent_inodes() below) is currently
1397 * too expensive when an extent has a large number of references, both
1398 * in time spent and used memory. So for now just fallback to write
1399 * operations instead of clone operations when an extent has more than
1400 * a certain amount of references.
1402 if (btrfs_extent_refs(tmp_path->nodes[0], ei) > SEND_MAX_EXTENT_REFS) {
1406 btrfs_release_path(tmp_path);
1409 * Setup the clone roots.
1411 for (i = 0; i < sctx->clone_roots_cnt; i++) {
1412 cur_clone_root = sctx->clone_roots + i;
1413 cur_clone_root->ino = (u64)-1;
1414 cur_clone_root->offset = 0;
1415 cur_clone_root->found_refs = 0;
1418 backref_ctx.sctx = sctx;
1419 backref_ctx.found = 0;
1420 backref_ctx.cur_objectid = ino;
1421 backref_ctx.cur_offset = data_offset;
1422 backref_ctx.found_itself = 0;
1423 backref_ctx.extent_len = num_bytes;
1426 * The last extent of a file may be too large due to page alignment.
1427 * We need to adjust extent_len in this case so that the checks in
1428 * __iterate_backrefs work.
1430 if (data_offset + num_bytes >= ino_size)
1431 backref_ctx.extent_len = ino_size - data_offset;
1434 * Now collect all backrefs.
1436 if (compressed == BTRFS_COMPRESS_NONE)
1437 extent_item_pos = logical - found_key.objectid;
1439 extent_item_pos = 0;
1440 ret = iterate_extent_inodes(fs_info, found_key.objectid,
1441 extent_item_pos, 1, __iterate_backrefs,
1442 &backref_ctx, false);
1447 down_read(&fs_info->commit_root_sem);
1448 if (fs_info->last_reloc_trans > sctx->last_reloc_trans) {
1450 * A transaction commit for a transaction in which block group
1451 * relocation was done just happened.
1452 * The disk_bytenr of the file extent item we processed is
1453 * possibly stale, referring to the extent's location before
1454 * relocation. So act as if we haven't found any clone sources
1455 * and fallback to write commands, which will read the correct
1456 * data from the new extent location. Otherwise we will fail
1457 * below because we haven't found our own back reference or we
1458 * could be getting incorrect sources in case the old extent
1459 * was already reallocated after the relocation.
1461 up_read(&fs_info->commit_root_sem);
1465 up_read(&fs_info->commit_root_sem);
1467 if (!backref_ctx.found_itself) {
1468 /* found a bug in backref code? */
1471 "did not find backref in send_root. inode=%llu, offset=%llu, disk_byte=%llu found extent=%llu",
1472 ino, data_offset, disk_byte, found_key.objectid);
1476 btrfs_debug(fs_info,
1477 "find_extent_clone: data_offset=%llu, ino=%llu, num_bytes=%llu, logical=%llu",
1478 data_offset, ino, num_bytes, logical);
1480 if (!backref_ctx.found)
1481 btrfs_debug(fs_info, "no clones found");
1483 cur_clone_root = NULL;
1484 for (i = 0; i < sctx->clone_roots_cnt; i++) {
1485 if (sctx->clone_roots[i].found_refs) {
1486 if (!cur_clone_root)
1487 cur_clone_root = sctx->clone_roots + i;
1488 else if (sctx->clone_roots[i].root == sctx->send_root)
1489 /* prefer clones from send_root over others */
1490 cur_clone_root = sctx->clone_roots + i;
1495 if (cur_clone_root) {
1496 *found = cur_clone_root;
1503 btrfs_free_path(tmp_path);
1507 static int read_symlink(struct btrfs_root *root,
1509 struct fs_path *dest)
1512 struct btrfs_path *path;
1513 struct btrfs_key key;
1514 struct btrfs_file_extent_item *ei;
1520 path = alloc_path_for_send();
1525 key.type = BTRFS_EXTENT_DATA_KEY;
1527 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1532 * An empty symlink inode. Can happen in rare error paths when
1533 * creating a symlink (transaction committed before the inode
1534 * eviction handler removed the symlink inode items and a crash
1535 * happened in between or the subvol was snapshoted in between).
1536 * Print an informative message to dmesg/syslog so that the user
1537 * can delete the symlink.
1539 btrfs_err(root->fs_info,
1540 "Found empty symlink inode %llu at root %llu",
1541 ino, root->root_key.objectid);
1546 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
1547 struct btrfs_file_extent_item);
1548 type = btrfs_file_extent_type(path->nodes[0], ei);
1549 compression = btrfs_file_extent_compression(path->nodes[0], ei);
1550 BUG_ON(type != BTRFS_FILE_EXTENT_INLINE);
1551 BUG_ON(compression);
1553 off = btrfs_file_extent_inline_start(ei);
1554 len = btrfs_file_extent_ram_bytes(path->nodes[0], ei);
1556 ret = fs_path_add_from_extent_buffer(dest, path->nodes[0], off, len);
1559 btrfs_free_path(path);
1564 * Helper function to generate a file name that is unique in the root of
1565 * send_root and parent_root. This is used to generate names for orphan inodes.
1567 static int gen_unique_name(struct send_ctx *sctx,
1569 struct fs_path *dest)
1572 struct btrfs_path *path;
1573 struct btrfs_dir_item *di;
1578 path = alloc_path_for_send();
1583 len = snprintf(tmp, sizeof(tmp), "o%llu-%llu-%llu",
1585 ASSERT(len < sizeof(tmp));
1587 di = btrfs_lookup_dir_item(NULL, sctx->send_root,
1588 path, BTRFS_FIRST_FREE_OBJECTID,
1589 tmp, strlen(tmp), 0);
1590 btrfs_release_path(path);
1596 /* not unique, try again */
1601 if (!sctx->parent_root) {
1607 di = btrfs_lookup_dir_item(NULL, sctx->parent_root,
1608 path, BTRFS_FIRST_FREE_OBJECTID,
1609 tmp, strlen(tmp), 0);
1610 btrfs_release_path(path);
1616 /* not unique, try again */
1624 ret = fs_path_add(dest, tmp, strlen(tmp));
1627 btrfs_free_path(path);
1632 inode_state_no_change,
1633 inode_state_will_create,
1634 inode_state_did_create,
1635 inode_state_will_delete,
1636 inode_state_did_delete,
1639 static int get_cur_inode_state(struct send_ctx *sctx, u64 ino, u64 gen)
1647 ret = get_inode_info(sctx->send_root, ino, NULL, &left_gen, NULL, NULL,
1649 if (ret < 0 && ret != -ENOENT)
1653 if (!sctx->parent_root) {
1654 right_ret = -ENOENT;
1656 ret = get_inode_info(sctx->parent_root, ino, NULL, &right_gen,
1657 NULL, NULL, NULL, NULL, NULL);
1658 if (ret < 0 && ret != -ENOENT)
1663 if (!left_ret && !right_ret) {
1664 if (left_gen == gen && right_gen == gen) {
1665 ret = inode_state_no_change;
1666 } else if (left_gen == gen) {
1667 if (ino < sctx->send_progress)
1668 ret = inode_state_did_create;
1670 ret = inode_state_will_create;
1671 } else if (right_gen == gen) {
1672 if (ino < sctx->send_progress)
1673 ret = inode_state_did_delete;
1675 ret = inode_state_will_delete;
1679 } else if (!left_ret) {
1680 if (left_gen == gen) {
1681 if (ino < sctx->send_progress)
1682 ret = inode_state_did_create;
1684 ret = inode_state_will_create;
1688 } else if (!right_ret) {
1689 if (right_gen == gen) {
1690 if (ino < sctx->send_progress)
1691 ret = inode_state_did_delete;
1693 ret = inode_state_will_delete;
1705 static int is_inode_existent(struct send_ctx *sctx, u64 ino, u64 gen)
1709 if (ino == BTRFS_FIRST_FREE_OBJECTID)
1712 ret = get_cur_inode_state(sctx, ino, gen);
1716 if (ret == inode_state_no_change ||
1717 ret == inode_state_did_create ||
1718 ret == inode_state_will_delete)
1728 * Helper function to lookup a dir item in a dir.
1730 static int lookup_dir_item_inode(struct btrfs_root *root,
1731 u64 dir, const char *name, int name_len,
1735 struct btrfs_dir_item *di;
1736 struct btrfs_key key;
1737 struct btrfs_path *path;
1739 path = alloc_path_for_send();
1743 di = btrfs_lookup_dir_item(NULL, root, path,
1744 dir, name, name_len, 0);
1745 if (IS_ERR_OR_NULL(di)) {
1746 ret = di ? PTR_ERR(di) : -ENOENT;
1749 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
1750 if (key.type == BTRFS_ROOT_ITEM_KEY) {
1754 *found_inode = key.objectid;
1757 btrfs_free_path(path);
1762 * Looks up the first btrfs_inode_ref of a given ino. It returns the parent dir,
1763 * generation of the parent dir and the name of the dir entry.
1765 static int get_first_ref(struct btrfs_root *root, u64 ino,
1766 u64 *dir, u64 *dir_gen, struct fs_path *name)
1769 struct btrfs_key key;
1770 struct btrfs_key found_key;
1771 struct btrfs_path *path;
1775 path = alloc_path_for_send();
1780 key.type = BTRFS_INODE_REF_KEY;
1783 ret = btrfs_search_slot_for_read(root, &key, path, 1, 0);
1787 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1789 if (ret || found_key.objectid != ino ||
1790 (found_key.type != BTRFS_INODE_REF_KEY &&
1791 found_key.type != BTRFS_INODE_EXTREF_KEY)) {
1796 if (found_key.type == BTRFS_INODE_REF_KEY) {
1797 struct btrfs_inode_ref *iref;
1798 iref = btrfs_item_ptr(path->nodes[0], path->slots[0],
1799 struct btrfs_inode_ref);
1800 len = btrfs_inode_ref_name_len(path->nodes[0], iref);
1801 ret = fs_path_add_from_extent_buffer(name, path->nodes[0],
1802 (unsigned long)(iref + 1),
1804 parent_dir = found_key.offset;
1806 struct btrfs_inode_extref *extref;
1807 extref = btrfs_item_ptr(path->nodes[0], path->slots[0],
1808 struct btrfs_inode_extref);
1809 len = btrfs_inode_extref_name_len(path->nodes[0], extref);
1810 ret = fs_path_add_from_extent_buffer(name, path->nodes[0],
1811 (unsigned long)&extref->name, len);
1812 parent_dir = btrfs_inode_extref_parent(path->nodes[0], extref);
1816 btrfs_release_path(path);
1819 ret = get_inode_info(root, parent_dir, NULL, dir_gen, NULL,
1820 NULL, NULL, NULL, NULL);
1828 btrfs_free_path(path);
1832 static int is_first_ref(struct btrfs_root *root,
1834 const char *name, int name_len)
1837 struct fs_path *tmp_name;
1840 tmp_name = fs_path_alloc();
1844 ret = get_first_ref(root, ino, &tmp_dir, NULL, tmp_name);
1848 if (dir != tmp_dir || name_len != fs_path_len(tmp_name)) {
1853 ret = !memcmp(tmp_name->start, name, name_len);
1856 fs_path_free(tmp_name);
1861 * Used by process_recorded_refs to determine if a new ref would overwrite an
1862 * already existing ref. In case it detects an overwrite, it returns the
1863 * inode/gen in who_ino/who_gen.
1864 * When an overwrite is detected, process_recorded_refs does proper orphanizing
1865 * to make sure later references to the overwritten inode are possible.
1866 * Orphanizing is however only required for the first ref of an inode.
1867 * process_recorded_refs does an additional is_first_ref check to see if
1868 * orphanizing is really required.
1870 static int will_overwrite_ref(struct send_ctx *sctx, u64 dir, u64 dir_gen,
1871 const char *name, int name_len,
1872 u64 *who_ino, u64 *who_gen, u64 *who_mode)
1876 u64 other_inode = 0;
1878 if (!sctx->parent_root)
1881 ret = is_inode_existent(sctx, dir, dir_gen);
1886 * If we have a parent root we need to verify that the parent dir was
1887 * not deleted and then re-created, if it was then we have no overwrite
1888 * and we can just unlink this entry.
1890 if (sctx->parent_root && dir != BTRFS_FIRST_FREE_OBJECTID) {
1891 ret = get_inode_info(sctx->parent_root, dir, NULL, &gen, NULL,
1892 NULL, NULL, NULL, NULL);
1893 if (ret < 0 && ret != -ENOENT)
1903 ret = lookup_dir_item_inode(sctx->parent_root, dir, name, name_len,
1905 if (ret < 0 && ret != -ENOENT)
1913 * Check if the overwritten ref was already processed. If yes, the ref
1914 * was already unlinked/moved, so we can safely assume that we will not
1915 * overwrite anything at this point in time.
1917 if (other_inode > sctx->send_progress ||
1918 is_waiting_for_move(sctx, other_inode)) {
1919 ret = get_inode_info(sctx->parent_root, other_inode, NULL,
1920 who_gen, who_mode, NULL, NULL, NULL, NULL);
1925 *who_ino = other_inode;
1935 * Checks if the ref was overwritten by an already processed inode. This is
1936 * used by __get_cur_name_and_parent to find out if the ref was orphanized and
1937 * thus the orphan name needs be used.
1938 * process_recorded_refs also uses it to avoid unlinking of refs that were
1941 static int did_overwrite_ref(struct send_ctx *sctx,
1942 u64 dir, u64 dir_gen,
1943 u64 ino, u64 ino_gen,
1944 const char *name, int name_len)
1950 if (!sctx->parent_root)
1953 ret = is_inode_existent(sctx, dir, dir_gen);
1957 if (dir != BTRFS_FIRST_FREE_OBJECTID) {
1958 ret = get_inode_info(sctx->send_root, dir, NULL, &gen, NULL,
1959 NULL, NULL, NULL, NULL);
1960 if (ret < 0 && ret != -ENOENT)
1970 /* check if the ref was overwritten by another ref */
1971 ret = lookup_dir_item_inode(sctx->send_root, dir, name, name_len,
1973 if (ret < 0 && ret != -ENOENT)
1976 /* was never and will never be overwritten */
1981 ret = get_inode_info(sctx->send_root, ow_inode, NULL, &gen, NULL, NULL,
1986 if (ow_inode == ino && gen == ino_gen) {
1992 * We know that it is or will be overwritten. Check this now.
1993 * The current inode being processed might have been the one that caused
1994 * inode 'ino' to be orphanized, therefore check if ow_inode matches
1995 * the current inode being processed.
1997 if ((ow_inode < sctx->send_progress) ||
1998 (ino != sctx->cur_ino && ow_inode == sctx->cur_ino &&
1999 gen == sctx->cur_inode_gen))
2009 * Same as did_overwrite_ref, but also checks if it is the first ref of an inode
2010 * that got overwritten. This is used by process_recorded_refs to determine
2011 * if it has to use the path as returned by get_cur_path or the orphan name.
2013 static int did_overwrite_first_ref(struct send_ctx *sctx, u64 ino, u64 gen)
2016 struct fs_path *name = NULL;
2020 if (!sctx->parent_root)
2023 name = fs_path_alloc();
2027 ret = get_first_ref(sctx->parent_root, ino, &dir, &dir_gen, name);
2031 ret = did_overwrite_ref(sctx, dir, dir_gen, ino, gen,
2032 name->start, fs_path_len(name));
2040 * Insert a name cache entry. On 32bit kernels the radix tree index is 32bit,
2041 * so we need to do some special handling in case we have clashes. This function
2042 * takes care of this with the help of name_cache_entry::radix_list.
2043 * In case of error, nce is kfreed.
2045 static int name_cache_insert(struct send_ctx *sctx,
2046 struct name_cache_entry *nce)
2049 struct list_head *nce_head;
2051 nce_head = radix_tree_lookup(&sctx->name_cache,
2052 (unsigned long)nce->ino);
2054 nce_head = kmalloc(sizeof(*nce_head), GFP_KERNEL);
2059 INIT_LIST_HEAD(nce_head);
2061 ret = radix_tree_insert(&sctx->name_cache, nce->ino, nce_head);
2068 list_add_tail(&nce->radix_list, nce_head);
2069 list_add_tail(&nce->list, &sctx->name_cache_list);
2070 sctx->name_cache_size++;
2075 static void name_cache_delete(struct send_ctx *sctx,
2076 struct name_cache_entry *nce)
2078 struct list_head *nce_head;
2080 nce_head = radix_tree_lookup(&sctx->name_cache,
2081 (unsigned long)nce->ino);
2083 btrfs_err(sctx->send_root->fs_info,
2084 "name_cache_delete lookup failed ino %llu cache size %d, leaking memory",
2085 nce->ino, sctx->name_cache_size);
2088 list_del(&nce->radix_list);
2089 list_del(&nce->list);
2090 sctx->name_cache_size--;
2093 * We may not get to the final release of nce_head if the lookup fails
2095 if (nce_head && list_empty(nce_head)) {
2096 radix_tree_delete(&sctx->name_cache, (unsigned long)nce->ino);
2101 static struct name_cache_entry *name_cache_search(struct send_ctx *sctx,
2104 struct list_head *nce_head;
2105 struct name_cache_entry *cur;
2107 nce_head = radix_tree_lookup(&sctx->name_cache, (unsigned long)ino);
2111 list_for_each_entry(cur, nce_head, radix_list) {
2112 if (cur->ino == ino && cur->gen == gen)
2119 * Remove some entries from the beginning of name_cache_list.
2121 static void name_cache_clean_unused(struct send_ctx *sctx)
2123 struct name_cache_entry *nce;
2125 if (sctx->name_cache_size < SEND_CTX_NAME_CACHE_CLEAN_SIZE)
2128 while (sctx->name_cache_size > SEND_CTX_MAX_NAME_CACHE_SIZE) {
2129 nce = list_entry(sctx->name_cache_list.next,
2130 struct name_cache_entry, list);
2131 name_cache_delete(sctx, nce);
2136 static void name_cache_free(struct send_ctx *sctx)
2138 struct name_cache_entry *nce;
2140 while (!list_empty(&sctx->name_cache_list)) {
2141 nce = list_entry(sctx->name_cache_list.next,
2142 struct name_cache_entry, list);
2143 name_cache_delete(sctx, nce);
2149 * Used by get_cur_path for each ref up to the root.
2150 * Returns 0 if it succeeded.
2151 * Returns 1 if the inode is not existent or got overwritten. In that case, the
2152 * name is an orphan name. This instructs get_cur_path to stop iterating. If 1
2153 * is returned, parent_ino/parent_gen are not guaranteed to be valid.
2154 * Returns <0 in case of error.
2156 static int __get_cur_name_and_parent(struct send_ctx *sctx,
2160 struct fs_path *dest)
2164 struct name_cache_entry *nce = NULL;
2167 * First check if we already did a call to this function with the same
2168 * ino/gen. If yes, check if the cache entry is still up-to-date. If yes
2169 * return the cached result.
2171 nce = name_cache_search(sctx, ino, gen);
2173 if (ino < sctx->send_progress && nce->need_later_update) {
2174 name_cache_delete(sctx, nce);
2179 * Removes the entry from the list and adds it back to
2180 * the end. This marks the entry as recently used so
2181 * that name_cache_clean_unused does not remove it.
2183 list_move_tail(&nce->list, &sctx->name_cache_list);
2185 *parent_ino = nce->parent_ino;
2186 *parent_gen = nce->parent_gen;
2187 ret = fs_path_add(dest, nce->name, nce->name_len);
2196 * If the inode is not existent yet, add the orphan name and return 1.
2197 * This should only happen for the parent dir that we determine in
2198 * record_new_ref_if_needed().
2200 ret = is_inode_existent(sctx, ino, gen);
2205 ret = gen_unique_name(sctx, ino, gen, dest);
2213 * Depending on whether the inode was already processed or not, use
2214 * send_root or parent_root for ref lookup.
2216 if (ino < sctx->send_progress)
2217 ret = get_first_ref(sctx->send_root, ino,
2218 parent_ino, parent_gen, dest);
2220 ret = get_first_ref(sctx->parent_root, ino,
2221 parent_ino, parent_gen, dest);
2226 * Check if the ref was overwritten by an inode's ref that was processed
2227 * earlier. If yes, treat as orphan and return 1.
2229 ret = did_overwrite_ref(sctx, *parent_ino, *parent_gen, ino, gen,
2230 dest->start, dest->end - dest->start);
2234 fs_path_reset(dest);
2235 ret = gen_unique_name(sctx, ino, gen, dest);
2243 * Store the result of the lookup in the name cache.
2245 nce = kmalloc(sizeof(*nce) + fs_path_len(dest) + 1, GFP_KERNEL);
2253 nce->parent_ino = *parent_ino;
2254 nce->parent_gen = *parent_gen;
2255 nce->name_len = fs_path_len(dest);
2257 strcpy(nce->name, dest->start);
2259 if (ino < sctx->send_progress)
2260 nce->need_later_update = 0;
2262 nce->need_later_update = 1;
2264 nce_ret = name_cache_insert(sctx, nce);
2267 name_cache_clean_unused(sctx);
2274 * Magic happens here. This function returns the first ref to an inode as it
2275 * would look like while receiving the stream at this point in time.
2276 * We walk the path up to the root. For every inode in between, we check if it
2277 * was already processed/sent. If yes, we continue with the parent as found
2278 * in send_root. If not, we continue with the parent as found in parent_root.
2279 * If we encounter an inode that was deleted at this point in time, we use the
2280 * inodes "orphan" name instead of the real name and stop. Same with new inodes
2281 * that were not created yet and overwritten inodes/refs.
2283 * When do we have orphan inodes:
2284 * 1. When an inode is freshly created and thus no valid refs are available yet
2285 * 2. When a directory lost all it's refs (deleted) but still has dir items
2286 * inside which were not processed yet (pending for move/delete). If anyone
2287 * tried to get the path to the dir items, it would get a path inside that
2289 * 3. When an inode is moved around or gets new links, it may overwrite the ref
2290 * of an unprocessed inode. If in that case the first ref would be
2291 * overwritten, the overwritten inode gets "orphanized". Later when we
2292 * process this overwritten inode, it is restored at a new place by moving
2295 * sctx->send_progress tells this function at which point in time receiving
2298 static int get_cur_path(struct send_ctx *sctx, u64 ino, u64 gen,
2299 struct fs_path *dest)
2302 struct fs_path *name = NULL;
2303 u64 parent_inode = 0;
2307 name = fs_path_alloc();
2314 fs_path_reset(dest);
2316 while (!stop && ino != BTRFS_FIRST_FREE_OBJECTID) {
2317 struct waiting_dir_move *wdm;
2319 fs_path_reset(name);
2321 if (is_waiting_for_rm(sctx, ino, gen)) {
2322 ret = gen_unique_name(sctx, ino, gen, name);
2325 ret = fs_path_add_path(dest, name);
2329 wdm = get_waiting_dir_move(sctx, ino);
2330 if (wdm && wdm->orphanized) {
2331 ret = gen_unique_name(sctx, ino, gen, name);
2334 ret = get_first_ref(sctx->parent_root, ino,
2335 &parent_inode, &parent_gen, name);
2337 ret = __get_cur_name_and_parent(sctx, ino, gen,
2347 ret = fs_path_add_path(dest, name);
2358 fs_path_unreverse(dest);
2363 * Sends a BTRFS_SEND_C_SUBVOL command/item to userspace
2365 static int send_subvol_begin(struct send_ctx *sctx)
2368 struct btrfs_root *send_root = sctx->send_root;
2369 struct btrfs_root *parent_root = sctx->parent_root;
2370 struct btrfs_path *path;
2371 struct btrfs_key key;
2372 struct btrfs_root_ref *ref;
2373 struct extent_buffer *leaf;
2377 path = btrfs_alloc_path();
2381 name = kmalloc(BTRFS_PATH_NAME_MAX, GFP_KERNEL);
2383 btrfs_free_path(path);
2387 key.objectid = send_root->root_key.objectid;
2388 key.type = BTRFS_ROOT_BACKREF_KEY;
2391 ret = btrfs_search_slot_for_read(send_root->fs_info->tree_root,
2400 leaf = path->nodes[0];
2401 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2402 if (key.type != BTRFS_ROOT_BACKREF_KEY ||
2403 key.objectid != send_root->root_key.objectid) {
2407 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
2408 namelen = btrfs_root_ref_name_len(leaf, ref);
2409 read_extent_buffer(leaf, name, (unsigned long)(ref + 1), namelen);
2410 btrfs_release_path(path);
2413 ret = begin_cmd(sctx, BTRFS_SEND_C_SNAPSHOT);
2417 ret = begin_cmd(sctx, BTRFS_SEND_C_SUBVOL);
2422 TLV_PUT_STRING(sctx, BTRFS_SEND_A_PATH, name, namelen);
2424 if (!btrfs_is_empty_uuid(sctx->send_root->root_item.received_uuid))
2425 TLV_PUT_UUID(sctx, BTRFS_SEND_A_UUID,
2426 sctx->send_root->root_item.received_uuid);
2428 TLV_PUT_UUID(sctx, BTRFS_SEND_A_UUID,
2429 sctx->send_root->root_item.uuid);
2431 TLV_PUT_U64(sctx, BTRFS_SEND_A_CTRANSID,
2432 btrfs_root_ctransid(&sctx->send_root->root_item));
2434 if (!btrfs_is_empty_uuid(parent_root->root_item.received_uuid))
2435 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
2436 parent_root->root_item.received_uuid);
2438 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
2439 parent_root->root_item.uuid);
2440 TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_CTRANSID,
2441 btrfs_root_ctransid(&sctx->parent_root->root_item));
2444 ret = send_cmd(sctx);
2448 btrfs_free_path(path);
2453 static int send_truncate(struct send_ctx *sctx, u64 ino, u64 gen, u64 size)
2455 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2459 btrfs_debug(fs_info, "send_truncate %llu size=%llu", ino, size);
2461 p = fs_path_alloc();
2465 ret = begin_cmd(sctx, BTRFS_SEND_C_TRUNCATE);
2469 ret = get_cur_path(sctx, ino, gen, p);
2472 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2473 TLV_PUT_U64(sctx, BTRFS_SEND_A_SIZE, size);
2475 ret = send_cmd(sctx);
2483 static int send_chmod(struct send_ctx *sctx, u64 ino, u64 gen, u64 mode)
2485 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2489 btrfs_debug(fs_info, "send_chmod %llu mode=%llu", ino, mode);
2491 p = fs_path_alloc();
2495 ret = begin_cmd(sctx, BTRFS_SEND_C_CHMOD);
2499 ret = get_cur_path(sctx, ino, gen, p);
2502 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2503 TLV_PUT_U64(sctx, BTRFS_SEND_A_MODE, mode & 07777);
2505 ret = send_cmd(sctx);
2513 static int send_fileattr(struct send_ctx *sctx, u64 ino, u64 gen, u64 fileattr)
2515 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2519 if (sctx->proto < 2)
2522 btrfs_debug(fs_info, "send_fileattr %llu fileattr=%llu", ino, fileattr);
2524 p = fs_path_alloc();
2528 ret = begin_cmd(sctx, BTRFS_SEND_C_FILEATTR);
2532 ret = get_cur_path(sctx, ino, gen, p);
2535 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2536 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILEATTR, fileattr);
2538 ret = send_cmd(sctx);
2546 static int send_chown(struct send_ctx *sctx, u64 ino, u64 gen, u64 uid, u64 gid)
2548 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2552 btrfs_debug(fs_info, "send_chown %llu uid=%llu, gid=%llu",
2555 p = fs_path_alloc();
2559 ret = begin_cmd(sctx, BTRFS_SEND_C_CHOWN);
2563 ret = get_cur_path(sctx, ino, gen, p);
2566 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2567 TLV_PUT_U64(sctx, BTRFS_SEND_A_UID, uid);
2568 TLV_PUT_U64(sctx, BTRFS_SEND_A_GID, gid);
2570 ret = send_cmd(sctx);
2578 static int send_utimes(struct send_ctx *sctx, u64 ino, u64 gen)
2580 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2582 struct fs_path *p = NULL;
2583 struct btrfs_inode_item *ii;
2584 struct btrfs_path *path = NULL;
2585 struct extent_buffer *eb;
2586 struct btrfs_key key;
2589 btrfs_debug(fs_info, "send_utimes %llu", ino);
2591 p = fs_path_alloc();
2595 path = alloc_path_for_send();
2602 key.type = BTRFS_INODE_ITEM_KEY;
2604 ret = btrfs_search_slot(NULL, sctx->send_root, &key, path, 0, 0);
2610 eb = path->nodes[0];
2611 slot = path->slots[0];
2612 ii = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
2614 ret = begin_cmd(sctx, BTRFS_SEND_C_UTIMES);
2618 ret = get_cur_path(sctx, ino, gen, p);
2621 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2622 TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_ATIME, eb, &ii->atime);
2623 TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_MTIME, eb, &ii->mtime);
2624 TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_CTIME, eb, &ii->ctime);
2625 if (sctx->proto >= 2)
2626 TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_OTIME, eb, &ii->otime);
2628 ret = send_cmd(sctx);
2633 btrfs_free_path(path);
2638 * Sends a BTRFS_SEND_C_MKXXX or SYMLINK command to user space. We don't have
2639 * a valid path yet because we did not process the refs yet. So, the inode
2640 * is created as orphan.
2642 static int send_create_inode(struct send_ctx *sctx, u64 ino)
2644 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2652 btrfs_debug(fs_info, "send_create_inode %llu", ino);
2654 p = fs_path_alloc();
2658 if (ino != sctx->cur_ino) {
2659 ret = get_inode_info(sctx->send_root, ino, NULL, &gen, &mode,
2660 NULL, NULL, &rdev, NULL);
2664 gen = sctx->cur_inode_gen;
2665 mode = sctx->cur_inode_mode;
2666 rdev = sctx->cur_inode_rdev;
2669 if (S_ISREG(mode)) {
2670 cmd = BTRFS_SEND_C_MKFILE;
2671 } else if (S_ISDIR(mode)) {
2672 cmd = BTRFS_SEND_C_MKDIR;
2673 } else if (S_ISLNK(mode)) {
2674 cmd = BTRFS_SEND_C_SYMLINK;
2675 } else if (S_ISCHR(mode) || S_ISBLK(mode)) {
2676 cmd = BTRFS_SEND_C_MKNOD;
2677 } else if (S_ISFIFO(mode)) {
2678 cmd = BTRFS_SEND_C_MKFIFO;
2679 } else if (S_ISSOCK(mode)) {
2680 cmd = BTRFS_SEND_C_MKSOCK;
2682 btrfs_warn(sctx->send_root->fs_info, "unexpected inode type %o",
2683 (int)(mode & S_IFMT));
2688 ret = begin_cmd(sctx, cmd);
2692 ret = gen_unique_name(sctx, ino, gen, p);
2696 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2697 TLV_PUT_U64(sctx, BTRFS_SEND_A_INO, ino);
2699 if (S_ISLNK(mode)) {
2701 ret = read_symlink(sctx->send_root, ino, p);
2704 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH_LINK, p);
2705 } else if (S_ISCHR(mode) || S_ISBLK(mode) ||
2706 S_ISFIFO(mode) || S_ISSOCK(mode)) {
2707 TLV_PUT_U64(sctx, BTRFS_SEND_A_RDEV, new_encode_dev(rdev));
2708 TLV_PUT_U64(sctx, BTRFS_SEND_A_MODE, mode);
2711 ret = send_cmd(sctx);
2723 * We need some special handling for inodes that get processed before the parent
2724 * directory got created. See process_recorded_refs for details.
2725 * This function does the check if we already created the dir out of order.
2727 static int did_create_dir(struct send_ctx *sctx, u64 dir)
2731 struct btrfs_path *path = NULL;
2732 struct btrfs_key key;
2733 struct btrfs_key found_key;
2734 struct btrfs_key di_key;
2735 struct btrfs_dir_item *di;
2737 path = alloc_path_for_send();
2742 key.type = BTRFS_DIR_INDEX_KEY;
2745 btrfs_for_each_slot(sctx->send_root, &key, &found_key, path, iter_ret) {
2746 struct extent_buffer *eb = path->nodes[0];
2748 if (found_key.objectid != key.objectid ||
2749 found_key.type != key.type) {
2754 di = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dir_item);
2755 btrfs_dir_item_key_to_cpu(eb, di, &di_key);
2757 if (di_key.type != BTRFS_ROOT_ITEM_KEY &&
2758 di_key.objectid < sctx->send_progress) {
2763 /* Catch error found during iteration */
2767 btrfs_free_path(path);
2772 * Only creates the inode if it is:
2773 * 1. Not a directory
2774 * 2. Or a directory which was not created already due to out of order
2775 * directories. See did_create_dir and process_recorded_refs for details.
2777 static int send_create_inode_if_needed(struct send_ctx *sctx)
2781 if (S_ISDIR(sctx->cur_inode_mode)) {
2782 ret = did_create_dir(sctx, sctx->cur_ino);
2789 return send_create_inode(sctx, sctx->cur_ino);
2792 struct recorded_ref {
2793 struct list_head list;
2795 struct fs_path *full_path;
2799 struct rb_node node;
2800 struct rb_root *root;
2803 static struct recorded_ref *recorded_ref_alloc(void)
2805 struct recorded_ref *ref;
2807 ref = kzalloc(sizeof(*ref), GFP_KERNEL);
2810 RB_CLEAR_NODE(&ref->node);
2811 INIT_LIST_HEAD(&ref->list);
2815 static void recorded_ref_free(struct recorded_ref *ref)
2819 if (!RB_EMPTY_NODE(&ref->node))
2820 rb_erase(&ref->node, ref->root);
2821 list_del(&ref->list);
2822 fs_path_free(ref->full_path);
2826 static void set_ref_path(struct recorded_ref *ref, struct fs_path *path)
2828 ref->full_path = path;
2829 ref->name = (char *)kbasename(ref->full_path->start);
2830 ref->name_len = ref->full_path->end - ref->name;
2833 static int dup_ref(struct recorded_ref *ref, struct list_head *list)
2835 struct recorded_ref *new;
2837 new = recorded_ref_alloc();
2841 new->dir = ref->dir;
2842 new->dir_gen = ref->dir_gen;
2843 list_add_tail(&new->list, list);
2847 static void __free_recorded_refs(struct list_head *head)
2849 struct recorded_ref *cur;
2851 while (!list_empty(head)) {
2852 cur = list_entry(head->next, struct recorded_ref, list);
2853 recorded_ref_free(cur);
2857 static void free_recorded_refs(struct send_ctx *sctx)
2859 __free_recorded_refs(&sctx->new_refs);
2860 __free_recorded_refs(&sctx->deleted_refs);
2864 * Renames/moves a file/dir to its orphan name. Used when the first
2865 * ref of an unprocessed inode gets overwritten and for all non empty
2868 static int orphanize_inode(struct send_ctx *sctx, u64 ino, u64 gen,
2869 struct fs_path *path)
2872 struct fs_path *orphan;
2874 orphan = fs_path_alloc();
2878 ret = gen_unique_name(sctx, ino, gen, orphan);
2882 ret = send_rename(sctx, path, orphan);
2885 fs_path_free(orphan);
2889 static struct orphan_dir_info *add_orphan_dir_info(struct send_ctx *sctx,
2890 u64 dir_ino, u64 dir_gen)
2892 struct rb_node **p = &sctx->orphan_dirs.rb_node;
2893 struct rb_node *parent = NULL;
2894 struct orphan_dir_info *entry, *odi;
2898 entry = rb_entry(parent, struct orphan_dir_info, node);
2899 if (dir_ino < entry->ino)
2901 else if (dir_ino > entry->ino)
2902 p = &(*p)->rb_right;
2903 else if (dir_gen < entry->gen)
2905 else if (dir_gen > entry->gen)
2906 p = &(*p)->rb_right;
2911 odi = kmalloc(sizeof(*odi), GFP_KERNEL);
2913 return ERR_PTR(-ENOMEM);
2916 odi->last_dir_index_offset = 0;
2918 rb_link_node(&odi->node, parent, p);
2919 rb_insert_color(&odi->node, &sctx->orphan_dirs);
2923 static struct orphan_dir_info *get_orphan_dir_info(struct send_ctx *sctx,
2924 u64 dir_ino, u64 gen)
2926 struct rb_node *n = sctx->orphan_dirs.rb_node;
2927 struct orphan_dir_info *entry;
2930 entry = rb_entry(n, struct orphan_dir_info, node);
2931 if (dir_ino < entry->ino)
2933 else if (dir_ino > entry->ino)
2935 else if (gen < entry->gen)
2937 else if (gen > entry->gen)
2945 static int is_waiting_for_rm(struct send_ctx *sctx, u64 dir_ino, u64 gen)
2947 struct orphan_dir_info *odi = get_orphan_dir_info(sctx, dir_ino, gen);
2952 static void free_orphan_dir_info(struct send_ctx *sctx,
2953 struct orphan_dir_info *odi)
2957 rb_erase(&odi->node, &sctx->orphan_dirs);
2962 * Returns 1 if a directory can be removed at this point in time.
2963 * We check this by iterating all dir items and checking if the inode behind
2964 * the dir item was already processed.
2966 static int can_rmdir(struct send_ctx *sctx, u64 dir, u64 dir_gen,
2971 struct btrfs_root *root = sctx->parent_root;
2972 struct btrfs_path *path;
2973 struct btrfs_key key;
2974 struct btrfs_key found_key;
2975 struct btrfs_key loc;
2976 struct btrfs_dir_item *di;
2977 struct orphan_dir_info *odi = NULL;
2980 * Don't try to rmdir the top/root subvolume dir.
2982 if (dir == BTRFS_FIRST_FREE_OBJECTID)
2985 path = alloc_path_for_send();
2990 key.type = BTRFS_DIR_INDEX_KEY;
2993 odi = get_orphan_dir_info(sctx, dir, dir_gen);
2995 key.offset = odi->last_dir_index_offset;
2997 btrfs_for_each_slot(root, &key, &found_key, path, iter_ret) {
2998 struct waiting_dir_move *dm;
3000 if (found_key.objectid != key.objectid ||
3001 found_key.type != key.type)
3004 di = btrfs_item_ptr(path->nodes[0], path->slots[0],
3005 struct btrfs_dir_item);
3006 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &loc);
3008 dm = get_waiting_dir_move(sctx, loc.objectid);
3010 odi = add_orphan_dir_info(sctx, dir, dir_gen);
3016 odi->last_dir_index_offset = found_key.offset;
3017 dm->rmdir_ino = dir;
3018 dm->rmdir_gen = dir_gen;
3023 if (loc.objectid > send_progress) {
3024 odi = add_orphan_dir_info(sctx, dir, dir_gen);
3030 odi->last_dir_index_offset = found_key.offset;
3039 free_orphan_dir_info(sctx, odi);
3044 btrfs_free_path(path);
3048 static int is_waiting_for_move(struct send_ctx *sctx, u64 ino)
3050 struct waiting_dir_move *entry = get_waiting_dir_move(sctx, ino);
3052 return entry != NULL;
3055 static int add_waiting_dir_move(struct send_ctx *sctx, u64 ino, bool orphanized)
3057 struct rb_node **p = &sctx->waiting_dir_moves.rb_node;
3058 struct rb_node *parent = NULL;
3059 struct waiting_dir_move *entry, *dm;
3061 dm = kmalloc(sizeof(*dm), GFP_KERNEL);
3067 dm->orphanized = orphanized;
3071 entry = rb_entry(parent, struct waiting_dir_move, node);
3072 if (ino < entry->ino) {
3074 } else if (ino > entry->ino) {
3075 p = &(*p)->rb_right;
3082 rb_link_node(&dm->node, parent, p);
3083 rb_insert_color(&dm->node, &sctx->waiting_dir_moves);
3087 static struct waiting_dir_move *
3088 get_waiting_dir_move(struct send_ctx *sctx, u64 ino)
3090 struct rb_node *n = sctx->waiting_dir_moves.rb_node;
3091 struct waiting_dir_move *entry;
3094 entry = rb_entry(n, struct waiting_dir_move, node);
3095 if (ino < entry->ino)
3097 else if (ino > entry->ino)
3105 static void free_waiting_dir_move(struct send_ctx *sctx,
3106 struct waiting_dir_move *dm)
3110 rb_erase(&dm->node, &sctx->waiting_dir_moves);
3114 static int add_pending_dir_move(struct send_ctx *sctx,
3118 struct list_head *new_refs,
3119 struct list_head *deleted_refs,
3120 const bool is_orphan)
3122 struct rb_node **p = &sctx->pending_dir_moves.rb_node;
3123 struct rb_node *parent = NULL;
3124 struct pending_dir_move *entry = NULL, *pm;
3125 struct recorded_ref *cur;
3129 pm = kmalloc(sizeof(*pm), GFP_KERNEL);
3132 pm->parent_ino = parent_ino;
3135 INIT_LIST_HEAD(&pm->list);
3136 INIT_LIST_HEAD(&pm->update_refs);
3137 RB_CLEAR_NODE(&pm->node);
3141 entry = rb_entry(parent, struct pending_dir_move, node);
3142 if (parent_ino < entry->parent_ino) {
3144 } else if (parent_ino > entry->parent_ino) {
3145 p = &(*p)->rb_right;
3152 list_for_each_entry(cur, deleted_refs, list) {
3153 ret = dup_ref(cur, &pm->update_refs);
3157 list_for_each_entry(cur, new_refs, list) {
3158 ret = dup_ref(cur, &pm->update_refs);
3163 ret = add_waiting_dir_move(sctx, pm->ino, is_orphan);
3168 list_add_tail(&pm->list, &entry->list);
3170 rb_link_node(&pm->node, parent, p);
3171 rb_insert_color(&pm->node, &sctx->pending_dir_moves);
3176 __free_recorded_refs(&pm->update_refs);
3182 static struct pending_dir_move *get_pending_dir_moves(struct send_ctx *sctx,
3185 struct rb_node *n = sctx->pending_dir_moves.rb_node;
3186 struct pending_dir_move *entry;
3189 entry = rb_entry(n, struct pending_dir_move, node);
3190 if (parent_ino < entry->parent_ino)
3192 else if (parent_ino > entry->parent_ino)
3200 static int path_loop(struct send_ctx *sctx, struct fs_path *name,
3201 u64 ino, u64 gen, u64 *ancestor_ino)
3204 u64 parent_inode = 0;
3206 u64 start_ino = ino;
3209 while (ino != BTRFS_FIRST_FREE_OBJECTID) {
3210 fs_path_reset(name);
3212 if (is_waiting_for_rm(sctx, ino, gen))
3214 if (is_waiting_for_move(sctx, ino)) {
3215 if (*ancestor_ino == 0)
3216 *ancestor_ino = ino;
3217 ret = get_first_ref(sctx->parent_root, ino,
3218 &parent_inode, &parent_gen, name);
3220 ret = __get_cur_name_and_parent(sctx, ino, gen,
3230 if (parent_inode == start_ino) {
3232 if (*ancestor_ino == 0)
3233 *ancestor_ino = ino;
3242 static int apply_dir_move(struct send_ctx *sctx, struct pending_dir_move *pm)
3244 struct fs_path *from_path = NULL;
3245 struct fs_path *to_path = NULL;
3246 struct fs_path *name = NULL;
3247 u64 orig_progress = sctx->send_progress;
3248 struct recorded_ref *cur;
3249 u64 parent_ino, parent_gen;
3250 struct waiting_dir_move *dm = NULL;
3257 name = fs_path_alloc();
3258 from_path = fs_path_alloc();
3259 if (!name || !from_path) {
3264 dm = get_waiting_dir_move(sctx, pm->ino);
3266 rmdir_ino = dm->rmdir_ino;
3267 rmdir_gen = dm->rmdir_gen;
3268 is_orphan = dm->orphanized;
3269 free_waiting_dir_move(sctx, dm);
3272 ret = gen_unique_name(sctx, pm->ino,
3273 pm->gen, from_path);
3275 ret = get_first_ref(sctx->parent_root, pm->ino,
3276 &parent_ino, &parent_gen, name);
3279 ret = get_cur_path(sctx, parent_ino, parent_gen,
3283 ret = fs_path_add_path(from_path, name);
3288 sctx->send_progress = sctx->cur_ino + 1;
3289 ret = path_loop(sctx, name, pm->ino, pm->gen, &ancestor);
3293 LIST_HEAD(deleted_refs);
3294 ASSERT(ancestor > BTRFS_FIRST_FREE_OBJECTID);
3295 ret = add_pending_dir_move(sctx, pm->ino, pm->gen, ancestor,
3296 &pm->update_refs, &deleted_refs,
3301 dm = get_waiting_dir_move(sctx, pm->ino);
3303 dm->rmdir_ino = rmdir_ino;
3304 dm->rmdir_gen = rmdir_gen;
3308 fs_path_reset(name);
3311 ret = get_cur_path(sctx, pm->ino, pm->gen, to_path);
3315 ret = send_rename(sctx, from_path, to_path);
3320 struct orphan_dir_info *odi;
3323 odi = get_orphan_dir_info(sctx, rmdir_ino, rmdir_gen);
3325 /* already deleted */
3330 ret = can_rmdir(sctx, rmdir_ino, gen, sctx->cur_ino);
3336 name = fs_path_alloc();
3341 ret = get_cur_path(sctx, rmdir_ino, gen, name);
3344 ret = send_rmdir(sctx, name);
3350 ret = send_utimes(sctx, pm->ino, pm->gen);
3355 * After rename/move, need to update the utimes of both new parent(s)
3356 * and old parent(s).
3358 list_for_each_entry(cur, &pm->update_refs, list) {
3360 * The parent inode might have been deleted in the send snapshot
3362 ret = get_inode_info(sctx->send_root, cur->dir, NULL,
3363 NULL, NULL, NULL, NULL, NULL, NULL);
3364 if (ret == -ENOENT) {
3371 ret = send_utimes(sctx, cur->dir, cur->dir_gen);
3378 fs_path_free(from_path);
3379 fs_path_free(to_path);
3380 sctx->send_progress = orig_progress;
3385 static void free_pending_move(struct send_ctx *sctx, struct pending_dir_move *m)
3387 if (!list_empty(&m->list))
3389 if (!RB_EMPTY_NODE(&m->node))
3390 rb_erase(&m->node, &sctx->pending_dir_moves);
3391 __free_recorded_refs(&m->update_refs);
3395 static void tail_append_pending_moves(struct send_ctx *sctx,
3396 struct pending_dir_move *moves,
3397 struct list_head *stack)
3399 if (list_empty(&moves->list)) {
3400 list_add_tail(&moves->list, stack);
3403 list_splice_init(&moves->list, &list);
3404 list_add_tail(&moves->list, stack);
3405 list_splice_tail(&list, stack);
3407 if (!RB_EMPTY_NODE(&moves->node)) {
3408 rb_erase(&moves->node, &sctx->pending_dir_moves);
3409 RB_CLEAR_NODE(&moves->node);
3413 static int apply_children_dir_moves(struct send_ctx *sctx)
3415 struct pending_dir_move *pm;
3416 struct list_head stack;
3417 u64 parent_ino = sctx->cur_ino;
3420 pm = get_pending_dir_moves(sctx, parent_ino);
3424 INIT_LIST_HEAD(&stack);
3425 tail_append_pending_moves(sctx, pm, &stack);
3427 while (!list_empty(&stack)) {
3428 pm = list_first_entry(&stack, struct pending_dir_move, list);
3429 parent_ino = pm->ino;
3430 ret = apply_dir_move(sctx, pm);
3431 free_pending_move(sctx, pm);
3434 pm = get_pending_dir_moves(sctx, parent_ino);
3436 tail_append_pending_moves(sctx, pm, &stack);
3441 while (!list_empty(&stack)) {
3442 pm = list_first_entry(&stack, struct pending_dir_move, list);
3443 free_pending_move(sctx, pm);
3449 * We might need to delay a directory rename even when no ancestor directory
3450 * (in the send root) with a higher inode number than ours (sctx->cur_ino) was
3451 * renamed. This happens when we rename a directory to the old name (the name
3452 * in the parent root) of some other unrelated directory that got its rename
3453 * delayed due to some ancestor with higher number that got renamed.
3459 * |---- a/ (ino 257)
3460 * | |---- file (ino 260)
3462 * |---- b/ (ino 258)
3463 * |---- c/ (ino 259)
3467 * |---- a/ (ino 258)
3468 * |---- x/ (ino 259)
3469 * |---- y/ (ino 257)
3470 * |----- file (ino 260)
3472 * Here we can not rename 258 from 'b' to 'a' without the rename of inode 257
3473 * from 'a' to 'x/y' happening first, which in turn depends on the rename of
3474 * inode 259 from 'c' to 'x'. So the order of rename commands the send stream
3477 * 1 - rename 259 from 'c' to 'x'
3478 * 2 - rename 257 from 'a' to 'x/y'
3479 * 3 - rename 258 from 'b' to 'a'
3481 * Returns 1 if the rename of sctx->cur_ino needs to be delayed, 0 if it can
3482 * be done right away and < 0 on error.
3484 static int wait_for_dest_dir_move(struct send_ctx *sctx,
3485 struct recorded_ref *parent_ref,
3486 const bool is_orphan)
3488 struct btrfs_fs_info *fs_info = sctx->parent_root->fs_info;
3489 struct btrfs_path *path;
3490 struct btrfs_key key;
3491 struct btrfs_key di_key;
3492 struct btrfs_dir_item *di;
3496 struct waiting_dir_move *wdm;
3498 if (RB_EMPTY_ROOT(&sctx->waiting_dir_moves))
3501 path = alloc_path_for_send();
3505 key.objectid = parent_ref->dir;
3506 key.type = BTRFS_DIR_ITEM_KEY;
3507 key.offset = btrfs_name_hash(parent_ref->name, parent_ref->name_len);
3509 ret = btrfs_search_slot(NULL, sctx->parent_root, &key, path, 0, 0);
3512 } else if (ret > 0) {
3517 di = btrfs_match_dir_item_name(fs_info, path, parent_ref->name,
3518 parent_ref->name_len);
3524 * di_key.objectid has the number of the inode that has a dentry in the
3525 * parent directory with the same name that sctx->cur_ino is being
3526 * renamed to. We need to check if that inode is in the send root as
3527 * well and if it is currently marked as an inode with a pending rename,
3528 * if it is, we need to delay the rename of sctx->cur_ino as well, so
3529 * that it happens after that other inode is renamed.
3531 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &di_key);
3532 if (di_key.type != BTRFS_INODE_ITEM_KEY) {
3537 ret = get_inode_info(sctx->parent_root, di_key.objectid, NULL,
3538 &left_gen, NULL, NULL, NULL, NULL, NULL);
3541 ret = get_inode_info(sctx->send_root, di_key.objectid, NULL,
3542 &right_gen, NULL, NULL, NULL, NULL, NULL);
3549 /* Different inode, no need to delay the rename of sctx->cur_ino */
3550 if (right_gen != left_gen) {
3555 wdm = get_waiting_dir_move(sctx, di_key.objectid);
3556 if (wdm && !wdm->orphanized) {
3557 ret = add_pending_dir_move(sctx,
3559 sctx->cur_inode_gen,
3562 &sctx->deleted_refs,
3568 btrfs_free_path(path);
3573 * Check if inode ino2, or any of its ancestors, is inode ino1.
3574 * Return 1 if true, 0 if false and < 0 on error.
3576 static int check_ino_in_path(struct btrfs_root *root,
3581 struct fs_path *fs_path)
3586 return ino1_gen == ino2_gen;
3588 while (ino > BTRFS_FIRST_FREE_OBJECTID) {
3593 fs_path_reset(fs_path);
3594 ret = get_first_ref(root, ino, &parent, &parent_gen, fs_path);
3598 return parent_gen == ino1_gen;
3605 * Check if inode ino1 is an ancestor of inode ino2 in the given root for any
3606 * possible path (in case ino2 is not a directory and has multiple hard links).
3607 * Return 1 if true, 0 if false and < 0 on error.
3609 static int is_ancestor(struct btrfs_root *root,
3613 struct fs_path *fs_path)
3615 bool free_fs_path = false;
3618 struct btrfs_path *path = NULL;
3619 struct btrfs_key key;
3622 fs_path = fs_path_alloc();
3625 free_fs_path = true;
3628 path = alloc_path_for_send();
3634 key.objectid = ino2;
3635 key.type = BTRFS_INODE_REF_KEY;
3638 btrfs_for_each_slot(root, &key, &key, path, iter_ret) {
3639 struct extent_buffer *leaf = path->nodes[0];
3640 int slot = path->slots[0];
3644 if (key.objectid != ino2)
3646 if (key.type != BTRFS_INODE_REF_KEY &&
3647 key.type != BTRFS_INODE_EXTREF_KEY)
3650 item_size = btrfs_item_size(leaf, slot);
3651 while (cur_offset < item_size) {
3655 if (key.type == BTRFS_INODE_EXTREF_KEY) {
3657 struct btrfs_inode_extref *extref;
3659 ptr = btrfs_item_ptr_offset(leaf, slot);
3660 extref = (struct btrfs_inode_extref *)
3662 parent = btrfs_inode_extref_parent(leaf,
3664 cur_offset += sizeof(*extref);
3665 cur_offset += btrfs_inode_extref_name_len(leaf,
3668 parent = key.offset;
3669 cur_offset = item_size;
3672 ret = get_inode_info(root, parent, NULL, &parent_gen,
3673 NULL, NULL, NULL, NULL, NULL);
3676 ret = check_ino_in_path(root, ino1, ino1_gen,
3677 parent, parent_gen, fs_path);
3687 btrfs_free_path(path);
3689 fs_path_free(fs_path);
3693 static int wait_for_parent_move(struct send_ctx *sctx,
3694 struct recorded_ref *parent_ref,
3695 const bool is_orphan)
3698 u64 ino = parent_ref->dir;
3699 u64 ino_gen = parent_ref->dir_gen;
3700 u64 parent_ino_before, parent_ino_after;
3701 struct fs_path *path_before = NULL;
3702 struct fs_path *path_after = NULL;
3705 path_after = fs_path_alloc();
3706 path_before = fs_path_alloc();
3707 if (!path_after || !path_before) {
3713 * Our current directory inode may not yet be renamed/moved because some
3714 * ancestor (immediate or not) has to be renamed/moved first. So find if
3715 * such ancestor exists and make sure our own rename/move happens after
3716 * that ancestor is processed to avoid path build infinite loops (done
3717 * at get_cur_path()).
3719 while (ino > BTRFS_FIRST_FREE_OBJECTID) {
3720 u64 parent_ino_after_gen;
3722 if (is_waiting_for_move(sctx, ino)) {
3724 * If the current inode is an ancestor of ino in the
3725 * parent root, we need to delay the rename of the
3726 * current inode, otherwise don't delayed the rename
3727 * because we can end up with a circular dependency
3728 * of renames, resulting in some directories never
3729 * getting the respective rename operations issued in
3730 * the send stream or getting into infinite path build
3733 ret = is_ancestor(sctx->parent_root,
3734 sctx->cur_ino, sctx->cur_inode_gen,
3740 fs_path_reset(path_before);
3741 fs_path_reset(path_after);
3743 ret = get_first_ref(sctx->send_root, ino, &parent_ino_after,
3744 &parent_ino_after_gen, path_after);
3747 ret = get_first_ref(sctx->parent_root, ino, &parent_ino_before,
3749 if (ret < 0 && ret != -ENOENT) {
3751 } else if (ret == -ENOENT) {
3756 len1 = fs_path_len(path_before);
3757 len2 = fs_path_len(path_after);
3758 if (ino > sctx->cur_ino &&
3759 (parent_ino_before != parent_ino_after || len1 != len2 ||
3760 memcmp(path_before->start, path_after->start, len1))) {
3763 ret = get_inode_info(sctx->parent_root, ino, NULL,
3764 &parent_ino_gen, NULL, NULL, NULL,
3768 if (ino_gen == parent_ino_gen) {
3773 ino = parent_ino_after;
3774 ino_gen = parent_ino_after_gen;
3778 fs_path_free(path_before);
3779 fs_path_free(path_after);
3782 ret = add_pending_dir_move(sctx,
3784 sctx->cur_inode_gen,
3787 &sctx->deleted_refs,
3796 static int update_ref_path(struct send_ctx *sctx, struct recorded_ref *ref)
3799 struct fs_path *new_path;
3802 * Our reference's name member points to its full_path member string, so
3803 * we use here a new path.
3805 new_path = fs_path_alloc();
3809 ret = get_cur_path(sctx, ref->dir, ref->dir_gen, new_path);
3811 fs_path_free(new_path);
3814 ret = fs_path_add(new_path, ref->name, ref->name_len);
3816 fs_path_free(new_path);
3820 fs_path_free(ref->full_path);
3821 set_ref_path(ref, new_path);
3827 * When processing the new references for an inode we may orphanize an existing
3828 * directory inode because its old name conflicts with one of the new references
3829 * of the current inode. Later, when processing another new reference of our
3830 * inode, we might need to orphanize another inode, but the path we have in the
3831 * reference reflects the pre-orphanization name of the directory we previously
3832 * orphanized. For example:
3834 * parent snapshot looks like:
3837 * |----- f1 (ino 257)
3838 * |----- f2 (ino 258)
3839 * |----- d1/ (ino 259)
3840 * |----- d2/ (ino 260)
3842 * send snapshot looks like:
3845 * |----- d1 (ino 258)
3846 * |----- f2/ (ino 259)
3847 * |----- f2_link/ (ino 260)
3848 * | |----- f1 (ino 257)
3850 * |----- d2 (ino 258)
3852 * When processing inode 257 we compute the name for inode 259 as "d1", and we
3853 * cache it in the name cache. Later when we start processing inode 258, when
3854 * collecting all its new references we set a full path of "d1/d2" for its new
3855 * reference with name "d2". When we start processing the new references we
3856 * start by processing the new reference with name "d1", and this results in
3857 * orphanizing inode 259, since its old reference causes a conflict. Then we
3858 * move on the next new reference, with name "d2", and we find out we must
3859 * orphanize inode 260, as its old reference conflicts with ours - but for the
3860 * orphanization we use a source path corresponding to the path we stored in the
3861 * new reference, which is "d1/d2" and not "o259-6-0/d2" - this makes the
3862 * receiver fail since the path component "d1/" no longer exists, it was renamed
3863 * to "o259-6-0/" when processing the previous new reference. So in this case we
3864 * must recompute the path in the new reference and use it for the new
3865 * orphanization operation.
3867 static int refresh_ref_path(struct send_ctx *sctx, struct recorded_ref *ref)
3872 name = kmemdup(ref->name, ref->name_len, GFP_KERNEL);
3876 fs_path_reset(ref->full_path);
3877 ret = get_cur_path(sctx, ref->dir, ref->dir_gen, ref->full_path);
3881 ret = fs_path_add(ref->full_path, name, ref->name_len);
3885 /* Update the reference's base name pointer. */
3886 set_ref_path(ref, ref->full_path);
3893 * This does all the move/link/unlink/rmdir magic.
3895 static int process_recorded_refs(struct send_ctx *sctx, int *pending_move)
3897 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
3899 struct recorded_ref *cur;
3900 struct recorded_ref *cur2;
3901 struct list_head check_dirs;
3902 struct fs_path *valid_path = NULL;
3906 int did_overwrite = 0;
3908 u64 last_dir_ino_rm = 0;
3909 bool can_rename = true;
3910 bool orphanized_dir = false;
3911 bool orphanized_ancestor = false;
3913 btrfs_debug(fs_info, "process_recorded_refs %llu", sctx->cur_ino);
3916 * This should never happen as the root dir always has the same ref
3917 * which is always '..'
3919 BUG_ON(sctx->cur_ino <= BTRFS_FIRST_FREE_OBJECTID);
3920 INIT_LIST_HEAD(&check_dirs);
3922 valid_path = fs_path_alloc();
3929 * First, check if the first ref of the current inode was overwritten
3930 * before. If yes, we know that the current inode was already orphanized
3931 * and thus use the orphan name. If not, we can use get_cur_path to
3932 * get the path of the first ref as it would like while receiving at
3933 * this point in time.
3934 * New inodes are always orphan at the beginning, so force to use the
3935 * orphan name in this case.
3936 * The first ref is stored in valid_path and will be updated if it
3937 * gets moved around.
3939 if (!sctx->cur_inode_new) {
3940 ret = did_overwrite_first_ref(sctx, sctx->cur_ino,
3941 sctx->cur_inode_gen);
3947 if (sctx->cur_inode_new || did_overwrite) {
3948 ret = gen_unique_name(sctx, sctx->cur_ino,
3949 sctx->cur_inode_gen, valid_path);
3954 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen,
3961 * Before doing any rename and link operations, do a first pass on the
3962 * new references to orphanize any unprocessed inodes that may have a
3963 * reference that conflicts with one of the new references of the current
3964 * inode. This needs to happen first because a new reference may conflict
3965 * with the old reference of a parent directory, so we must make sure
3966 * that the path used for link and rename commands don't use an
3967 * orphanized name when an ancestor was not yet orphanized.
3974 * |----- testdir/ (ino 259)
3975 * | |----- a (ino 257)
3977 * |----- b (ino 258)
3982 * |----- testdir_2/ (ino 259)
3983 * | |----- a (ino 260)
3985 * |----- testdir (ino 257)
3986 * |----- b (ino 257)
3987 * |----- b2 (ino 258)
3989 * Processing the new reference for inode 257 with name "b" may happen
3990 * before processing the new reference with name "testdir". If so, we
3991 * must make sure that by the time we send a link command to create the
3992 * hard link "b", inode 259 was already orphanized, since the generated
3993 * path in "valid_path" already contains the orphanized name for 259.
3994 * We are processing inode 257, so only later when processing 259 we do
3995 * the rename operation to change its temporary (orphanized) name to
3998 list_for_each_entry(cur, &sctx->new_refs, list) {
3999 ret = get_cur_inode_state(sctx, cur->dir, cur->dir_gen);
4002 if (ret == inode_state_will_create)
4006 * Check if this new ref would overwrite the first ref of another
4007 * unprocessed inode. If yes, orphanize the overwritten inode.
4008 * If we find an overwritten ref that is not the first ref,
4011 ret = will_overwrite_ref(sctx, cur->dir, cur->dir_gen,
4012 cur->name, cur->name_len,
4013 &ow_inode, &ow_gen, &ow_mode);
4017 ret = is_first_ref(sctx->parent_root,
4018 ow_inode, cur->dir, cur->name,
4023 struct name_cache_entry *nce;
4024 struct waiting_dir_move *wdm;
4026 if (orphanized_dir) {
4027 ret = refresh_ref_path(sctx, cur);
4032 ret = orphanize_inode(sctx, ow_inode, ow_gen,
4036 if (S_ISDIR(ow_mode))
4037 orphanized_dir = true;
4040 * If ow_inode has its rename operation delayed
4041 * make sure that its orphanized name is used in
4042 * the source path when performing its rename
4045 if (is_waiting_for_move(sctx, ow_inode)) {
4046 wdm = get_waiting_dir_move(sctx,
4049 wdm->orphanized = true;
4053 * Make sure we clear our orphanized inode's
4054 * name from the name cache. This is because the
4055 * inode ow_inode might be an ancestor of some
4056 * other inode that will be orphanized as well
4057 * later and has an inode number greater than
4058 * sctx->send_progress. We need to prevent
4059 * future name lookups from using the old name
4060 * and get instead the orphan name.
4062 nce = name_cache_search(sctx, ow_inode, ow_gen);
4064 name_cache_delete(sctx, nce);
4069 * ow_inode might currently be an ancestor of
4070 * cur_ino, therefore compute valid_path (the
4071 * current path of cur_ino) again because it
4072 * might contain the pre-orphanization name of
4073 * ow_inode, which is no longer valid.
4075 ret = is_ancestor(sctx->parent_root,
4077 sctx->cur_ino, NULL);
4079 orphanized_ancestor = true;
4080 fs_path_reset(valid_path);
4081 ret = get_cur_path(sctx, sctx->cur_ino,
4082 sctx->cur_inode_gen,
4089 * If we previously orphanized a directory that
4090 * collided with a new reference that we already
4091 * processed, recompute the current path because
4092 * that directory may be part of the path.
4094 if (orphanized_dir) {
4095 ret = refresh_ref_path(sctx, cur);
4099 ret = send_unlink(sctx, cur->full_path);
4107 list_for_each_entry(cur, &sctx->new_refs, list) {
4109 * We may have refs where the parent directory does not exist
4110 * yet. This happens if the parent directories inum is higher
4111 * than the current inum. To handle this case, we create the
4112 * parent directory out of order. But we need to check if this
4113 * did already happen before due to other refs in the same dir.
4115 ret = get_cur_inode_state(sctx, cur->dir, cur->dir_gen);
4118 if (ret == inode_state_will_create) {
4121 * First check if any of the current inodes refs did
4122 * already create the dir.
4124 list_for_each_entry(cur2, &sctx->new_refs, list) {
4127 if (cur2->dir == cur->dir) {
4134 * If that did not happen, check if a previous inode
4135 * did already create the dir.
4138 ret = did_create_dir(sctx, cur->dir);
4142 ret = send_create_inode(sctx, cur->dir);
4148 if (S_ISDIR(sctx->cur_inode_mode) && sctx->parent_root) {
4149 ret = wait_for_dest_dir_move(sctx, cur, is_orphan);
4158 if (S_ISDIR(sctx->cur_inode_mode) && sctx->parent_root &&
4160 ret = wait_for_parent_move(sctx, cur, is_orphan);
4170 * link/move the ref to the new place. If we have an orphan
4171 * inode, move it and update valid_path. If not, link or move
4172 * it depending on the inode mode.
4174 if (is_orphan && can_rename) {
4175 ret = send_rename(sctx, valid_path, cur->full_path);
4179 ret = fs_path_copy(valid_path, cur->full_path);
4182 } else if (can_rename) {
4183 if (S_ISDIR(sctx->cur_inode_mode)) {
4185 * Dirs can't be linked, so move it. For moved
4186 * dirs, we always have one new and one deleted
4187 * ref. The deleted ref is ignored later.
4189 ret = send_rename(sctx, valid_path,
4192 ret = fs_path_copy(valid_path,
4198 * We might have previously orphanized an inode
4199 * which is an ancestor of our current inode,
4200 * so our reference's full path, which was
4201 * computed before any such orphanizations, must
4204 if (orphanized_dir) {
4205 ret = update_ref_path(sctx, cur);
4209 ret = send_link(sctx, cur->full_path,
4215 ret = dup_ref(cur, &check_dirs);
4220 if (S_ISDIR(sctx->cur_inode_mode) && sctx->cur_inode_deleted) {
4222 * Check if we can already rmdir the directory. If not,
4223 * orphanize it. For every dir item inside that gets deleted
4224 * later, we do this check again and rmdir it then if possible.
4225 * See the use of check_dirs for more details.
4227 ret = can_rmdir(sctx, sctx->cur_ino, sctx->cur_inode_gen,
4232 ret = send_rmdir(sctx, valid_path);
4235 } else if (!is_orphan) {
4236 ret = orphanize_inode(sctx, sctx->cur_ino,
4237 sctx->cur_inode_gen, valid_path);
4243 list_for_each_entry(cur, &sctx->deleted_refs, list) {
4244 ret = dup_ref(cur, &check_dirs);
4248 } else if (S_ISDIR(sctx->cur_inode_mode) &&
4249 !list_empty(&sctx->deleted_refs)) {
4251 * We have a moved dir. Add the old parent to check_dirs
4253 cur = list_entry(sctx->deleted_refs.next, struct recorded_ref,
4255 ret = dup_ref(cur, &check_dirs);
4258 } else if (!S_ISDIR(sctx->cur_inode_mode)) {
4260 * We have a non dir inode. Go through all deleted refs and
4261 * unlink them if they were not already overwritten by other
4264 list_for_each_entry(cur, &sctx->deleted_refs, list) {
4265 ret = did_overwrite_ref(sctx, cur->dir, cur->dir_gen,
4266 sctx->cur_ino, sctx->cur_inode_gen,
4267 cur->name, cur->name_len);
4272 * If we orphanized any ancestor before, we need
4273 * to recompute the full path for deleted names,
4274 * since any such path was computed before we
4275 * processed any references and orphanized any
4278 if (orphanized_ancestor) {
4279 ret = update_ref_path(sctx, cur);
4283 ret = send_unlink(sctx, cur->full_path);
4287 ret = dup_ref(cur, &check_dirs);
4292 * If the inode is still orphan, unlink the orphan. This may
4293 * happen when a previous inode did overwrite the first ref
4294 * of this inode and no new refs were added for the current
4295 * inode. Unlinking does not mean that the inode is deleted in
4296 * all cases. There may still be links to this inode in other
4300 ret = send_unlink(sctx, valid_path);
4307 * We did collect all parent dirs where cur_inode was once located. We
4308 * now go through all these dirs and check if they are pending for
4309 * deletion and if it's finally possible to perform the rmdir now.
4310 * We also update the inode stats of the parent dirs here.
4312 list_for_each_entry(cur, &check_dirs, list) {
4314 * In case we had refs into dirs that were not processed yet,
4315 * we don't need to do the utime and rmdir logic for these dirs.
4316 * The dir will be processed later.
4318 if (cur->dir > sctx->cur_ino)
4321 ret = get_cur_inode_state(sctx, cur->dir, cur->dir_gen);
4325 if (ret == inode_state_did_create ||
4326 ret == inode_state_no_change) {
4327 /* TODO delayed utimes */
4328 ret = send_utimes(sctx, cur->dir, cur->dir_gen);
4331 } else if (ret == inode_state_did_delete &&
4332 cur->dir != last_dir_ino_rm) {
4333 ret = can_rmdir(sctx, cur->dir, cur->dir_gen,
4338 ret = get_cur_path(sctx, cur->dir,
4339 cur->dir_gen, valid_path);
4342 ret = send_rmdir(sctx, valid_path);
4345 last_dir_ino_rm = cur->dir;
4353 __free_recorded_refs(&check_dirs);
4354 free_recorded_refs(sctx);
4355 fs_path_free(valid_path);
4359 static int rbtree_ref_comp(const void *k, const struct rb_node *node)
4361 const struct recorded_ref *data = k;
4362 const struct recorded_ref *ref = rb_entry(node, struct recorded_ref, node);
4365 if (data->dir > ref->dir)
4367 if (data->dir < ref->dir)
4369 if (data->dir_gen > ref->dir_gen)
4371 if (data->dir_gen < ref->dir_gen)
4373 if (data->name_len > ref->name_len)
4375 if (data->name_len < ref->name_len)
4377 result = strcmp(data->name, ref->name);
4385 static bool rbtree_ref_less(struct rb_node *node, const struct rb_node *parent)
4387 const struct recorded_ref *entry = rb_entry(node, struct recorded_ref, node);
4389 return rbtree_ref_comp(entry, parent) < 0;
4392 static int record_ref_in_tree(struct rb_root *root, struct list_head *refs,
4393 struct fs_path *name, u64 dir, u64 dir_gen,
4394 struct send_ctx *sctx)
4397 struct fs_path *path = NULL;
4398 struct recorded_ref *ref = NULL;
4400 path = fs_path_alloc();
4406 ref = recorded_ref_alloc();
4412 ret = get_cur_path(sctx, dir, dir_gen, path);
4415 ret = fs_path_add_path(path, name);
4420 ref->dir_gen = dir_gen;
4421 set_ref_path(ref, path);
4422 list_add_tail(&ref->list, refs);
4423 rb_add(&ref->node, root, rbtree_ref_less);
4427 if (path && (!ref || !ref->full_path))
4429 recorded_ref_free(ref);
4434 static int record_new_ref_if_needed(int num, u64 dir, int index,
4435 struct fs_path *name, void *ctx)
4438 struct send_ctx *sctx = ctx;
4439 struct rb_node *node = NULL;
4440 struct recorded_ref data;
4441 struct recorded_ref *ref;
4444 ret = get_inode_info(sctx->send_root, dir, NULL, &dir_gen, NULL,
4445 NULL, NULL, NULL, NULL);
4450 data.dir_gen = dir_gen;
4451 set_ref_path(&data, name);
4452 node = rb_find(&data, &sctx->rbtree_deleted_refs, rbtree_ref_comp);
4454 ref = rb_entry(node, struct recorded_ref, node);
4455 recorded_ref_free(ref);
4457 ret = record_ref_in_tree(&sctx->rbtree_new_refs,
4458 &sctx->new_refs, name, dir, dir_gen,
4465 static int record_deleted_ref_if_needed(int num, u64 dir, int index,
4466 struct fs_path *name, void *ctx)
4469 struct send_ctx *sctx = ctx;
4470 struct rb_node *node = NULL;
4471 struct recorded_ref data;
4472 struct recorded_ref *ref;
4475 ret = get_inode_info(sctx->parent_root, dir, NULL, &dir_gen, NULL,
4476 NULL, NULL, NULL, NULL);
4481 data.dir_gen = dir_gen;
4482 set_ref_path(&data, name);
4483 node = rb_find(&data, &sctx->rbtree_new_refs, rbtree_ref_comp);
4485 ref = rb_entry(node, struct recorded_ref, node);
4486 recorded_ref_free(ref);
4488 ret = record_ref_in_tree(&sctx->rbtree_deleted_refs,
4489 &sctx->deleted_refs, name, dir,
4496 static int record_new_ref(struct send_ctx *sctx)
4500 ret = iterate_inode_ref(sctx->send_root, sctx->left_path,
4501 sctx->cmp_key, 0, record_new_ref_if_needed, sctx);
4510 static int record_deleted_ref(struct send_ctx *sctx)
4514 ret = iterate_inode_ref(sctx->parent_root, sctx->right_path,
4515 sctx->cmp_key, 0, record_deleted_ref_if_needed,
4525 static int record_changed_ref(struct send_ctx *sctx)
4529 ret = iterate_inode_ref(sctx->send_root, sctx->left_path,
4530 sctx->cmp_key, 0, record_new_ref_if_needed, sctx);
4533 ret = iterate_inode_ref(sctx->parent_root, sctx->right_path,
4534 sctx->cmp_key, 0, record_deleted_ref_if_needed, sctx);
4544 * Record and process all refs at once. Needed when an inode changes the
4545 * generation number, which means that it was deleted and recreated.
4547 static int process_all_refs(struct send_ctx *sctx,
4548 enum btrfs_compare_tree_result cmd)
4552 struct btrfs_root *root;
4553 struct btrfs_path *path;
4554 struct btrfs_key key;
4555 struct btrfs_key found_key;
4556 iterate_inode_ref_t cb;
4557 int pending_move = 0;
4559 path = alloc_path_for_send();
4563 if (cmd == BTRFS_COMPARE_TREE_NEW) {
4564 root = sctx->send_root;
4565 cb = record_new_ref_if_needed;
4566 } else if (cmd == BTRFS_COMPARE_TREE_DELETED) {
4567 root = sctx->parent_root;
4568 cb = record_deleted_ref_if_needed;
4570 btrfs_err(sctx->send_root->fs_info,
4571 "Wrong command %d in process_all_refs", cmd);
4576 key.objectid = sctx->cmp_key->objectid;
4577 key.type = BTRFS_INODE_REF_KEY;
4579 btrfs_for_each_slot(root, &key, &found_key, path, iter_ret) {
4580 if (found_key.objectid != key.objectid ||
4581 (found_key.type != BTRFS_INODE_REF_KEY &&
4582 found_key.type != BTRFS_INODE_EXTREF_KEY))
4585 ret = iterate_inode_ref(root, path, &found_key, 0, cb, sctx);
4589 /* Catch error found during iteration */
4594 btrfs_release_path(path);
4597 * We don't actually care about pending_move as we are simply
4598 * re-creating this inode and will be rename'ing it into place once we
4599 * rename the parent directory.
4601 ret = process_recorded_refs(sctx, &pending_move);
4603 btrfs_free_path(path);
4607 static int send_set_xattr(struct send_ctx *sctx,
4608 struct fs_path *path,
4609 const char *name, int name_len,
4610 const char *data, int data_len)
4614 ret = begin_cmd(sctx, BTRFS_SEND_C_SET_XATTR);
4618 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
4619 TLV_PUT_STRING(sctx, BTRFS_SEND_A_XATTR_NAME, name, name_len);
4620 TLV_PUT(sctx, BTRFS_SEND_A_XATTR_DATA, data, data_len);
4622 ret = send_cmd(sctx);
4629 static int send_remove_xattr(struct send_ctx *sctx,
4630 struct fs_path *path,
4631 const char *name, int name_len)
4635 ret = begin_cmd(sctx, BTRFS_SEND_C_REMOVE_XATTR);
4639 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
4640 TLV_PUT_STRING(sctx, BTRFS_SEND_A_XATTR_NAME, name, name_len);
4642 ret = send_cmd(sctx);
4649 static int __process_new_xattr(int num, struct btrfs_key *di_key,
4650 const char *name, int name_len, const char *data,
4651 int data_len, void *ctx)
4654 struct send_ctx *sctx = ctx;
4656 struct posix_acl_xattr_header dummy_acl;
4658 /* Capabilities are emitted by finish_inode_if_needed */
4659 if (!strncmp(name, XATTR_NAME_CAPS, name_len))
4662 p = fs_path_alloc();
4667 * This hack is needed because empty acls are stored as zero byte
4668 * data in xattrs. Problem with that is, that receiving these zero byte
4669 * acls will fail later. To fix this, we send a dummy acl list that
4670 * only contains the version number and no entries.
4672 if (!strncmp(name, XATTR_NAME_POSIX_ACL_ACCESS, name_len) ||
4673 !strncmp(name, XATTR_NAME_POSIX_ACL_DEFAULT, name_len)) {
4674 if (data_len == 0) {
4675 dummy_acl.a_version =
4676 cpu_to_le32(POSIX_ACL_XATTR_VERSION);
4677 data = (char *)&dummy_acl;
4678 data_len = sizeof(dummy_acl);
4682 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
4686 ret = send_set_xattr(sctx, p, name, name_len, data, data_len);
4693 static int __process_deleted_xattr(int num, struct btrfs_key *di_key,
4694 const char *name, int name_len,
4695 const char *data, int data_len, void *ctx)
4698 struct send_ctx *sctx = ctx;
4701 p = fs_path_alloc();
4705 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
4709 ret = send_remove_xattr(sctx, p, name, name_len);
4716 static int process_new_xattr(struct send_ctx *sctx)
4720 ret = iterate_dir_item(sctx->send_root, sctx->left_path,
4721 __process_new_xattr, sctx);
4726 static int process_deleted_xattr(struct send_ctx *sctx)
4728 return iterate_dir_item(sctx->parent_root, sctx->right_path,
4729 __process_deleted_xattr, sctx);
4732 struct find_xattr_ctx {
4740 static int __find_xattr(int num, struct btrfs_key *di_key, const char *name,
4741 int name_len, const char *data, int data_len, void *vctx)
4743 struct find_xattr_ctx *ctx = vctx;
4745 if (name_len == ctx->name_len &&
4746 strncmp(name, ctx->name, name_len) == 0) {
4747 ctx->found_idx = num;
4748 ctx->found_data_len = data_len;
4749 ctx->found_data = kmemdup(data, data_len, GFP_KERNEL);
4750 if (!ctx->found_data)
4757 static int find_xattr(struct btrfs_root *root,
4758 struct btrfs_path *path,
4759 struct btrfs_key *key,
4760 const char *name, int name_len,
4761 char **data, int *data_len)
4764 struct find_xattr_ctx ctx;
4767 ctx.name_len = name_len;
4769 ctx.found_data = NULL;
4770 ctx.found_data_len = 0;
4772 ret = iterate_dir_item(root, path, __find_xattr, &ctx);
4776 if (ctx.found_idx == -1)
4779 *data = ctx.found_data;
4780 *data_len = ctx.found_data_len;
4782 kfree(ctx.found_data);
4784 return ctx.found_idx;
4788 static int __process_changed_new_xattr(int num, struct btrfs_key *di_key,
4789 const char *name, int name_len,
4790 const char *data, int data_len,
4794 struct send_ctx *sctx = ctx;
4795 char *found_data = NULL;
4796 int found_data_len = 0;
4798 ret = find_xattr(sctx->parent_root, sctx->right_path,
4799 sctx->cmp_key, name, name_len, &found_data,
4801 if (ret == -ENOENT) {
4802 ret = __process_new_xattr(num, di_key, name, name_len, data,
4804 } else if (ret >= 0) {
4805 if (data_len != found_data_len ||
4806 memcmp(data, found_data, data_len)) {
4807 ret = __process_new_xattr(num, di_key, name, name_len,
4808 data, data_len, ctx);
4818 static int __process_changed_deleted_xattr(int num, struct btrfs_key *di_key,
4819 const char *name, int name_len,
4820 const char *data, int data_len,
4824 struct send_ctx *sctx = ctx;
4826 ret = find_xattr(sctx->send_root, sctx->left_path, sctx->cmp_key,
4827 name, name_len, NULL, NULL);
4829 ret = __process_deleted_xattr(num, di_key, name, name_len, data,
4837 static int process_changed_xattr(struct send_ctx *sctx)
4841 ret = iterate_dir_item(sctx->send_root, sctx->left_path,
4842 __process_changed_new_xattr, sctx);
4845 ret = iterate_dir_item(sctx->parent_root, sctx->right_path,
4846 __process_changed_deleted_xattr, sctx);
4852 static int process_all_new_xattrs(struct send_ctx *sctx)
4856 struct btrfs_root *root;
4857 struct btrfs_path *path;
4858 struct btrfs_key key;
4859 struct btrfs_key found_key;
4861 path = alloc_path_for_send();
4865 root = sctx->send_root;
4867 key.objectid = sctx->cmp_key->objectid;
4868 key.type = BTRFS_XATTR_ITEM_KEY;
4870 btrfs_for_each_slot(root, &key, &found_key, path, iter_ret) {
4871 if (found_key.objectid != key.objectid ||
4872 found_key.type != key.type) {
4877 ret = iterate_dir_item(root, path, __process_new_xattr, sctx);
4881 /* Catch error found during iteration */
4885 btrfs_free_path(path);
4889 static inline u64 max_send_read_size(const struct send_ctx *sctx)
4891 return sctx->send_max_size - SZ_16K;
4894 static int put_data_header(struct send_ctx *sctx, u32 len)
4896 if (WARN_ON_ONCE(sctx->put_data))
4898 sctx->put_data = true;
4899 if (sctx->proto >= 2) {
4901 * Since v2, the data attribute header doesn't include a length,
4902 * it is implicitly to the end of the command.
4904 if (sctx->send_max_size - sctx->send_size < sizeof(__le16) + len)
4906 put_unaligned_le16(BTRFS_SEND_A_DATA, sctx->send_buf + sctx->send_size);
4907 sctx->send_size += sizeof(__le16);
4909 struct btrfs_tlv_header *hdr;
4911 if (sctx->send_max_size - sctx->send_size < sizeof(*hdr) + len)
4913 hdr = (struct btrfs_tlv_header *)(sctx->send_buf + sctx->send_size);
4914 put_unaligned_le16(BTRFS_SEND_A_DATA, &hdr->tlv_type);
4915 put_unaligned_le16(len, &hdr->tlv_len);
4916 sctx->send_size += sizeof(*hdr);
4921 static int put_file_data(struct send_ctx *sctx, u64 offset, u32 len)
4923 struct btrfs_root *root = sctx->send_root;
4924 struct btrfs_fs_info *fs_info = root->fs_info;
4926 pgoff_t index = offset >> PAGE_SHIFT;
4928 unsigned pg_offset = offset_in_page(offset);
4931 ret = put_data_header(sctx, len);
4935 last_index = (offset + len - 1) >> PAGE_SHIFT;
4937 while (index <= last_index) {
4938 unsigned cur_len = min_t(unsigned, len,
4939 PAGE_SIZE - pg_offset);
4941 page = find_lock_page(sctx->cur_inode->i_mapping, index);
4943 page_cache_sync_readahead(sctx->cur_inode->i_mapping,
4944 &sctx->ra, NULL, index,
4945 last_index + 1 - index);
4947 page = find_or_create_page(sctx->cur_inode->i_mapping,
4955 if (PageReadahead(page))
4956 page_cache_async_readahead(sctx->cur_inode->i_mapping,
4957 &sctx->ra, NULL, page_folio(page),
4958 index, last_index + 1 - index);
4960 if (!PageUptodate(page)) {
4961 btrfs_read_folio(NULL, page_folio(page));
4963 if (!PageUptodate(page)) {
4966 "send: IO error at offset %llu for inode %llu root %llu",
4967 page_offset(page), sctx->cur_ino,
4968 sctx->send_root->root_key.objectid);
4975 memcpy_from_page(sctx->send_buf + sctx->send_size, page,
4976 pg_offset, cur_len);
4982 sctx->send_size += cur_len;
4989 * Read some bytes from the current inode/file and send a write command to
4992 static int send_write(struct send_ctx *sctx, u64 offset, u32 len)
4994 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
4998 p = fs_path_alloc();
5002 btrfs_debug(fs_info, "send_write offset=%llu, len=%d", offset, len);
5004 ret = begin_cmd(sctx, BTRFS_SEND_C_WRITE);
5008 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5012 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5013 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5014 ret = put_file_data(sctx, offset, len);
5018 ret = send_cmd(sctx);
5027 * Send a clone command to user space.
5029 static int send_clone(struct send_ctx *sctx,
5030 u64 offset, u32 len,
5031 struct clone_root *clone_root)
5037 btrfs_debug(sctx->send_root->fs_info,
5038 "send_clone offset=%llu, len=%d, clone_root=%llu, clone_inode=%llu, clone_offset=%llu",
5039 offset, len, clone_root->root->root_key.objectid,
5040 clone_root->ino, clone_root->offset);
5042 p = fs_path_alloc();
5046 ret = begin_cmd(sctx, BTRFS_SEND_C_CLONE);
5050 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5054 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5055 TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_LEN, len);
5056 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5058 if (clone_root->root == sctx->send_root) {
5059 ret = get_inode_info(sctx->send_root, clone_root->ino, NULL,
5060 &gen, NULL, NULL, NULL, NULL, NULL);
5063 ret = get_cur_path(sctx, clone_root->ino, gen, p);
5065 ret = get_inode_path(clone_root->root, clone_root->ino, p);
5071 * If the parent we're using has a received_uuid set then use that as
5072 * our clone source as that is what we will look for when doing a
5075 * This covers the case that we create a snapshot off of a received
5076 * subvolume and then use that as the parent and try to receive on a
5079 if (!btrfs_is_empty_uuid(clone_root->root->root_item.received_uuid))
5080 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
5081 clone_root->root->root_item.received_uuid);
5083 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
5084 clone_root->root->root_item.uuid);
5085 TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_CTRANSID,
5086 btrfs_root_ctransid(&clone_root->root->root_item));
5087 TLV_PUT_PATH(sctx, BTRFS_SEND_A_CLONE_PATH, p);
5088 TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_OFFSET,
5089 clone_root->offset);
5091 ret = send_cmd(sctx);
5100 * Send an update extent command to user space.
5102 static int send_update_extent(struct send_ctx *sctx,
5103 u64 offset, u32 len)
5108 p = fs_path_alloc();
5112 ret = begin_cmd(sctx, BTRFS_SEND_C_UPDATE_EXTENT);
5116 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5120 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5121 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5122 TLV_PUT_U64(sctx, BTRFS_SEND_A_SIZE, len);
5124 ret = send_cmd(sctx);
5132 static int send_hole(struct send_ctx *sctx, u64 end)
5134 struct fs_path *p = NULL;
5135 u64 read_size = max_send_read_size(sctx);
5136 u64 offset = sctx->cur_inode_last_extent;
5140 * A hole that starts at EOF or beyond it. Since we do not yet support
5141 * fallocate (for extent preallocation and hole punching), sending a
5142 * write of zeroes starting at EOF or beyond would later require issuing
5143 * a truncate operation which would undo the write and achieve nothing.
5145 if (offset >= sctx->cur_inode_size)
5149 * Don't go beyond the inode's i_size due to prealloc extents that start
5152 end = min_t(u64, end, sctx->cur_inode_size);
5154 if (sctx->flags & BTRFS_SEND_FLAG_NO_FILE_DATA)
5155 return send_update_extent(sctx, offset, end - offset);
5157 p = fs_path_alloc();
5160 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5162 goto tlv_put_failure;
5163 while (offset < end) {
5164 u64 len = min(end - offset, read_size);
5166 ret = begin_cmd(sctx, BTRFS_SEND_C_WRITE);
5169 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5170 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5171 ret = put_data_header(sctx, len);
5174 memset(sctx->send_buf + sctx->send_size, 0, len);
5175 sctx->send_size += len;
5176 ret = send_cmd(sctx);
5181 sctx->cur_inode_next_write_offset = offset;
5187 static int send_encoded_inline_extent(struct send_ctx *sctx,
5188 struct btrfs_path *path, u64 offset,
5191 struct btrfs_root *root = sctx->send_root;
5192 struct btrfs_fs_info *fs_info = root->fs_info;
5193 struct inode *inode;
5194 struct fs_path *fspath;
5195 struct extent_buffer *leaf = path->nodes[0];
5196 struct btrfs_key key;
5197 struct btrfs_file_extent_item *ei;
5202 inode = btrfs_iget(fs_info->sb, sctx->cur_ino, root);
5204 return PTR_ERR(inode);
5206 fspath = fs_path_alloc();
5212 ret = begin_cmd(sctx, BTRFS_SEND_C_ENCODED_WRITE);
5216 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, fspath);
5220 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5221 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
5222 ram_bytes = btrfs_file_extent_ram_bytes(leaf, ei);
5223 inline_size = btrfs_file_extent_inline_item_len(leaf, path->slots[0]);
5225 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, fspath);
5226 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5227 TLV_PUT_U64(sctx, BTRFS_SEND_A_UNENCODED_FILE_LEN,
5228 min(key.offset + ram_bytes - offset, len));
5229 TLV_PUT_U64(sctx, BTRFS_SEND_A_UNENCODED_LEN, ram_bytes);
5230 TLV_PUT_U64(sctx, BTRFS_SEND_A_UNENCODED_OFFSET, offset - key.offset);
5231 ret = btrfs_encoded_io_compression_from_extent(fs_info,
5232 btrfs_file_extent_compression(leaf, ei));
5235 TLV_PUT_U32(sctx, BTRFS_SEND_A_COMPRESSION, ret);
5237 ret = put_data_header(sctx, inline_size);
5240 read_extent_buffer(leaf, sctx->send_buf + sctx->send_size,
5241 btrfs_file_extent_inline_start(ei), inline_size);
5242 sctx->send_size += inline_size;
5244 ret = send_cmd(sctx);
5248 fs_path_free(fspath);
5253 static int send_encoded_extent(struct send_ctx *sctx, struct btrfs_path *path,
5254 u64 offset, u64 len)
5256 struct btrfs_root *root = sctx->send_root;
5257 struct btrfs_fs_info *fs_info = root->fs_info;
5258 struct inode *inode;
5259 struct fs_path *fspath;
5260 struct extent_buffer *leaf = path->nodes[0];
5261 struct btrfs_key key;
5262 struct btrfs_file_extent_item *ei;
5263 u64 disk_bytenr, disk_num_bytes;
5265 struct btrfs_cmd_header *hdr;
5269 inode = btrfs_iget(fs_info->sb, sctx->cur_ino, root);
5271 return PTR_ERR(inode);
5273 fspath = fs_path_alloc();
5279 ret = begin_cmd(sctx, BTRFS_SEND_C_ENCODED_WRITE);
5283 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, fspath);
5287 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5288 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
5289 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
5290 disk_num_bytes = btrfs_file_extent_disk_num_bytes(leaf, ei);
5292 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, fspath);
5293 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5294 TLV_PUT_U64(sctx, BTRFS_SEND_A_UNENCODED_FILE_LEN,
5295 min(key.offset + btrfs_file_extent_num_bytes(leaf, ei) - offset,
5297 TLV_PUT_U64(sctx, BTRFS_SEND_A_UNENCODED_LEN,
5298 btrfs_file_extent_ram_bytes(leaf, ei));
5299 TLV_PUT_U64(sctx, BTRFS_SEND_A_UNENCODED_OFFSET,
5300 offset - key.offset + btrfs_file_extent_offset(leaf, ei));
5301 ret = btrfs_encoded_io_compression_from_extent(fs_info,
5302 btrfs_file_extent_compression(leaf, ei));
5305 TLV_PUT_U32(sctx, BTRFS_SEND_A_COMPRESSION, ret);
5306 TLV_PUT_U32(sctx, BTRFS_SEND_A_ENCRYPTION, 0);
5308 ret = put_data_header(sctx, disk_num_bytes);
5313 * We want to do I/O directly into the send buffer, so get the next page
5314 * boundary in the send buffer. This means that there may be a gap
5315 * between the beginning of the command and the file data.
5317 data_offset = ALIGN(sctx->send_size, PAGE_SIZE);
5318 if (data_offset > sctx->send_max_size ||
5319 sctx->send_max_size - data_offset < disk_num_bytes) {
5325 * Note that send_buf is a mapping of send_buf_pages, so this is really
5326 * reading into send_buf.
5328 ret = btrfs_encoded_read_regular_fill_pages(BTRFS_I(inode), offset,
5329 disk_bytenr, disk_num_bytes,
5330 sctx->send_buf_pages +
5331 (data_offset >> PAGE_SHIFT));
5335 hdr = (struct btrfs_cmd_header *)sctx->send_buf;
5336 hdr->len = cpu_to_le32(sctx->send_size + disk_num_bytes - sizeof(*hdr));
5338 crc = btrfs_crc32c(0, sctx->send_buf, sctx->send_size);
5339 crc = btrfs_crc32c(crc, sctx->send_buf + data_offset, disk_num_bytes);
5340 hdr->crc = cpu_to_le32(crc);
5342 ret = write_buf(sctx->send_filp, sctx->send_buf, sctx->send_size,
5345 ret = write_buf(sctx->send_filp, sctx->send_buf + data_offset,
5346 disk_num_bytes, &sctx->send_off);
5348 sctx->send_size = 0;
5349 sctx->put_data = false;
5353 fs_path_free(fspath);
5358 static int send_extent_data(struct send_ctx *sctx, struct btrfs_path *path,
5359 const u64 offset, const u64 len)
5361 const u64 end = offset + len;
5362 struct extent_buffer *leaf = path->nodes[0];
5363 struct btrfs_file_extent_item *ei;
5364 u64 read_size = max_send_read_size(sctx);
5367 if (sctx->flags & BTRFS_SEND_FLAG_NO_FILE_DATA)
5368 return send_update_extent(sctx, offset, len);
5370 ei = btrfs_item_ptr(leaf, path->slots[0],
5371 struct btrfs_file_extent_item);
5372 if ((sctx->flags & BTRFS_SEND_FLAG_COMPRESSED) &&
5373 btrfs_file_extent_compression(leaf, ei) != BTRFS_COMPRESS_NONE) {
5374 bool is_inline = (btrfs_file_extent_type(leaf, ei) ==
5375 BTRFS_FILE_EXTENT_INLINE);
5378 * Send the compressed extent unless the compressed data is
5379 * larger than the decompressed data. This can happen if we're
5380 * not sending the entire extent, either because it has been
5381 * partially overwritten/truncated or because this is a part of
5382 * the extent that we couldn't clone in clone_range().
5385 btrfs_file_extent_inline_item_len(leaf,
5386 path->slots[0]) <= len) {
5387 return send_encoded_inline_extent(sctx, path, offset,
5389 } else if (!is_inline &&
5390 btrfs_file_extent_disk_num_bytes(leaf, ei) <= len) {
5391 return send_encoded_extent(sctx, path, offset, len);
5395 if (sctx->cur_inode == NULL) {
5396 struct btrfs_root *root = sctx->send_root;
5398 sctx->cur_inode = btrfs_iget(root->fs_info->sb, sctx->cur_ino, root);
5399 if (IS_ERR(sctx->cur_inode)) {
5400 int err = PTR_ERR(sctx->cur_inode);
5402 sctx->cur_inode = NULL;
5405 memset(&sctx->ra, 0, sizeof(struct file_ra_state));
5406 file_ra_state_init(&sctx->ra, sctx->cur_inode->i_mapping);
5409 * It's very likely there are no pages from this inode in the page
5410 * cache, so after reading extents and sending their data, we clean
5411 * the page cache to avoid trashing the page cache (adding pressure
5412 * to the page cache and forcing eviction of other data more useful
5413 * for applications).
5415 * We decide if we should clean the page cache simply by checking
5416 * if the inode's mapping nrpages is 0 when we first open it, and
5417 * not by using something like filemap_range_has_page() before
5418 * reading an extent because when we ask the readahead code to
5419 * read a given file range, it may (and almost always does) read
5420 * pages from beyond that range (see the documentation for
5421 * page_cache_sync_readahead()), so it would not be reliable,
5422 * because after reading the first extent future calls to
5423 * filemap_range_has_page() would return true because the readahead
5424 * on the previous extent resulted in reading pages of the current
5427 sctx->clean_page_cache = (sctx->cur_inode->i_mapping->nrpages == 0);
5428 sctx->page_cache_clear_start = round_down(offset, PAGE_SIZE);
5431 while (sent < len) {
5432 u64 size = min(len - sent, read_size);
5435 ret = send_write(sctx, offset + sent, size);
5441 if (sctx->clean_page_cache && IS_ALIGNED(end, PAGE_SIZE)) {
5443 * Always operate only on ranges that are a multiple of the page
5444 * size. This is not only to prevent zeroing parts of a page in
5445 * the case of subpage sector size, but also to guarantee we evict
5446 * pages, as passing a range that is smaller than page size does
5447 * not evict the respective page (only zeroes part of its content).
5449 * Always start from the end offset of the last range cleared.
5450 * This is because the readahead code may (and very often does)
5451 * reads pages beyond the range we request for readahead. So if
5452 * we have an extent layout like this:
5454 * [ extent A ] [ extent B ] [ extent C ]
5456 * When we ask page_cache_sync_readahead() to read extent A, it
5457 * may also trigger reads for pages of extent B. If we are doing
5458 * an incremental send and extent B has not changed between the
5459 * parent and send snapshots, some or all of its pages may end
5460 * up being read and placed in the page cache. So when truncating
5461 * the page cache we always start from the end offset of the
5462 * previously processed extent up to the end of the current
5465 truncate_inode_pages_range(&sctx->cur_inode->i_data,
5466 sctx->page_cache_clear_start,
5468 sctx->page_cache_clear_start = end;
5475 * Search for a capability xattr related to sctx->cur_ino. If the capability is
5476 * found, call send_set_xattr function to emit it.
5478 * Return 0 if there isn't a capability, or when the capability was emitted
5479 * successfully, or < 0 if an error occurred.
5481 static int send_capabilities(struct send_ctx *sctx)
5483 struct fs_path *fspath = NULL;
5484 struct btrfs_path *path;
5485 struct btrfs_dir_item *di;
5486 struct extent_buffer *leaf;
5487 unsigned long data_ptr;
5492 path = alloc_path_for_send();
5496 di = btrfs_lookup_xattr(NULL, sctx->send_root, path, sctx->cur_ino,
5497 XATTR_NAME_CAPS, strlen(XATTR_NAME_CAPS), 0);
5499 /* There is no xattr for this inode */
5501 } else if (IS_ERR(di)) {
5506 leaf = path->nodes[0];
5507 buf_len = btrfs_dir_data_len(leaf, di);
5509 fspath = fs_path_alloc();
5510 buf = kmalloc(buf_len, GFP_KERNEL);
5511 if (!fspath || !buf) {
5516 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, fspath);
5520 data_ptr = (unsigned long)(di + 1) + btrfs_dir_name_len(leaf, di);
5521 read_extent_buffer(leaf, buf, data_ptr, buf_len);
5523 ret = send_set_xattr(sctx, fspath, XATTR_NAME_CAPS,
5524 strlen(XATTR_NAME_CAPS), buf, buf_len);
5527 fs_path_free(fspath);
5528 btrfs_free_path(path);
5532 static int clone_range(struct send_ctx *sctx, struct btrfs_path *dst_path,
5533 struct clone_root *clone_root, const u64 disk_byte,
5534 u64 data_offset, u64 offset, u64 len)
5536 struct btrfs_path *path;
5537 struct btrfs_key key;
5539 u64 clone_src_i_size = 0;
5542 * Prevent cloning from a zero offset with a length matching the sector
5543 * size because in some scenarios this will make the receiver fail.
5545 * For example, if in the source filesystem the extent at offset 0
5546 * has a length of sectorsize and it was written using direct IO, then
5547 * it can never be an inline extent (even if compression is enabled).
5548 * Then this extent can be cloned in the original filesystem to a non
5549 * zero file offset, but it may not be possible to clone in the
5550 * destination filesystem because it can be inlined due to compression
5551 * on the destination filesystem (as the receiver's write operations are
5552 * always done using buffered IO). The same happens when the original
5553 * filesystem does not have compression enabled but the destination
5556 if (clone_root->offset == 0 &&
5557 len == sctx->send_root->fs_info->sectorsize)
5558 return send_extent_data(sctx, dst_path, offset, len);
5560 path = alloc_path_for_send();
5565 * There are inodes that have extents that lie behind its i_size. Don't
5566 * accept clones from these extents.
5568 ret = __get_inode_info(clone_root->root, path, clone_root->ino,
5569 &clone_src_i_size, NULL, NULL, NULL, NULL, NULL,
5571 btrfs_release_path(path);
5576 * We can't send a clone operation for the entire range if we find
5577 * extent items in the respective range in the source file that
5578 * refer to different extents or if we find holes.
5579 * So check for that and do a mix of clone and regular write/copy
5580 * operations if needed.
5584 * mkfs.btrfs -f /dev/sda
5585 * mount /dev/sda /mnt
5586 * xfs_io -f -c "pwrite -S 0xaa 0K 100K" /mnt/foo
5587 * cp --reflink=always /mnt/foo /mnt/bar
5588 * xfs_io -c "pwrite -S 0xbb 50K 50K" /mnt/foo
5589 * btrfs subvolume snapshot -r /mnt /mnt/snap
5591 * If when we send the snapshot and we are processing file bar (which
5592 * has a higher inode number than foo) we blindly send a clone operation
5593 * for the [0, 100K[ range from foo to bar, the receiver ends up getting
5594 * a file bar that matches the content of file foo - iow, doesn't match
5595 * the content from bar in the original filesystem.
5597 key.objectid = clone_root->ino;
5598 key.type = BTRFS_EXTENT_DATA_KEY;
5599 key.offset = clone_root->offset;
5600 ret = btrfs_search_slot(NULL, clone_root->root, &key, path, 0, 0);
5603 if (ret > 0 && path->slots[0] > 0) {
5604 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1);
5605 if (key.objectid == clone_root->ino &&
5606 key.type == BTRFS_EXTENT_DATA_KEY)
5611 struct extent_buffer *leaf = path->nodes[0];
5612 int slot = path->slots[0];
5613 struct btrfs_file_extent_item *ei;
5617 u64 clone_data_offset;
5619 if (slot >= btrfs_header_nritems(leaf)) {
5620 ret = btrfs_next_leaf(clone_root->root, path);
5628 btrfs_item_key_to_cpu(leaf, &key, slot);
5631 * We might have an implicit trailing hole (NO_HOLES feature
5632 * enabled). We deal with it after leaving this loop.
5634 if (key.objectid != clone_root->ino ||
5635 key.type != BTRFS_EXTENT_DATA_KEY)
5638 ei = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5639 type = btrfs_file_extent_type(leaf, ei);
5640 if (type == BTRFS_FILE_EXTENT_INLINE) {
5641 ext_len = btrfs_file_extent_ram_bytes(leaf, ei);
5642 ext_len = PAGE_ALIGN(ext_len);
5644 ext_len = btrfs_file_extent_num_bytes(leaf, ei);
5647 if (key.offset + ext_len <= clone_root->offset)
5650 if (key.offset > clone_root->offset) {
5651 /* Implicit hole, NO_HOLES feature enabled. */
5652 u64 hole_len = key.offset - clone_root->offset;
5656 ret = send_extent_data(sctx, dst_path, offset,
5665 clone_root->offset += hole_len;
5666 data_offset += hole_len;
5669 if (key.offset >= clone_root->offset + len)
5672 if (key.offset >= clone_src_i_size)
5675 if (key.offset + ext_len > clone_src_i_size)
5676 ext_len = clone_src_i_size - key.offset;
5678 clone_data_offset = btrfs_file_extent_offset(leaf, ei);
5679 if (btrfs_file_extent_disk_bytenr(leaf, ei) == disk_byte) {
5680 clone_root->offset = key.offset;
5681 if (clone_data_offset < data_offset &&
5682 clone_data_offset + ext_len > data_offset) {
5685 extent_offset = data_offset - clone_data_offset;
5686 ext_len -= extent_offset;
5687 clone_data_offset += extent_offset;
5688 clone_root->offset += extent_offset;
5692 clone_len = min_t(u64, ext_len, len);
5694 if (btrfs_file_extent_disk_bytenr(leaf, ei) == disk_byte &&
5695 clone_data_offset == data_offset) {
5696 const u64 src_end = clone_root->offset + clone_len;
5697 const u64 sectorsize = SZ_64K;
5700 * We can't clone the last block, when its size is not
5701 * sector size aligned, into the middle of a file. If we
5702 * do so, the receiver will get a failure (-EINVAL) when
5703 * trying to clone or will silently corrupt the data in
5704 * the destination file if it's on a kernel without the
5705 * fix introduced by commit ac765f83f1397646
5706 * ("Btrfs: fix data corruption due to cloning of eof
5709 * So issue a clone of the aligned down range plus a
5710 * regular write for the eof block, if we hit that case.
5712 * Also, we use the maximum possible sector size, 64K,
5713 * because we don't know what's the sector size of the
5714 * filesystem that receives the stream, so we have to
5715 * assume the largest possible sector size.
5717 if (src_end == clone_src_i_size &&
5718 !IS_ALIGNED(src_end, sectorsize) &&
5719 offset + clone_len < sctx->cur_inode_size) {
5722 slen = ALIGN_DOWN(src_end - clone_root->offset,
5725 ret = send_clone(sctx, offset, slen,
5730 ret = send_extent_data(sctx, dst_path,
5734 ret = send_clone(sctx, offset, clone_len,
5738 ret = send_extent_data(sctx, dst_path, offset,
5748 offset += clone_len;
5749 clone_root->offset += clone_len;
5752 * If we are cloning from the file we are currently processing,
5753 * and using the send root as the clone root, we must stop once
5754 * the current clone offset reaches the current eof of the file
5755 * at the receiver, otherwise we would issue an invalid clone
5756 * operation (source range going beyond eof) and cause the
5757 * receiver to fail. So if we reach the current eof, bail out
5758 * and fallback to a regular write.
5760 if (clone_root->root == sctx->send_root &&
5761 clone_root->ino == sctx->cur_ino &&
5762 clone_root->offset >= sctx->cur_inode_next_write_offset)
5765 data_offset += clone_len;
5771 ret = send_extent_data(sctx, dst_path, offset, len);
5775 btrfs_free_path(path);
5779 static int send_write_or_clone(struct send_ctx *sctx,
5780 struct btrfs_path *path,
5781 struct btrfs_key *key,
5782 struct clone_root *clone_root)
5785 u64 offset = key->offset;
5787 u64 bs = sctx->send_root->fs_info->sb->s_blocksize;
5789 end = min_t(u64, btrfs_file_extent_end(path), sctx->cur_inode_size);
5793 if (clone_root && IS_ALIGNED(end, bs)) {
5794 struct btrfs_file_extent_item *ei;
5798 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
5799 struct btrfs_file_extent_item);
5800 disk_byte = btrfs_file_extent_disk_bytenr(path->nodes[0], ei);
5801 data_offset = btrfs_file_extent_offset(path->nodes[0], ei);
5802 ret = clone_range(sctx, path, clone_root, disk_byte,
5803 data_offset, offset, end - offset);
5805 ret = send_extent_data(sctx, path, offset, end - offset);
5807 sctx->cur_inode_next_write_offset = end;
5811 static int is_extent_unchanged(struct send_ctx *sctx,
5812 struct btrfs_path *left_path,
5813 struct btrfs_key *ekey)
5816 struct btrfs_key key;
5817 struct btrfs_path *path = NULL;
5818 struct extent_buffer *eb;
5820 struct btrfs_key found_key;
5821 struct btrfs_file_extent_item *ei;
5826 u64 left_offset_fixed;
5834 path = alloc_path_for_send();
5838 eb = left_path->nodes[0];
5839 slot = left_path->slots[0];
5840 ei = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
5841 left_type = btrfs_file_extent_type(eb, ei);
5843 if (left_type != BTRFS_FILE_EXTENT_REG) {
5847 left_disknr = btrfs_file_extent_disk_bytenr(eb, ei);
5848 left_len = btrfs_file_extent_num_bytes(eb, ei);
5849 left_offset = btrfs_file_extent_offset(eb, ei);
5850 left_gen = btrfs_file_extent_generation(eb, ei);
5853 * Following comments will refer to these graphics. L is the left
5854 * extents which we are checking at the moment. 1-8 are the right
5855 * extents that we iterate.
5858 * |-1-|-2a-|-3-|-4-|-5-|-6-|
5861 * |--1--|-2b-|...(same as above)
5863 * Alternative situation. Happens on files where extents got split.
5865 * |-----------7-----------|-6-|
5867 * Alternative situation. Happens on files which got larger.
5870 * Nothing follows after 8.
5873 key.objectid = ekey->objectid;
5874 key.type = BTRFS_EXTENT_DATA_KEY;
5875 key.offset = ekey->offset;
5876 ret = btrfs_search_slot_for_read(sctx->parent_root, &key, path, 0, 0);
5885 * Handle special case where the right side has no extents at all.
5887 eb = path->nodes[0];
5888 slot = path->slots[0];
5889 btrfs_item_key_to_cpu(eb, &found_key, slot);
5890 if (found_key.objectid != key.objectid ||
5891 found_key.type != key.type) {
5892 /* If we're a hole then just pretend nothing changed */
5893 ret = (left_disknr) ? 0 : 1;
5898 * We're now on 2a, 2b or 7.
5901 while (key.offset < ekey->offset + left_len) {
5902 ei = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
5903 right_type = btrfs_file_extent_type(eb, ei);
5904 if (right_type != BTRFS_FILE_EXTENT_REG &&
5905 right_type != BTRFS_FILE_EXTENT_INLINE) {
5910 if (right_type == BTRFS_FILE_EXTENT_INLINE) {
5911 right_len = btrfs_file_extent_ram_bytes(eb, ei);
5912 right_len = PAGE_ALIGN(right_len);
5914 right_len = btrfs_file_extent_num_bytes(eb, ei);
5918 * Are we at extent 8? If yes, we know the extent is changed.
5919 * This may only happen on the first iteration.
5921 if (found_key.offset + right_len <= ekey->offset) {
5922 /* If we're a hole just pretend nothing changed */
5923 ret = (left_disknr) ? 0 : 1;
5928 * We just wanted to see if when we have an inline extent, what
5929 * follows it is a regular extent (wanted to check the above
5930 * condition for inline extents too). This should normally not
5931 * happen but it's possible for example when we have an inline
5932 * compressed extent representing data with a size matching
5933 * the page size (currently the same as sector size).
5935 if (right_type == BTRFS_FILE_EXTENT_INLINE) {
5940 right_disknr = btrfs_file_extent_disk_bytenr(eb, ei);
5941 right_offset = btrfs_file_extent_offset(eb, ei);
5942 right_gen = btrfs_file_extent_generation(eb, ei);
5944 left_offset_fixed = left_offset;
5945 if (key.offset < ekey->offset) {
5946 /* Fix the right offset for 2a and 7. */
5947 right_offset += ekey->offset - key.offset;
5949 /* Fix the left offset for all behind 2a and 2b */
5950 left_offset_fixed += key.offset - ekey->offset;
5954 * Check if we have the same extent.
5956 if (left_disknr != right_disknr ||
5957 left_offset_fixed != right_offset ||
5958 left_gen != right_gen) {
5964 * Go to the next extent.
5966 ret = btrfs_next_item(sctx->parent_root, path);
5970 eb = path->nodes[0];
5971 slot = path->slots[0];
5972 btrfs_item_key_to_cpu(eb, &found_key, slot);
5974 if (ret || found_key.objectid != key.objectid ||
5975 found_key.type != key.type) {
5976 key.offset += right_len;
5979 if (found_key.offset != key.offset + right_len) {
5987 * We're now behind the left extent (treat as unchanged) or at the end
5988 * of the right side (treat as changed).
5990 if (key.offset >= ekey->offset + left_len)
5997 btrfs_free_path(path);
6001 static int get_last_extent(struct send_ctx *sctx, u64 offset)
6003 struct btrfs_path *path;
6004 struct btrfs_root *root = sctx->send_root;
6005 struct btrfs_key key;
6008 path = alloc_path_for_send();
6012 sctx->cur_inode_last_extent = 0;
6014 key.objectid = sctx->cur_ino;
6015 key.type = BTRFS_EXTENT_DATA_KEY;
6016 key.offset = offset;
6017 ret = btrfs_search_slot_for_read(root, &key, path, 0, 1);
6021 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
6022 if (key.objectid != sctx->cur_ino || key.type != BTRFS_EXTENT_DATA_KEY)
6025 sctx->cur_inode_last_extent = btrfs_file_extent_end(path);
6027 btrfs_free_path(path);
6031 static int range_is_hole_in_parent(struct send_ctx *sctx,
6035 struct btrfs_path *path;
6036 struct btrfs_key key;
6037 struct btrfs_root *root = sctx->parent_root;
6038 u64 search_start = start;
6041 path = alloc_path_for_send();
6045 key.objectid = sctx->cur_ino;
6046 key.type = BTRFS_EXTENT_DATA_KEY;
6047 key.offset = search_start;
6048 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6051 if (ret > 0 && path->slots[0] > 0)
6054 while (search_start < end) {
6055 struct extent_buffer *leaf = path->nodes[0];
6056 int slot = path->slots[0];
6057 struct btrfs_file_extent_item *fi;
6060 if (slot >= btrfs_header_nritems(leaf)) {
6061 ret = btrfs_next_leaf(root, path);
6069 btrfs_item_key_to_cpu(leaf, &key, slot);
6070 if (key.objectid < sctx->cur_ino ||
6071 key.type < BTRFS_EXTENT_DATA_KEY)
6073 if (key.objectid > sctx->cur_ino ||
6074 key.type > BTRFS_EXTENT_DATA_KEY ||
6078 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6079 extent_end = btrfs_file_extent_end(path);
6080 if (extent_end <= start)
6082 if (btrfs_file_extent_disk_bytenr(leaf, fi) == 0) {
6083 search_start = extent_end;
6093 btrfs_free_path(path);
6097 static int maybe_send_hole(struct send_ctx *sctx, struct btrfs_path *path,
6098 struct btrfs_key *key)
6102 if (sctx->cur_ino != key->objectid || !need_send_hole(sctx))
6105 if (sctx->cur_inode_last_extent == (u64)-1) {
6106 ret = get_last_extent(sctx, key->offset - 1);
6111 if (path->slots[0] == 0 &&
6112 sctx->cur_inode_last_extent < key->offset) {
6114 * We might have skipped entire leafs that contained only
6115 * file extent items for our current inode. These leafs have
6116 * a generation number smaller (older) than the one in the
6117 * current leaf and the leaf our last extent came from, and
6118 * are located between these 2 leafs.
6120 ret = get_last_extent(sctx, key->offset - 1);
6125 if (sctx->cur_inode_last_extent < key->offset) {
6126 ret = range_is_hole_in_parent(sctx,
6127 sctx->cur_inode_last_extent,
6132 ret = send_hole(sctx, key->offset);
6136 sctx->cur_inode_last_extent = btrfs_file_extent_end(path);
6140 static int process_extent(struct send_ctx *sctx,
6141 struct btrfs_path *path,
6142 struct btrfs_key *key)
6144 struct clone_root *found_clone = NULL;
6147 if (S_ISLNK(sctx->cur_inode_mode))
6150 if (sctx->parent_root && !sctx->cur_inode_new) {
6151 ret = is_extent_unchanged(sctx, path, key);
6159 struct btrfs_file_extent_item *ei;
6162 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
6163 struct btrfs_file_extent_item);
6164 type = btrfs_file_extent_type(path->nodes[0], ei);
6165 if (type == BTRFS_FILE_EXTENT_PREALLOC ||
6166 type == BTRFS_FILE_EXTENT_REG) {
6168 * The send spec does not have a prealloc command yet,
6169 * so just leave a hole for prealloc'ed extents until
6170 * we have enough commands queued up to justify rev'ing
6173 if (type == BTRFS_FILE_EXTENT_PREALLOC) {
6178 /* Have a hole, just skip it. */
6179 if (btrfs_file_extent_disk_bytenr(path->nodes[0], ei) == 0) {
6186 ret = find_extent_clone(sctx, path, key->objectid, key->offset,
6187 sctx->cur_inode_size, &found_clone);
6188 if (ret != -ENOENT && ret < 0)
6191 ret = send_write_or_clone(sctx, path, key, found_clone);
6195 ret = maybe_send_hole(sctx, path, key);
6200 static int process_all_extents(struct send_ctx *sctx)
6204 struct btrfs_root *root;
6205 struct btrfs_path *path;
6206 struct btrfs_key key;
6207 struct btrfs_key found_key;
6209 root = sctx->send_root;
6210 path = alloc_path_for_send();
6214 key.objectid = sctx->cmp_key->objectid;
6215 key.type = BTRFS_EXTENT_DATA_KEY;
6217 btrfs_for_each_slot(root, &key, &found_key, path, iter_ret) {
6218 if (found_key.objectid != key.objectid ||
6219 found_key.type != key.type) {
6224 ret = process_extent(sctx, path, &found_key);
6228 /* Catch error found during iteration */
6232 btrfs_free_path(path);
6236 static int process_recorded_refs_if_needed(struct send_ctx *sctx, int at_end,
6238 int *refs_processed)
6242 if (sctx->cur_ino == 0)
6244 if (!at_end && sctx->cur_ino == sctx->cmp_key->objectid &&
6245 sctx->cmp_key->type <= BTRFS_INODE_EXTREF_KEY)
6247 if (list_empty(&sctx->new_refs) && list_empty(&sctx->deleted_refs))
6250 ret = process_recorded_refs(sctx, pending_move);
6254 *refs_processed = 1;
6259 static int finish_inode_if_needed(struct send_ctx *sctx, int at_end)
6272 bool need_fileattr = false;
6273 int need_truncate = 1;
6274 int pending_move = 0;
6275 int refs_processed = 0;
6277 if (sctx->ignore_cur_inode)
6280 ret = process_recorded_refs_if_needed(sctx, at_end, &pending_move,
6286 * We have processed the refs and thus need to advance send_progress.
6287 * Now, calls to get_cur_xxx will take the updated refs of the current
6288 * inode into account.
6290 * On the other hand, if our current inode is a directory and couldn't
6291 * be moved/renamed because its parent was renamed/moved too and it has
6292 * a higher inode number, we can only move/rename our current inode
6293 * after we moved/renamed its parent. Therefore in this case operate on
6294 * the old path (pre move/rename) of our current inode, and the
6295 * move/rename will be performed later.
6297 if (refs_processed && !pending_move)
6298 sctx->send_progress = sctx->cur_ino + 1;
6300 if (sctx->cur_ino == 0 || sctx->cur_inode_deleted)
6302 if (!at_end && sctx->cmp_key->objectid == sctx->cur_ino)
6305 ret = get_inode_info(sctx->send_root, sctx->cur_ino, NULL, NULL,
6306 &left_mode, &left_uid, &left_gid, NULL, &left_fileattr);
6310 if (!sctx->parent_root || sctx->cur_inode_new) {
6312 if (!S_ISLNK(sctx->cur_inode_mode))
6314 if (sctx->cur_inode_next_write_offset == sctx->cur_inode_size)
6319 ret = get_inode_info(sctx->parent_root, sctx->cur_ino,
6320 &old_size, NULL, &right_mode, &right_uid,
6321 &right_gid, NULL, &right_fileattr);
6325 if (left_uid != right_uid || left_gid != right_gid)
6327 if (!S_ISLNK(sctx->cur_inode_mode) && left_mode != right_mode)
6329 if (!S_ISLNK(sctx->cur_inode_mode) && left_fileattr != right_fileattr)
6330 need_fileattr = true;
6331 if ((old_size == sctx->cur_inode_size) ||
6332 (sctx->cur_inode_size > old_size &&
6333 sctx->cur_inode_next_write_offset == sctx->cur_inode_size))
6337 if (S_ISREG(sctx->cur_inode_mode)) {
6338 if (need_send_hole(sctx)) {
6339 if (sctx->cur_inode_last_extent == (u64)-1 ||
6340 sctx->cur_inode_last_extent <
6341 sctx->cur_inode_size) {
6342 ret = get_last_extent(sctx, (u64)-1);
6346 if (sctx->cur_inode_last_extent <
6347 sctx->cur_inode_size) {
6348 ret = send_hole(sctx, sctx->cur_inode_size);
6353 if (need_truncate) {
6354 ret = send_truncate(sctx, sctx->cur_ino,
6355 sctx->cur_inode_gen,
6356 sctx->cur_inode_size);
6363 ret = send_chown(sctx, sctx->cur_ino, sctx->cur_inode_gen,
6364 left_uid, left_gid);
6369 ret = send_chmod(sctx, sctx->cur_ino, sctx->cur_inode_gen,
6374 if (need_fileattr) {
6375 ret = send_fileattr(sctx, sctx->cur_ino, sctx->cur_inode_gen,
6381 ret = send_capabilities(sctx);
6386 * If other directory inodes depended on our current directory
6387 * inode's move/rename, now do their move/rename operations.
6389 if (!is_waiting_for_move(sctx, sctx->cur_ino)) {
6390 ret = apply_children_dir_moves(sctx);
6394 * Need to send that every time, no matter if it actually
6395 * changed between the two trees as we have done changes to
6396 * the inode before. If our inode is a directory and it's
6397 * waiting to be moved/renamed, we will send its utimes when
6398 * it's moved/renamed, therefore we don't need to do it here.
6400 sctx->send_progress = sctx->cur_ino + 1;
6401 ret = send_utimes(sctx, sctx->cur_ino, sctx->cur_inode_gen);
6410 struct parent_paths_ctx {
6411 struct list_head *refs;
6412 struct send_ctx *sctx;
6415 static int record_parent_ref(int num, u64 dir, int index, struct fs_path *name,
6418 struct parent_paths_ctx *ppctx = ctx;
6421 * Pass 0 as the generation for the directory, we don't care about it
6422 * here as we have no new references to add, we just want to delete all
6423 * references for an inode.
6425 return record_ref_in_tree(&ppctx->sctx->rbtree_deleted_refs, ppctx->refs,
6426 name, dir, 0, ppctx->sctx);
6430 * Issue unlink operations for all paths of the current inode found in the
6433 static int btrfs_unlink_all_paths(struct send_ctx *sctx)
6435 LIST_HEAD(deleted_refs);
6436 struct btrfs_path *path;
6437 struct btrfs_root *root = sctx->parent_root;
6438 struct btrfs_key key;
6439 struct btrfs_key found_key;
6440 struct parent_paths_ctx ctx;
6444 path = alloc_path_for_send();
6448 key.objectid = sctx->cur_ino;
6449 key.type = BTRFS_INODE_REF_KEY;
6452 ctx.refs = &deleted_refs;
6455 btrfs_for_each_slot(root, &key, &found_key, path, iter_ret) {
6456 if (found_key.objectid != key.objectid)
6458 if (found_key.type != key.type &&
6459 found_key.type != BTRFS_INODE_EXTREF_KEY)
6462 ret = iterate_inode_ref(root, path, &found_key, 1,
6463 record_parent_ref, &ctx);
6467 /* Catch error found during iteration */
6473 while (!list_empty(&deleted_refs)) {
6474 struct recorded_ref *ref;
6476 ref = list_first_entry(&deleted_refs, struct recorded_ref, list);
6477 ret = send_unlink(sctx, ref->full_path);
6480 recorded_ref_free(ref);
6484 btrfs_free_path(path);
6486 __free_recorded_refs(&deleted_refs);
6490 static void close_current_inode(struct send_ctx *sctx)
6494 if (sctx->cur_inode == NULL)
6497 i_size = i_size_read(sctx->cur_inode);
6500 * If we are doing an incremental send, we may have extents between the
6501 * last processed extent and the i_size that have not been processed
6502 * because they haven't changed but we may have read some of their pages
6503 * through readahead, see the comments at send_extent_data().
6505 if (sctx->clean_page_cache && sctx->page_cache_clear_start < i_size)
6506 truncate_inode_pages_range(&sctx->cur_inode->i_data,
6507 sctx->page_cache_clear_start,
6508 round_up(i_size, PAGE_SIZE) - 1);
6510 iput(sctx->cur_inode);
6511 sctx->cur_inode = NULL;
6514 static int changed_inode(struct send_ctx *sctx,
6515 enum btrfs_compare_tree_result result)
6518 struct btrfs_key *key = sctx->cmp_key;
6519 struct btrfs_inode_item *left_ii = NULL;
6520 struct btrfs_inode_item *right_ii = NULL;
6524 close_current_inode(sctx);
6526 sctx->cur_ino = key->objectid;
6527 sctx->cur_inode_new_gen = false;
6528 sctx->cur_inode_last_extent = (u64)-1;
6529 sctx->cur_inode_next_write_offset = 0;
6530 sctx->ignore_cur_inode = false;
6533 * Set send_progress to current inode. This will tell all get_cur_xxx
6534 * functions that the current inode's refs are not updated yet. Later,
6535 * when process_recorded_refs is finished, it is set to cur_ino + 1.
6537 sctx->send_progress = sctx->cur_ino;
6539 if (result == BTRFS_COMPARE_TREE_NEW ||
6540 result == BTRFS_COMPARE_TREE_CHANGED) {
6541 left_ii = btrfs_item_ptr(sctx->left_path->nodes[0],
6542 sctx->left_path->slots[0],
6543 struct btrfs_inode_item);
6544 left_gen = btrfs_inode_generation(sctx->left_path->nodes[0],
6547 right_ii = btrfs_item_ptr(sctx->right_path->nodes[0],
6548 sctx->right_path->slots[0],
6549 struct btrfs_inode_item);
6550 right_gen = btrfs_inode_generation(sctx->right_path->nodes[0],
6553 if (result == BTRFS_COMPARE_TREE_CHANGED) {
6554 right_ii = btrfs_item_ptr(sctx->right_path->nodes[0],
6555 sctx->right_path->slots[0],
6556 struct btrfs_inode_item);
6558 right_gen = btrfs_inode_generation(sctx->right_path->nodes[0],
6562 * The cur_ino = root dir case is special here. We can't treat
6563 * the inode as deleted+reused because it would generate a
6564 * stream that tries to delete/mkdir the root dir.
6566 if (left_gen != right_gen &&
6567 sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID)
6568 sctx->cur_inode_new_gen = true;
6572 * Normally we do not find inodes with a link count of zero (orphans)
6573 * because the most common case is to create a snapshot and use it
6574 * for a send operation. However other less common use cases involve
6575 * using a subvolume and send it after turning it to RO mode just
6576 * after deleting all hard links of a file while holding an open
6577 * file descriptor against it or turning a RO snapshot into RW mode,
6578 * keep an open file descriptor against a file, delete it and then
6579 * turn the snapshot back to RO mode before using it for a send
6580 * operation. So if we find such cases, ignore the inode and all its
6581 * items completely if it's a new inode, or if it's a changed inode
6582 * make sure all its previous paths (from the parent snapshot) are all
6583 * unlinked and all other the inode items are ignored.
6585 if (result == BTRFS_COMPARE_TREE_NEW ||
6586 result == BTRFS_COMPARE_TREE_CHANGED) {
6589 nlinks = btrfs_inode_nlink(sctx->left_path->nodes[0], left_ii);
6591 sctx->ignore_cur_inode = true;
6592 if (result == BTRFS_COMPARE_TREE_CHANGED)
6593 ret = btrfs_unlink_all_paths(sctx);
6598 if (result == BTRFS_COMPARE_TREE_NEW) {
6599 sctx->cur_inode_gen = left_gen;
6600 sctx->cur_inode_new = true;
6601 sctx->cur_inode_deleted = false;
6602 sctx->cur_inode_size = btrfs_inode_size(
6603 sctx->left_path->nodes[0], left_ii);
6604 sctx->cur_inode_mode = btrfs_inode_mode(
6605 sctx->left_path->nodes[0], left_ii);
6606 sctx->cur_inode_rdev = btrfs_inode_rdev(
6607 sctx->left_path->nodes[0], left_ii);
6608 if (sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID)
6609 ret = send_create_inode_if_needed(sctx);
6610 } else if (result == BTRFS_COMPARE_TREE_DELETED) {
6611 sctx->cur_inode_gen = right_gen;
6612 sctx->cur_inode_new = false;
6613 sctx->cur_inode_deleted = true;
6614 sctx->cur_inode_size = btrfs_inode_size(
6615 sctx->right_path->nodes[0], right_ii);
6616 sctx->cur_inode_mode = btrfs_inode_mode(
6617 sctx->right_path->nodes[0], right_ii);
6618 } else if (result == BTRFS_COMPARE_TREE_CHANGED) {
6620 * We need to do some special handling in case the inode was
6621 * reported as changed with a changed generation number. This
6622 * means that the original inode was deleted and new inode
6623 * reused the same inum. So we have to treat the old inode as
6624 * deleted and the new one as new.
6626 if (sctx->cur_inode_new_gen) {
6628 * First, process the inode as if it was deleted.
6630 sctx->cur_inode_gen = right_gen;
6631 sctx->cur_inode_new = false;
6632 sctx->cur_inode_deleted = true;
6633 sctx->cur_inode_size = btrfs_inode_size(
6634 sctx->right_path->nodes[0], right_ii);
6635 sctx->cur_inode_mode = btrfs_inode_mode(
6636 sctx->right_path->nodes[0], right_ii);
6637 ret = process_all_refs(sctx,
6638 BTRFS_COMPARE_TREE_DELETED);
6643 * Now process the inode as if it was new.
6645 sctx->cur_inode_gen = left_gen;
6646 sctx->cur_inode_new = true;
6647 sctx->cur_inode_deleted = false;
6648 sctx->cur_inode_size = btrfs_inode_size(
6649 sctx->left_path->nodes[0], left_ii);
6650 sctx->cur_inode_mode = btrfs_inode_mode(
6651 sctx->left_path->nodes[0], left_ii);
6652 sctx->cur_inode_rdev = btrfs_inode_rdev(
6653 sctx->left_path->nodes[0], left_ii);
6654 ret = send_create_inode_if_needed(sctx);
6658 ret = process_all_refs(sctx, BTRFS_COMPARE_TREE_NEW);
6662 * Advance send_progress now as we did not get into
6663 * process_recorded_refs_if_needed in the new_gen case.
6665 sctx->send_progress = sctx->cur_ino + 1;
6668 * Now process all extents and xattrs of the inode as if
6669 * they were all new.
6671 ret = process_all_extents(sctx);
6674 ret = process_all_new_xattrs(sctx);
6678 sctx->cur_inode_gen = left_gen;
6679 sctx->cur_inode_new = false;
6680 sctx->cur_inode_new_gen = false;
6681 sctx->cur_inode_deleted = false;
6682 sctx->cur_inode_size = btrfs_inode_size(
6683 sctx->left_path->nodes[0], left_ii);
6684 sctx->cur_inode_mode = btrfs_inode_mode(
6685 sctx->left_path->nodes[0], left_ii);
6694 * We have to process new refs before deleted refs, but compare_trees gives us
6695 * the new and deleted refs mixed. To fix this, we record the new/deleted refs
6696 * first and later process them in process_recorded_refs.
6697 * For the cur_inode_new_gen case, we skip recording completely because
6698 * changed_inode did already initiate processing of refs. The reason for this is
6699 * that in this case, compare_tree actually compares the refs of 2 different
6700 * inodes. To fix this, process_all_refs is used in changed_inode to handle all
6701 * refs of the right tree as deleted and all refs of the left tree as new.
6703 static int changed_ref(struct send_ctx *sctx,
6704 enum btrfs_compare_tree_result result)
6708 if (sctx->cur_ino != sctx->cmp_key->objectid) {
6709 inconsistent_snapshot_error(sctx, result, "reference");
6713 if (!sctx->cur_inode_new_gen &&
6714 sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID) {
6715 if (result == BTRFS_COMPARE_TREE_NEW)
6716 ret = record_new_ref(sctx);
6717 else if (result == BTRFS_COMPARE_TREE_DELETED)
6718 ret = record_deleted_ref(sctx);
6719 else if (result == BTRFS_COMPARE_TREE_CHANGED)
6720 ret = record_changed_ref(sctx);
6727 * Process new/deleted/changed xattrs. We skip processing in the
6728 * cur_inode_new_gen case because changed_inode did already initiate processing
6729 * of xattrs. The reason is the same as in changed_ref
6731 static int changed_xattr(struct send_ctx *sctx,
6732 enum btrfs_compare_tree_result result)
6736 if (sctx->cur_ino != sctx->cmp_key->objectid) {
6737 inconsistent_snapshot_error(sctx, result, "xattr");
6741 if (!sctx->cur_inode_new_gen && !sctx->cur_inode_deleted) {
6742 if (result == BTRFS_COMPARE_TREE_NEW)
6743 ret = process_new_xattr(sctx);
6744 else if (result == BTRFS_COMPARE_TREE_DELETED)
6745 ret = process_deleted_xattr(sctx);
6746 else if (result == BTRFS_COMPARE_TREE_CHANGED)
6747 ret = process_changed_xattr(sctx);
6754 * Process new/deleted/changed extents. We skip processing in the
6755 * cur_inode_new_gen case because changed_inode did already initiate processing
6756 * of extents. The reason is the same as in changed_ref
6758 static int changed_extent(struct send_ctx *sctx,
6759 enum btrfs_compare_tree_result result)
6764 * We have found an extent item that changed without the inode item
6765 * having changed. This can happen either after relocation (where the
6766 * disk_bytenr of an extent item is replaced at
6767 * relocation.c:replace_file_extents()) or after deduplication into a
6768 * file in both the parent and send snapshots (where an extent item can
6769 * get modified or replaced with a new one). Note that deduplication
6770 * updates the inode item, but it only changes the iversion (sequence
6771 * field in the inode item) of the inode, so if a file is deduplicated
6772 * the same amount of times in both the parent and send snapshots, its
6773 * iversion becomes the same in both snapshots, whence the inode item is
6774 * the same on both snapshots.
6776 if (sctx->cur_ino != sctx->cmp_key->objectid)
6779 if (!sctx->cur_inode_new_gen && !sctx->cur_inode_deleted) {
6780 if (result != BTRFS_COMPARE_TREE_DELETED)
6781 ret = process_extent(sctx, sctx->left_path,
6788 static int dir_changed(struct send_ctx *sctx, u64 dir)
6790 u64 orig_gen, new_gen;
6793 ret = get_inode_info(sctx->send_root, dir, NULL, &new_gen, NULL, NULL,
6798 ret = get_inode_info(sctx->parent_root, dir, NULL, &orig_gen, NULL,
6799 NULL, NULL, NULL, NULL);
6803 return (orig_gen != new_gen) ? 1 : 0;
6806 static int compare_refs(struct send_ctx *sctx, struct btrfs_path *path,
6807 struct btrfs_key *key)
6809 struct btrfs_inode_extref *extref;
6810 struct extent_buffer *leaf;
6811 u64 dirid = 0, last_dirid = 0;
6818 /* Easy case, just check this one dirid */
6819 if (key->type == BTRFS_INODE_REF_KEY) {
6820 dirid = key->offset;
6822 ret = dir_changed(sctx, dirid);
6826 leaf = path->nodes[0];
6827 item_size = btrfs_item_size(leaf, path->slots[0]);
6828 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
6829 while (cur_offset < item_size) {
6830 extref = (struct btrfs_inode_extref *)(ptr +
6832 dirid = btrfs_inode_extref_parent(leaf, extref);
6833 ref_name_len = btrfs_inode_extref_name_len(leaf, extref);
6834 cur_offset += ref_name_len + sizeof(*extref);
6835 if (dirid == last_dirid)
6837 ret = dir_changed(sctx, dirid);
6847 * Updates compare related fields in sctx and simply forwards to the actual
6848 * changed_xxx functions.
6850 static int changed_cb(struct btrfs_path *left_path,
6851 struct btrfs_path *right_path,
6852 struct btrfs_key *key,
6853 enum btrfs_compare_tree_result result,
6854 struct send_ctx *sctx)
6859 * We can not hold the commit root semaphore here. This is because in
6860 * the case of sending and receiving to the same filesystem, using a
6861 * pipe, could result in a deadlock:
6863 * 1) The task running send blocks on the pipe because it's full;
6865 * 2) The task running receive, which is the only consumer of the pipe,
6866 * is waiting for a transaction commit (for example due to a space
6867 * reservation when doing a write or triggering a transaction commit
6868 * when creating a subvolume);
6870 * 3) The transaction is waiting to write lock the commit root semaphore,
6871 * but can not acquire it since it's being held at 1).
6873 * Down this call chain we write to the pipe through kernel_write().
6874 * The same type of problem can also happen when sending to a file that
6875 * is stored in the same filesystem - when reserving space for a write
6876 * into the file, we can trigger a transaction commit.
6878 * Our caller has supplied us with clones of leaves from the send and
6879 * parent roots, so we're safe here from a concurrent relocation and
6880 * further reallocation of metadata extents while we are here. Below we
6881 * also assert that the leaves are clones.
6883 lockdep_assert_not_held(&sctx->send_root->fs_info->commit_root_sem);
6886 * We always have a send root, so left_path is never NULL. We will not
6887 * have a leaf when we have reached the end of the send root but have
6888 * not yet reached the end of the parent root.
6890 if (left_path->nodes[0])
6891 ASSERT(test_bit(EXTENT_BUFFER_UNMAPPED,
6892 &left_path->nodes[0]->bflags));
6894 * When doing a full send we don't have a parent root, so right_path is
6895 * NULL. When doing an incremental send, we may have reached the end of
6896 * the parent root already, so we don't have a leaf at right_path.
6898 if (right_path && right_path->nodes[0])
6899 ASSERT(test_bit(EXTENT_BUFFER_UNMAPPED,
6900 &right_path->nodes[0]->bflags));
6902 if (result == BTRFS_COMPARE_TREE_SAME) {
6903 if (key->type == BTRFS_INODE_REF_KEY ||
6904 key->type == BTRFS_INODE_EXTREF_KEY) {
6905 ret = compare_refs(sctx, left_path, key);
6910 } else if (key->type == BTRFS_EXTENT_DATA_KEY) {
6911 return maybe_send_hole(sctx, left_path, key);
6915 result = BTRFS_COMPARE_TREE_CHANGED;
6919 sctx->left_path = left_path;
6920 sctx->right_path = right_path;
6921 sctx->cmp_key = key;
6923 ret = finish_inode_if_needed(sctx, 0);
6927 /* Ignore non-FS objects */
6928 if (key->objectid == BTRFS_FREE_INO_OBJECTID ||
6929 key->objectid == BTRFS_FREE_SPACE_OBJECTID)
6932 if (key->type == BTRFS_INODE_ITEM_KEY) {
6933 ret = changed_inode(sctx, result);
6934 } else if (!sctx->ignore_cur_inode) {
6935 if (key->type == BTRFS_INODE_REF_KEY ||
6936 key->type == BTRFS_INODE_EXTREF_KEY)
6937 ret = changed_ref(sctx, result);
6938 else if (key->type == BTRFS_XATTR_ITEM_KEY)
6939 ret = changed_xattr(sctx, result);
6940 else if (key->type == BTRFS_EXTENT_DATA_KEY)
6941 ret = changed_extent(sctx, result);
6948 static int search_key_again(const struct send_ctx *sctx,
6949 struct btrfs_root *root,
6950 struct btrfs_path *path,
6951 const struct btrfs_key *key)
6955 if (!path->need_commit_sem)
6956 lockdep_assert_held_read(&root->fs_info->commit_root_sem);
6959 * Roots used for send operations are readonly and no one can add,
6960 * update or remove keys from them, so we should be able to find our
6961 * key again. The only exception is deduplication, which can operate on
6962 * readonly roots and add, update or remove keys to/from them - but at
6963 * the moment we don't allow it to run in parallel with send.
6965 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
6968 btrfs_print_tree(path->nodes[path->lowest_level], false);
6969 btrfs_err(root->fs_info,
6970 "send: key (%llu %u %llu) not found in %s root %llu, lowest_level %d, slot %d",
6971 key->objectid, key->type, key->offset,
6972 (root == sctx->parent_root ? "parent" : "send"),
6973 root->root_key.objectid, path->lowest_level,
6974 path->slots[path->lowest_level]);
6981 static int full_send_tree(struct send_ctx *sctx)
6984 struct btrfs_root *send_root = sctx->send_root;
6985 struct btrfs_key key;
6986 struct btrfs_fs_info *fs_info = send_root->fs_info;
6987 struct btrfs_path *path;
6989 path = alloc_path_for_send();
6992 path->reada = READA_FORWARD_ALWAYS;
6994 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
6995 key.type = BTRFS_INODE_ITEM_KEY;
6998 down_read(&fs_info->commit_root_sem);
6999 sctx->last_reloc_trans = fs_info->last_reloc_trans;
7000 up_read(&fs_info->commit_root_sem);
7002 ret = btrfs_search_slot_for_read(send_root, &key, path, 1, 0);
7009 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
7011 ret = changed_cb(path, NULL, &key,
7012 BTRFS_COMPARE_TREE_NEW, sctx);
7016 down_read(&fs_info->commit_root_sem);
7017 if (fs_info->last_reloc_trans > sctx->last_reloc_trans) {
7018 sctx->last_reloc_trans = fs_info->last_reloc_trans;
7019 up_read(&fs_info->commit_root_sem);
7021 * A transaction used for relocating a block group was
7022 * committed or is about to finish its commit. Release
7023 * our path (leaf) and restart the search, so that we
7024 * avoid operating on any file extent items that are
7025 * stale, with a disk_bytenr that reflects a pre
7026 * relocation value. This way we avoid as much as
7027 * possible to fallback to regular writes when checking
7028 * if we can clone file ranges.
7030 btrfs_release_path(path);
7031 ret = search_key_again(sctx, send_root, path, &key);
7035 up_read(&fs_info->commit_root_sem);
7038 ret = btrfs_next_item(send_root, path);
7048 ret = finish_inode_if_needed(sctx, 1);
7051 btrfs_free_path(path);
7055 static int replace_node_with_clone(struct btrfs_path *path, int level)
7057 struct extent_buffer *clone;
7059 clone = btrfs_clone_extent_buffer(path->nodes[level]);
7063 free_extent_buffer(path->nodes[level]);
7064 path->nodes[level] = clone;
7069 static int tree_move_down(struct btrfs_path *path, int *level, u64 reada_min_gen)
7071 struct extent_buffer *eb;
7072 struct extent_buffer *parent = path->nodes[*level];
7073 int slot = path->slots[*level];
7074 const int nritems = btrfs_header_nritems(parent);
7078 lockdep_assert_held_read(&parent->fs_info->commit_root_sem);
7080 BUG_ON(*level == 0);
7081 eb = btrfs_read_node_slot(parent, slot);
7086 * Trigger readahead for the next leaves we will process, so that it is
7087 * very likely that when we need them they are already in memory and we
7088 * will not block on disk IO. For nodes we only do readahead for one,
7089 * since the time window between processing nodes is typically larger.
7091 reada_max = (*level == 1 ? SZ_128K : eb->fs_info->nodesize);
7093 for (slot++; slot < nritems && reada_done < reada_max; slot++) {
7094 if (btrfs_node_ptr_generation(parent, slot) > reada_min_gen) {
7095 btrfs_readahead_node_child(parent, slot);
7096 reada_done += eb->fs_info->nodesize;
7100 path->nodes[*level - 1] = eb;
7101 path->slots[*level - 1] = 0;
7105 return replace_node_with_clone(path, 0);
7110 static int tree_move_next_or_upnext(struct btrfs_path *path,
7111 int *level, int root_level)
7115 nritems = btrfs_header_nritems(path->nodes[*level]);
7117 path->slots[*level]++;
7119 while (path->slots[*level] >= nritems) {
7120 if (*level == root_level) {
7121 path->slots[*level] = nritems - 1;
7126 path->slots[*level] = 0;
7127 free_extent_buffer(path->nodes[*level]);
7128 path->nodes[*level] = NULL;
7130 path->slots[*level]++;
7132 nritems = btrfs_header_nritems(path->nodes[*level]);
7139 * Returns 1 if it had to move up and next. 0 is returned if it moved only next
7142 static int tree_advance(struct btrfs_path *path,
7143 int *level, int root_level,
7145 struct btrfs_key *key,
7150 if (*level == 0 || !allow_down) {
7151 ret = tree_move_next_or_upnext(path, level, root_level);
7153 ret = tree_move_down(path, level, reada_min_gen);
7157 * Even if we have reached the end of a tree, ret is -1, update the key
7158 * anyway, so that in case we need to restart due to a block group
7159 * relocation, we can assert that the last key of the root node still
7160 * exists in the tree.
7163 btrfs_item_key_to_cpu(path->nodes[*level], key,
7164 path->slots[*level]);
7166 btrfs_node_key_to_cpu(path->nodes[*level], key,
7167 path->slots[*level]);
7172 static int tree_compare_item(struct btrfs_path *left_path,
7173 struct btrfs_path *right_path,
7178 unsigned long off1, off2;
7180 len1 = btrfs_item_size(left_path->nodes[0], left_path->slots[0]);
7181 len2 = btrfs_item_size(right_path->nodes[0], right_path->slots[0]);
7185 off1 = btrfs_item_ptr_offset(left_path->nodes[0], left_path->slots[0]);
7186 off2 = btrfs_item_ptr_offset(right_path->nodes[0],
7187 right_path->slots[0]);
7189 read_extent_buffer(left_path->nodes[0], tmp_buf, off1, len1);
7191 cmp = memcmp_extent_buffer(right_path->nodes[0], tmp_buf, off2, len1);
7198 * A transaction used for relocating a block group was committed or is about to
7199 * finish its commit. Release our paths and restart the search, so that we are
7200 * not using stale extent buffers:
7202 * 1) For levels > 0, we are only holding references of extent buffers, without
7203 * any locks on them, which does not prevent them from having been relocated
7204 * and reallocated after the last time we released the commit root semaphore.
7205 * The exception are the root nodes, for which we always have a clone, see
7206 * the comment at btrfs_compare_trees();
7208 * 2) For leaves, level 0, we are holding copies (clones) of extent buffers, so
7209 * we are safe from the concurrent relocation and reallocation. However they
7210 * can have file extent items with a pre relocation disk_bytenr value, so we
7211 * restart the start from the current commit roots and clone the new leaves so
7212 * that we get the post relocation disk_bytenr values. Not doing so, could
7213 * make us clone the wrong data in case there are new extents using the old
7214 * disk_bytenr that happen to be shared.
7216 static int restart_after_relocation(struct btrfs_path *left_path,
7217 struct btrfs_path *right_path,
7218 const struct btrfs_key *left_key,
7219 const struct btrfs_key *right_key,
7222 const struct send_ctx *sctx)
7227 lockdep_assert_held_read(&sctx->send_root->fs_info->commit_root_sem);
7229 btrfs_release_path(left_path);
7230 btrfs_release_path(right_path);
7233 * Since keys can not be added or removed to/from our roots because they
7234 * are readonly and we do not allow deduplication to run in parallel
7235 * (which can add, remove or change keys), the layout of the trees should
7238 left_path->lowest_level = left_level;
7239 ret = search_key_again(sctx, sctx->send_root, left_path, left_key);
7243 right_path->lowest_level = right_level;
7244 ret = search_key_again(sctx, sctx->parent_root, right_path, right_key);
7249 * If the lowest level nodes are leaves, clone them so that they can be
7250 * safely used by changed_cb() while not under the protection of the
7251 * commit root semaphore, even if relocation and reallocation happens in
7254 if (left_level == 0) {
7255 ret = replace_node_with_clone(left_path, 0);
7260 if (right_level == 0) {
7261 ret = replace_node_with_clone(right_path, 0);
7267 * Now clone the root nodes (unless they happen to be the leaves we have
7268 * already cloned). This is to protect against concurrent snapshotting of
7269 * the send and parent roots (see the comment at btrfs_compare_trees()).
7271 root_level = btrfs_header_level(sctx->send_root->commit_root);
7272 if (root_level > 0) {
7273 ret = replace_node_with_clone(left_path, root_level);
7278 root_level = btrfs_header_level(sctx->parent_root->commit_root);
7279 if (root_level > 0) {
7280 ret = replace_node_with_clone(right_path, root_level);
7289 * This function compares two trees and calls the provided callback for
7290 * every changed/new/deleted item it finds.
7291 * If shared tree blocks are encountered, whole subtrees are skipped, making
7292 * the compare pretty fast on snapshotted subvolumes.
7294 * This currently works on commit roots only. As commit roots are read only,
7295 * we don't do any locking. The commit roots are protected with transactions.
7296 * Transactions are ended and rejoined when a commit is tried in between.
7298 * This function checks for modifications done to the trees while comparing.
7299 * If it detects a change, it aborts immediately.
7301 static int btrfs_compare_trees(struct btrfs_root *left_root,
7302 struct btrfs_root *right_root, struct send_ctx *sctx)
7304 struct btrfs_fs_info *fs_info = left_root->fs_info;
7307 struct btrfs_path *left_path = NULL;
7308 struct btrfs_path *right_path = NULL;
7309 struct btrfs_key left_key;
7310 struct btrfs_key right_key;
7311 char *tmp_buf = NULL;
7312 int left_root_level;
7313 int right_root_level;
7316 int left_end_reached = 0;
7317 int right_end_reached = 0;
7318 int advance_left = 0;
7319 int advance_right = 0;
7326 left_path = btrfs_alloc_path();
7331 right_path = btrfs_alloc_path();
7337 tmp_buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
7343 left_path->search_commit_root = 1;
7344 left_path->skip_locking = 1;
7345 right_path->search_commit_root = 1;
7346 right_path->skip_locking = 1;
7349 * Strategy: Go to the first items of both trees. Then do
7351 * If both trees are at level 0
7352 * Compare keys of current items
7353 * If left < right treat left item as new, advance left tree
7355 * If left > right treat right item as deleted, advance right tree
7357 * If left == right do deep compare of items, treat as changed if
7358 * needed, advance both trees and repeat
7359 * If both trees are at the same level but not at level 0
7360 * Compare keys of current nodes/leafs
7361 * If left < right advance left tree and repeat
7362 * If left > right advance right tree and repeat
7363 * If left == right compare blockptrs of the next nodes/leafs
7364 * If they match advance both trees but stay at the same level
7366 * If they don't match advance both trees while allowing to go
7368 * If tree levels are different
7369 * Advance the tree that needs it and repeat
7371 * Advancing a tree means:
7372 * If we are at level 0, try to go to the next slot. If that's not
7373 * possible, go one level up and repeat. Stop when we found a level
7374 * where we could go to the next slot. We may at this point be on a
7377 * If we are not at level 0 and not on shared tree blocks, go one
7380 * If we are not at level 0 and on shared tree blocks, go one slot to
7381 * the right if possible or go up and right.
7384 down_read(&fs_info->commit_root_sem);
7385 left_level = btrfs_header_level(left_root->commit_root);
7386 left_root_level = left_level;
7388 * We clone the root node of the send and parent roots to prevent races
7389 * with snapshot creation of these roots. Snapshot creation COWs the
7390 * root node of a tree, so after the transaction is committed the old
7391 * extent can be reallocated while this send operation is still ongoing.
7392 * So we clone them, under the commit root semaphore, to be race free.
7394 left_path->nodes[left_level] =
7395 btrfs_clone_extent_buffer(left_root->commit_root);
7396 if (!left_path->nodes[left_level]) {
7401 right_level = btrfs_header_level(right_root->commit_root);
7402 right_root_level = right_level;
7403 right_path->nodes[right_level] =
7404 btrfs_clone_extent_buffer(right_root->commit_root);
7405 if (!right_path->nodes[right_level]) {
7410 * Our right root is the parent root, while the left root is the "send"
7411 * root. We know that all new nodes/leaves in the left root must have
7412 * a generation greater than the right root's generation, so we trigger
7413 * readahead for those nodes and leaves of the left root, as we know we
7414 * will need to read them at some point.
7416 reada_min_gen = btrfs_header_generation(right_root->commit_root);
7418 if (left_level == 0)
7419 btrfs_item_key_to_cpu(left_path->nodes[left_level],
7420 &left_key, left_path->slots[left_level]);
7422 btrfs_node_key_to_cpu(left_path->nodes[left_level],
7423 &left_key, left_path->slots[left_level]);
7424 if (right_level == 0)
7425 btrfs_item_key_to_cpu(right_path->nodes[right_level],
7426 &right_key, right_path->slots[right_level]);
7428 btrfs_node_key_to_cpu(right_path->nodes[right_level],
7429 &right_key, right_path->slots[right_level]);
7431 sctx->last_reloc_trans = fs_info->last_reloc_trans;
7434 if (need_resched() ||
7435 rwsem_is_contended(&fs_info->commit_root_sem)) {
7436 up_read(&fs_info->commit_root_sem);
7438 down_read(&fs_info->commit_root_sem);
7441 if (fs_info->last_reloc_trans > sctx->last_reloc_trans) {
7442 ret = restart_after_relocation(left_path, right_path,
7443 &left_key, &right_key,
7444 left_level, right_level,
7448 sctx->last_reloc_trans = fs_info->last_reloc_trans;
7451 if (advance_left && !left_end_reached) {
7452 ret = tree_advance(left_path, &left_level,
7454 advance_left != ADVANCE_ONLY_NEXT,
7455 &left_key, reada_min_gen);
7457 left_end_reached = ADVANCE;
7462 if (advance_right && !right_end_reached) {
7463 ret = tree_advance(right_path, &right_level,
7465 advance_right != ADVANCE_ONLY_NEXT,
7466 &right_key, reada_min_gen);
7468 right_end_reached = ADVANCE;
7474 if (left_end_reached && right_end_reached) {
7477 } else if (left_end_reached) {
7478 if (right_level == 0) {
7479 up_read(&fs_info->commit_root_sem);
7480 ret = changed_cb(left_path, right_path,
7482 BTRFS_COMPARE_TREE_DELETED,
7486 down_read(&fs_info->commit_root_sem);
7488 advance_right = ADVANCE;
7490 } else if (right_end_reached) {
7491 if (left_level == 0) {
7492 up_read(&fs_info->commit_root_sem);
7493 ret = changed_cb(left_path, right_path,
7495 BTRFS_COMPARE_TREE_NEW,
7499 down_read(&fs_info->commit_root_sem);
7501 advance_left = ADVANCE;
7505 if (left_level == 0 && right_level == 0) {
7506 up_read(&fs_info->commit_root_sem);
7507 cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
7509 ret = changed_cb(left_path, right_path,
7511 BTRFS_COMPARE_TREE_NEW,
7513 advance_left = ADVANCE;
7514 } else if (cmp > 0) {
7515 ret = changed_cb(left_path, right_path,
7517 BTRFS_COMPARE_TREE_DELETED,
7519 advance_right = ADVANCE;
7521 enum btrfs_compare_tree_result result;
7523 WARN_ON(!extent_buffer_uptodate(left_path->nodes[0]));
7524 ret = tree_compare_item(left_path, right_path,
7527 result = BTRFS_COMPARE_TREE_CHANGED;
7529 result = BTRFS_COMPARE_TREE_SAME;
7530 ret = changed_cb(left_path, right_path,
7531 &left_key, result, sctx);
7532 advance_left = ADVANCE;
7533 advance_right = ADVANCE;
7538 down_read(&fs_info->commit_root_sem);
7539 } else if (left_level == right_level) {
7540 cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
7542 advance_left = ADVANCE;
7543 } else if (cmp > 0) {
7544 advance_right = ADVANCE;
7546 left_blockptr = btrfs_node_blockptr(
7547 left_path->nodes[left_level],
7548 left_path->slots[left_level]);
7549 right_blockptr = btrfs_node_blockptr(
7550 right_path->nodes[right_level],
7551 right_path->slots[right_level]);
7552 left_gen = btrfs_node_ptr_generation(
7553 left_path->nodes[left_level],
7554 left_path->slots[left_level]);
7555 right_gen = btrfs_node_ptr_generation(
7556 right_path->nodes[right_level],
7557 right_path->slots[right_level]);
7558 if (left_blockptr == right_blockptr &&
7559 left_gen == right_gen) {
7561 * As we're on a shared block, don't
7562 * allow to go deeper.
7564 advance_left = ADVANCE_ONLY_NEXT;
7565 advance_right = ADVANCE_ONLY_NEXT;
7567 advance_left = ADVANCE;
7568 advance_right = ADVANCE;
7571 } else if (left_level < right_level) {
7572 advance_right = ADVANCE;
7574 advance_left = ADVANCE;
7579 up_read(&fs_info->commit_root_sem);
7581 btrfs_free_path(left_path);
7582 btrfs_free_path(right_path);
7587 static int send_subvol(struct send_ctx *sctx)
7591 if (!(sctx->flags & BTRFS_SEND_FLAG_OMIT_STREAM_HEADER)) {
7592 ret = send_header(sctx);
7597 ret = send_subvol_begin(sctx);
7601 if (sctx->parent_root) {
7602 ret = btrfs_compare_trees(sctx->send_root, sctx->parent_root, sctx);
7605 ret = finish_inode_if_needed(sctx, 1);
7609 ret = full_send_tree(sctx);
7615 free_recorded_refs(sctx);
7620 * If orphan cleanup did remove any orphans from a root, it means the tree
7621 * was modified and therefore the commit root is not the same as the current
7622 * root anymore. This is a problem, because send uses the commit root and
7623 * therefore can see inode items that don't exist in the current root anymore,
7624 * and for example make calls to btrfs_iget, which will do tree lookups based
7625 * on the current root and not on the commit root. Those lookups will fail,
7626 * returning a -ESTALE error, and making send fail with that error. So make
7627 * sure a send does not see any orphans we have just removed, and that it will
7628 * see the same inodes regardless of whether a transaction commit happened
7629 * before it started (meaning that the commit root will be the same as the
7630 * current root) or not.
7632 static int ensure_commit_roots_uptodate(struct send_ctx *sctx)
7635 struct btrfs_trans_handle *trans = NULL;
7638 if (sctx->parent_root &&
7639 sctx->parent_root->node != sctx->parent_root->commit_root)
7642 for (i = 0; i < sctx->clone_roots_cnt; i++)
7643 if (sctx->clone_roots[i].root->node !=
7644 sctx->clone_roots[i].root->commit_root)
7648 return btrfs_end_transaction(trans);
7653 /* Use any root, all fs roots will get their commit roots updated. */
7655 trans = btrfs_join_transaction(sctx->send_root);
7657 return PTR_ERR(trans);
7661 return btrfs_commit_transaction(trans);
7665 * Make sure any existing dellaloc is flushed for any root used by a send
7666 * operation so that we do not miss any data and we do not race with writeback
7667 * finishing and changing a tree while send is using the tree. This could
7668 * happen if a subvolume is in RW mode, has delalloc, is turned to RO mode and
7669 * a send operation then uses the subvolume.
7670 * After flushing delalloc ensure_commit_roots_uptodate() must be called.
7672 static int flush_delalloc_roots(struct send_ctx *sctx)
7674 struct btrfs_root *root = sctx->parent_root;
7679 ret = btrfs_start_delalloc_snapshot(root, false);
7682 btrfs_wait_ordered_extents(root, U64_MAX, 0, U64_MAX);
7685 for (i = 0; i < sctx->clone_roots_cnt; i++) {
7686 root = sctx->clone_roots[i].root;
7687 ret = btrfs_start_delalloc_snapshot(root, false);
7690 btrfs_wait_ordered_extents(root, U64_MAX, 0, U64_MAX);
7696 static void btrfs_root_dec_send_in_progress(struct btrfs_root* root)
7698 spin_lock(&root->root_item_lock);
7699 root->send_in_progress--;
7701 * Not much left to do, we don't know why it's unbalanced and
7702 * can't blindly reset it to 0.
7704 if (root->send_in_progress < 0)
7705 btrfs_err(root->fs_info,
7706 "send_in_progress unbalanced %d root %llu",
7707 root->send_in_progress, root->root_key.objectid);
7708 spin_unlock(&root->root_item_lock);
7711 static void dedupe_in_progress_warn(const struct btrfs_root *root)
7713 btrfs_warn_rl(root->fs_info,
7714 "cannot use root %llu for send while deduplications on it are in progress (%d in progress)",
7715 root->root_key.objectid, root->dedupe_in_progress);
7718 long btrfs_ioctl_send(struct inode *inode, struct btrfs_ioctl_send_args *arg)
7721 struct btrfs_root *send_root = BTRFS_I(inode)->root;
7722 struct btrfs_fs_info *fs_info = send_root->fs_info;
7723 struct btrfs_root *clone_root;
7724 struct send_ctx *sctx = NULL;
7726 u64 *clone_sources_tmp = NULL;
7727 int clone_sources_to_rollback = 0;
7729 int sort_clone_roots = 0;
7731 if (!capable(CAP_SYS_ADMIN))
7735 * The subvolume must remain read-only during send, protect against
7736 * making it RW. This also protects against deletion.
7738 spin_lock(&send_root->root_item_lock);
7739 if (btrfs_root_readonly(send_root) && send_root->dedupe_in_progress) {
7740 dedupe_in_progress_warn(send_root);
7741 spin_unlock(&send_root->root_item_lock);
7744 send_root->send_in_progress++;
7745 spin_unlock(&send_root->root_item_lock);
7748 * Userspace tools do the checks and warn the user if it's
7751 if (!btrfs_root_readonly(send_root)) {
7757 * Check that we don't overflow at later allocations, we request
7758 * clone_sources_count + 1 items, and compare to unsigned long inside
7761 if (arg->clone_sources_count >
7762 ULONG_MAX / sizeof(struct clone_root) - 1) {
7767 if (arg->flags & ~BTRFS_SEND_FLAG_MASK) {
7772 sctx = kzalloc(sizeof(struct send_ctx), GFP_KERNEL);
7778 INIT_LIST_HEAD(&sctx->new_refs);
7779 INIT_LIST_HEAD(&sctx->deleted_refs);
7780 INIT_RADIX_TREE(&sctx->name_cache, GFP_KERNEL);
7781 INIT_LIST_HEAD(&sctx->name_cache_list);
7783 sctx->flags = arg->flags;
7785 if (arg->flags & BTRFS_SEND_FLAG_VERSION) {
7786 if (arg->version > BTRFS_SEND_STREAM_VERSION) {
7790 /* Zero means "use the highest version" */
7791 sctx->proto = arg->version ?: BTRFS_SEND_STREAM_VERSION;
7795 if ((arg->flags & BTRFS_SEND_FLAG_COMPRESSED) && sctx->proto < 2) {
7800 sctx->send_filp = fget(arg->send_fd);
7801 if (!sctx->send_filp) {
7806 sctx->send_root = send_root;
7808 * Unlikely but possible, if the subvolume is marked for deletion but
7809 * is slow to remove the directory entry, send can still be started
7811 if (btrfs_root_dead(sctx->send_root)) {
7816 sctx->clone_roots_cnt = arg->clone_sources_count;
7818 if (sctx->proto >= 2) {
7819 u32 send_buf_num_pages;
7821 sctx->send_max_size = ALIGN(SZ_16K + BTRFS_MAX_COMPRESSED, PAGE_SIZE);
7822 sctx->send_buf = vmalloc(sctx->send_max_size);
7823 if (!sctx->send_buf) {
7827 send_buf_num_pages = sctx->send_max_size >> PAGE_SHIFT;
7828 sctx->send_buf_pages = kcalloc(send_buf_num_pages,
7829 sizeof(*sctx->send_buf_pages),
7831 if (!sctx->send_buf_pages) {
7835 for (i = 0; i < send_buf_num_pages; i++) {
7836 sctx->send_buf_pages[i] =
7837 vmalloc_to_page(sctx->send_buf + (i << PAGE_SHIFT));
7840 sctx->send_max_size = BTRFS_SEND_BUF_SIZE_V1;
7841 sctx->send_buf = kvmalloc(sctx->send_max_size, GFP_KERNEL);
7843 if (!sctx->send_buf) {
7848 sctx->pending_dir_moves = RB_ROOT;
7849 sctx->waiting_dir_moves = RB_ROOT;
7850 sctx->orphan_dirs = RB_ROOT;
7851 sctx->rbtree_new_refs = RB_ROOT;
7852 sctx->rbtree_deleted_refs = RB_ROOT;
7854 sctx->clone_roots = kvcalloc(sizeof(*sctx->clone_roots),
7855 arg->clone_sources_count + 1,
7857 if (!sctx->clone_roots) {
7862 alloc_size = array_size(sizeof(*arg->clone_sources),
7863 arg->clone_sources_count);
7865 if (arg->clone_sources_count) {
7866 clone_sources_tmp = kvmalloc(alloc_size, GFP_KERNEL);
7867 if (!clone_sources_tmp) {
7872 ret = copy_from_user(clone_sources_tmp, arg->clone_sources,
7879 for (i = 0; i < arg->clone_sources_count; i++) {
7880 clone_root = btrfs_get_fs_root(fs_info,
7881 clone_sources_tmp[i], true);
7882 if (IS_ERR(clone_root)) {
7883 ret = PTR_ERR(clone_root);
7886 spin_lock(&clone_root->root_item_lock);
7887 if (!btrfs_root_readonly(clone_root) ||
7888 btrfs_root_dead(clone_root)) {
7889 spin_unlock(&clone_root->root_item_lock);
7890 btrfs_put_root(clone_root);
7894 if (clone_root->dedupe_in_progress) {
7895 dedupe_in_progress_warn(clone_root);
7896 spin_unlock(&clone_root->root_item_lock);
7897 btrfs_put_root(clone_root);
7901 clone_root->send_in_progress++;
7902 spin_unlock(&clone_root->root_item_lock);
7904 sctx->clone_roots[i].root = clone_root;
7905 clone_sources_to_rollback = i + 1;
7907 kvfree(clone_sources_tmp);
7908 clone_sources_tmp = NULL;
7911 if (arg->parent_root) {
7912 sctx->parent_root = btrfs_get_fs_root(fs_info, arg->parent_root,
7914 if (IS_ERR(sctx->parent_root)) {
7915 ret = PTR_ERR(sctx->parent_root);
7919 spin_lock(&sctx->parent_root->root_item_lock);
7920 sctx->parent_root->send_in_progress++;
7921 if (!btrfs_root_readonly(sctx->parent_root) ||
7922 btrfs_root_dead(sctx->parent_root)) {
7923 spin_unlock(&sctx->parent_root->root_item_lock);
7927 if (sctx->parent_root->dedupe_in_progress) {
7928 dedupe_in_progress_warn(sctx->parent_root);
7929 spin_unlock(&sctx->parent_root->root_item_lock);
7933 spin_unlock(&sctx->parent_root->root_item_lock);
7937 * Clones from send_root are allowed, but only if the clone source
7938 * is behind the current send position. This is checked while searching
7939 * for possible clone sources.
7941 sctx->clone_roots[sctx->clone_roots_cnt++].root =
7942 btrfs_grab_root(sctx->send_root);
7944 /* We do a bsearch later */
7945 sort(sctx->clone_roots, sctx->clone_roots_cnt,
7946 sizeof(*sctx->clone_roots), __clone_root_cmp_sort,
7948 sort_clone_roots = 1;
7950 ret = flush_delalloc_roots(sctx);
7954 ret = ensure_commit_roots_uptodate(sctx);
7958 ret = send_subvol(sctx);
7962 if (!(sctx->flags & BTRFS_SEND_FLAG_OMIT_END_CMD)) {
7963 ret = begin_cmd(sctx, BTRFS_SEND_C_END);
7966 ret = send_cmd(sctx);
7972 WARN_ON(sctx && !ret && !RB_EMPTY_ROOT(&sctx->pending_dir_moves));
7973 while (sctx && !RB_EMPTY_ROOT(&sctx->pending_dir_moves)) {
7975 struct pending_dir_move *pm;
7977 n = rb_first(&sctx->pending_dir_moves);
7978 pm = rb_entry(n, struct pending_dir_move, node);
7979 while (!list_empty(&pm->list)) {
7980 struct pending_dir_move *pm2;
7982 pm2 = list_first_entry(&pm->list,
7983 struct pending_dir_move, list);
7984 free_pending_move(sctx, pm2);
7986 free_pending_move(sctx, pm);
7989 WARN_ON(sctx && !ret && !RB_EMPTY_ROOT(&sctx->waiting_dir_moves));
7990 while (sctx && !RB_EMPTY_ROOT(&sctx->waiting_dir_moves)) {
7992 struct waiting_dir_move *dm;
7994 n = rb_first(&sctx->waiting_dir_moves);
7995 dm = rb_entry(n, struct waiting_dir_move, node);
7996 rb_erase(&dm->node, &sctx->waiting_dir_moves);
8000 WARN_ON(sctx && !ret && !RB_EMPTY_ROOT(&sctx->orphan_dirs));
8001 while (sctx && !RB_EMPTY_ROOT(&sctx->orphan_dirs)) {
8003 struct orphan_dir_info *odi;
8005 n = rb_first(&sctx->orphan_dirs);
8006 odi = rb_entry(n, struct orphan_dir_info, node);
8007 free_orphan_dir_info(sctx, odi);
8010 if (sort_clone_roots) {
8011 for (i = 0; i < sctx->clone_roots_cnt; i++) {
8012 btrfs_root_dec_send_in_progress(
8013 sctx->clone_roots[i].root);
8014 btrfs_put_root(sctx->clone_roots[i].root);
8017 for (i = 0; sctx && i < clone_sources_to_rollback; i++) {
8018 btrfs_root_dec_send_in_progress(
8019 sctx->clone_roots[i].root);
8020 btrfs_put_root(sctx->clone_roots[i].root);
8023 btrfs_root_dec_send_in_progress(send_root);
8025 if (sctx && !IS_ERR_OR_NULL(sctx->parent_root)) {
8026 btrfs_root_dec_send_in_progress(sctx->parent_root);
8027 btrfs_put_root(sctx->parent_root);
8030 kvfree(clone_sources_tmp);
8033 if (sctx->send_filp)
8034 fput(sctx->send_filp);
8036 kvfree(sctx->clone_roots);
8037 kfree(sctx->send_buf_pages);
8038 kvfree(sctx->send_buf);
8040 name_cache_free(sctx);
8042 close_current_inode(sctx);