1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2012 Alexander Block. All rights reserved.
6 #include <linux/bsearch.h>
8 #include <linux/file.h>
9 #include <linux/sort.h>
10 #include <linux/mount.h>
11 #include <linux/xattr.h>
12 #include <linux/posix_acl_xattr.h>
13 #include <linux/radix-tree.h>
14 #include <linux/vmalloc.h>
15 #include <linux/string.h>
16 #include <linux/compat.h>
17 #include <linux/crc32c.h>
23 #include "btrfs_inode.h"
24 #include "transaction.h"
25 #include "compression.h"
27 #include "print-tree.h"
30 * Maximum number of references an extent can have in order for us to attempt to
31 * issue clone operations instead of write operations. This currently exists to
32 * avoid hitting limitations of the backreference walking code (taking a lot of
33 * time and using too much memory for extents with large number of references).
35 #define SEND_MAX_EXTENT_REFS 64
38 * A fs_path is a helper to dynamically build path names with unknown size.
39 * It reallocates the internal buffer on demand.
40 * It allows fast adding of path elements on the right side (normal path) and
41 * fast adding to the left side (reversed path). A reversed path can also be
42 * unreversed if needed.
51 unsigned short buf_len:15;
52 unsigned short reversed:1;
56 * Average path length does not exceed 200 bytes, we'll have
57 * better packing in the slab and higher chance to satisfy
58 * a allocation later during send.
63 #define FS_PATH_INLINE_SIZE \
64 (sizeof(struct fs_path) - offsetof(struct fs_path, inline_buf))
67 /* reused for each extent */
69 struct btrfs_root *root;
76 #define SEND_CTX_MAX_NAME_CACHE_SIZE 128
77 #define SEND_CTX_NAME_CACHE_CLEAN_SIZE (SEND_CTX_MAX_NAME_CACHE_SIZE * 2)
80 struct file *send_filp;
86 u64 cmd_send_size[BTRFS_SEND_C_MAX + 1];
87 u64 flags; /* 'flags' member of btrfs_ioctl_send_args is u64 */
89 struct btrfs_root *send_root;
90 struct btrfs_root *parent_root;
91 struct clone_root *clone_roots;
94 /* current state of the compare_tree call */
95 struct btrfs_path *left_path;
96 struct btrfs_path *right_path;
97 struct btrfs_key *cmp_key;
100 * Keep track of the generation of the last transaction that was used
101 * for relocating a block group. This is periodically checked in order
102 * to detect if a relocation happened since the last check, so that we
103 * don't operate on stale extent buffers for nodes (level >= 1) or on
104 * stale disk_bytenr values of file extent items.
106 u64 last_reloc_trans;
109 * infos of the currently processed inode. In case of deleted inodes,
110 * these are the values from the deleted inode.
115 int cur_inode_new_gen;
116 int cur_inode_deleted;
120 u64 cur_inode_last_extent;
121 u64 cur_inode_next_write_offset;
122 bool ignore_cur_inode;
126 struct list_head new_refs;
127 struct list_head deleted_refs;
129 struct radix_tree_root name_cache;
130 struct list_head name_cache_list;
133 struct file_ra_state ra;
136 * We process inodes by their increasing order, so if before an
137 * incremental send we reverse the parent/child relationship of
138 * directories such that a directory with a lower inode number was
139 * the parent of a directory with a higher inode number, and the one
140 * becoming the new parent got renamed too, we can't rename/move the
141 * directory with lower inode number when we finish processing it - we
142 * must process the directory with higher inode number first, then
143 * rename/move it and then rename/move the directory with lower inode
144 * number. Example follows.
146 * Tree state when the first send was performed:
158 * Tree state when the second (incremental) send is performed:
167 * The sequence of steps that lead to the second state was:
169 * mv /a/b/c/d /a/b/c2/d2
170 * mv /a/b/c /a/b/c2/d2/cc
172 * "c" has lower inode number, but we can't move it (2nd mv operation)
173 * before we move "d", which has higher inode number.
175 * So we just memorize which move/rename operations must be performed
176 * later when their respective parent is processed and moved/renamed.
179 /* Indexed by parent directory inode number. */
180 struct rb_root pending_dir_moves;
183 * Reverse index, indexed by the inode number of a directory that
184 * is waiting for the move/rename of its immediate parent before its
185 * own move/rename can be performed.
187 struct rb_root waiting_dir_moves;
190 * A directory that is going to be rm'ed might have a child directory
191 * which is in the pending directory moves index above. In this case,
192 * the directory can only be removed after the move/rename of its child
193 * is performed. Example:
213 * Sequence of steps that lead to the send snapshot:
214 * rm -f /a/b/c/foo.txt
216 * mv /a/b/c/x /a/b/YY
219 * When the child is processed, its move/rename is delayed until its
220 * parent is processed (as explained above), but all other operations
221 * like update utimes, chown, chgrp, etc, are performed and the paths
222 * that it uses for those operations must use the orphanized name of
223 * its parent (the directory we're going to rm later), so we need to
224 * memorize that name.
226 * Indexed by the inode number of the directory to be deleted.
228 struct rb_root orphan_dirs;
231 struct pending_dir_move {
233 struct list_head list;
237 struct list_head update_refs;
240 struct waiting_dir_move {
244 * There might be some directory that could not be removed because it
245 * was waiting for this directory inode to be moved first. Therefore
246 * after this directory is moved, we can try to rmdir the ino rmdir_ino.
253 struct orphan_dir_info {
257 u64 last_dir_index_offset;
260 struct name_cache_entry {
261 struct list_head list;
263 * radix_tree has only 32bit entries but we need to handle 64bit inums.
264 * We use the lower 32bit of the 64bit inum to store it in the tree. If
265 * more then one inum would fall into the same entry, we use radix_list
266 * to store the additional entries. radix_list is also used to store
267 * entries where two entries have the same inum but different
270 struct list_head radix_list;
276 int need_later_update;
282 #define ADVANCE_ONLY_NEXT -1
284 enum btrfs_compare_tree_result {
285 BTRFS_COMPARE_TREE_NEW,
286 BTRFS_COMPARE_TREE_DELETED,
287 BTRFS_COMPARE_TREE_CHANGED,
288 BTRFS_COMPARE_TREE_SAME,
292 static void inconsistent_snapshot_error(struct send_ctx *sctx,
293 enum btrfs_compare_tree_result result,
296 const char *result_string;
299 case BTRFS_COMPARE_TREE_NEW:
300 result_string = "new";
302 case BTRFS_COMPARE_TREE_DELETED:
303 result_string = "deleted";
305 case BTRFS_COMPARE_TREE_CHANGED:
306 result_string = "updated";
308 case BTRFS_COMPARE_TREE_SAME:
310 result_string = "unchanged";
314 result_string = "unexpected";
317 btrfs_err(sctx->send_root->fs_info,
318 "Send: inconsistent snapshot, found %s %s for inode %llu without updated inode item, send root is %llu, parent root is %llu",
319 result_string, what, sctx->cmp_key->objectid,
320 sctx->send_root->root_key.objectid,
322 sctx->parent_root->root_key.objectid : 0));
325 static int is_waiting_for_move(struct send_ctx *sctx, u64 ino);
327 static struct waiting_dir_move *
328 get_waiting_dir_move(struct send_ctx *sctx, u64 ino);
330 static int is_waiting_for_rm(struct send_ctx *sctx, u64 dir_ino, u64 gen);
332 static int need_send_hole(struct send_ctx *sctx)
334 return (sctx->parent_root && !sctx->cur_inode_new &&
335 !sctx->cur_inode_new_gen && !sctx->cur_inode_deleted &&
336 S_ISREG(sctx->cur_inode_mode));
339 static void fs_path_reset(struct fs_path *p)
342 p->start = p->buf + p->buf_len - 1;
352 static struct fs_path *fs_path_alloc(void)
356 p = kmalloc(sizeof(*p), GFP_KERNEL);
360 p->buf = p->inline_buf;
361 p->buf_len = FS_PATH_INLINE_SIZE;
366 static struct fs_path *fs_path_alloc_reversed(void)
378 static void fs_path_free(struct fs_path *p)
382 if (p->buf != p->inline_buf)
387 static int fs_path_len(struct fs_path *p)
389 return p->end - p->start;
392 static int fs_path_ensure_buf(struct fs_path *p, int len)
400 if (p->buf_len >= len)
403 if (len > PATH_MAX) {
408 path_len = p->end - p->start;
409 old_buf_len = p->buf_len;
412 * First time the inline_buf does not suffice
414 if (p->buf == p->inline_buf) {
415 tmp_buf = kmalloc(len, GFP_KERNEL);
417 memcpy(tmp_buf, p->buf, old_buf_len);
419 tmp_buf = krealloc(p->buf, len, GFP_KERNEL);
425 * The real size of the buffer is bigger, this will let the fast path
426 * happen most of the time
428 p->buf_len = ksize(p->buf);
431 tmp_buf = p->buf + old_buf_len - path_len - 1;
432 p->end = p->buf + p->buf_len - 1;
433 p->start = p->end - path_len;
434 memmove(p->start, tmp_buf, path_len + 1);
437 p->end = p->start + path_len;
442 static int fs_path_prepare_for_add(struct fs_path *p, int name_len,
448 new_len = p->end - p->start + name_len;
449 if (p->start != p->end)
451 ret = fs_path_ensure_buf(p, new_len);
456 if (p->start != p->end)
458 p->start -= name_len;
459 *prepared = p->start;
461 if (p->start != p->end)
472 static int fs_path_add(struct fs_path *p, const char *name, int name_len)
477 ret = fs_path_prepare_for_add(p, name_len, &prepared);
480 memcpy(prepared, name, name_len);
486 static int fs_path_add_path(struct fs_path *p, struct fs_path *p2)
491 ret = fs_path_prepare_for_add(p, p2->end - p2->start, &prepared);
494 memcpy(prepared, p2->start, p2->end - p2->start);
500 static int fs_path_add_from_extent_buffer(struct fs_path *p,
501 struct extent_buffer *eb,
502 unsigned long off, int len)
507 ret = fs_path_prepare_for_add(p, len, &prepared);
511 read_extent_buffer(eb, prepared, off, len);
517 static int fs_path_copy(struct fs_path *p, struct fs_path *from)
521 p->reversed = from->reversed;
524 ret = fs_path_add_path(p, from);
530 static void fs_path_unreverse(struct fs_path *p)
539 len = p->end - p->start;
541 p->end = p->start + len;
542 memmove(p->start, tmp, len + 1);
546 static struct btrfs_path *alloc_path_for_send(void)
548 struct btrfs_path *path;
550 path = btrfs_alloc_path();
553 path->search_commit_root = 1;
554 path->skip_locking = 1;
555 path->need_commit_sem = 1;
559 static int write_buf(struct file *filp, const void *buf, u32 len, loff_t *off)
565 ret = kernel_write(filp, buf + pos, len - pos, off);
566 /* TODO handle that correctly */
567 /*if (ret == -ERESTARTSYS) {
581 static int tlv_put(struct send_ctx *sctx, u16 attr, const void *data, int len)
583 struct btrfs_tlv_header *hdr;
584 int total_len = sizeof(*hdr) + len;
585 int left = sctx->send_max_size - sctx->send_size;
587 if (unlikely(left < total_len))
590 hdr = (struct btrfs_tlv_header *) (sctx->send_buf + sctx->send_size);
591 put_unaligned_le16(attr, &hdr->tlv_type);
592 put_unaligned_le16(len, &hdr->tlv_len);
593 memcpy(hdr + 1, data, len);
594 sctx->send_size += total_len;
599 #define TLV_PUT_DEFINE_INT(bits) \
600 static int tlv_put_u##bits(struct send_ctx *sctx, \
601 u##bits attr, u##bits value) \
603 __le##bits __tmp = cpu_to_le##bits(value); \
604 return tlv_put(sctx, attr, &__tmp, sizeof(__tmp)); \
607 TLV_PUT_DEFINE_INT(64)
609 static int tlv_put_string(struct send_ctx *sctx, u16 attr,
610 const char *str, int len)
614 return tlv_put(sctx, attr, str, len);
617 static int tlv_put_uuid(struct send_ctx *sctx, u16 attr,
620 return tlv_put(sctx, attr, uuid, BTRFS_UUID_SIZE);
623 static int tlv_put_btrfs_timespec(struct send_ctx *sctx, u16 attr,
624 struct extent_buffer *eb,
625 struct btrfs_timespec *ts)
627 struct btrfs_timespec bts;
628 read_extent_buffer(eb, &bts, (unsigned long)ts, sizeof(bts));
629 return tlv_put(sctx, attr, &bts, sizeof(bts));
633 #define TLV_PUT(sctx, attrtype, data, attrlen) \
635 ret = tlv_put(sctx, attrtype, data, attrlen); \
637 goto tlv_put_failure; \
640 #define TLV_PUT_INT(sctx, attrtype, bits, value) \
642 ret = tlv_put_u##bits(sctx, attrtype, value); \
644 goto tlv_put_failure; \
647 #define TLV_PUT_U8(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 8, data)
648 #define TLV_PUT_U16(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 16, data)
649 #define TLV_PUT_U32(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 32, data)
650 #define TLV_PUT_U64(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 64, data)
651 #define TLV_PUT_STRING(sctx, attrtype, str, len) \
653 ret = tlv_put_string(sctx, attrtype, str, len); \
655 goto tlv_put_failure; \
657 #define TLV_PUT_PATH(sctx, attrtype, p) \
659 ret = tlv_put_string(sctx, attrtype, p->start, \
660 p->end - p->start); \
662 goto tlv_put_failure; \
664 #define TLV_PUT_UUID(sctx, attrtype, uuid) \
666 ret = tlv_put_uuid(sctx, attrtype, uuid); \
668 goto tlv_put_failure; \
670 #define TLV_PUT_BTRFS_TIMESPEC(sctx, attrtype, eb, ts) \
672 ret = tlv_put_btrfs_timespec(sctx, attrtype, eb, ts); \
674 goto tlv_put_failure; \
677 static int send_header(struct send_ctx *sctx)
679 struct btrfs_stream_header hdr;
681 strcpy(hdr.magic, BTRFS_SEND_STREAM_MAGIC);
682 hdr.version = cpu_to_le32(BTRFS_SEND_STREAM_VERSION);
684 return write_buf(sctx->send_filp, &hdr, sizeof(hdr),
689 * For each command/item we want to send to userspace, we call this function.
691 static int begin_cmd(struct send_ctx *sctx, int cmd)
693 struct btrfs_cmd_header *hdr;
695 if (WARN_ON(!sctx->send_buf))
698 BUG_ON(sctx->send_size);
700 sctx->send_size += sizeof(*hdr);
701 hdr = (struct btrfs_cmd_header *)sctx->send_buf;
702 put_unaligned_le16(cmd, &hdr->cmd);
707 static int send_cmd(struct send_ctx *sctx)
710 struct btrfs_cmd_header *hdr;
713 hdr = (struct btrfs_cmd_header *)sctx->send_buf;
714 put_unaligned_le32(sctx->send_size - sizeof(*hdr), &hdr->len);
715 put_unaligned_le32(0, &hdr->crc);
717 crc = btrfs_crc32c(0, (unsigned char *)sctx->send_buf, sctx->send_size);
718 put_unaligned_le32(crc, &hdr->crc);
720 ret = write_buf(sctx->send_filp, sctx->send_buf, sctx->send_size,
723 sctx->total_send_size += sctx->send_size;
724 sctx->cmd_send_size[get_unaligned_le16(&hdr->cmd)] += sctx->send_size;
731 * Sends a move instruction to user space
733 static int send_rename(struct send_ctx *sctx,
734 struct fs_path *from, struct fs_path *to)
736 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
739 btrfs_debug(fs_info, "send_rename %s -> %s", from->start, to->start);
741 ret = begin_cmd(sctx, BTRFS_SEND_C_RENAME);
745 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, from);
746 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH_TO, to);
748 ret = send_cmd(sctx);
756 * Sends a link instruction to user space
758 static int send_link(struct send_ctx *sctx,
759 struct fs_path *path, struct fs_path *lnk)
761 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
764 btrfs_debug(fs_info, "send_link %s -> %s", path->start, lnk->start);
766 ret = begin_cmd(sctx, BTRFS_SEND_C_LINK);
770 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
771 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH_LINK, lnk);
773 ret = send_cmd(sctx);
781 * Sends an unlink instruction to user space
783 static int send_unlink(struct send_ctx *sctx, struct fs_path *path)
785 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
788 btrfs_debug(fs_info, "send_unlink %s", path->start);
790 ret = begin_cmd(sctx, BTRFS_SEND_C_UNLINK);
794 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
796 ret = send_cmd(sctx);
804 * Sends a rmdir instruction to user space
806 static int send_rmdir(struct send_ctx *sctx, struct fs_path *path)
808 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
811 btrfs_debug(fs_info, "send_rmdir %s", path->start);
813 ret = begin_cmd(sctx, BTRFS_SEND_C_RMDIR);
817 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
819 ret = send_cmd(sctx);
827 * Helper function to retrieve some fields from an inode item.
829 static int __get_inode_info(struct btrfs_root *root, struct btrfs_path *path,
830 u64 ino, u64 *size, u64 *gen, u64 *mode, u64 *uid,
834 struct btrfs_inode_item *ii;
835 struct btrfs_key key;
838 key.type = BTRFS_INODE_ITEM_KEY;
840 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
847 ii = btrfs_item_ptr(path->nodes[0], path->slots[0],
848 struct btrfs_inode_item);
850 *size = btrfs_inode_size(path->nodes[0], ii);
852 *gen = btrfs_inode_generation(path->nodes[0], ii);
854 *mode = btrfs_inode_mode(path->nodes[0], ii);
856 *uid = btrfs_inode_uid(path->nodes[0], ii);
858 *gid = btrfs_inode_gid(path->nodes[0], ii);
860 *rdev = btrfs_inode_rdev(path->nodes[0], ii);
865 static int get_inode_info(struct btrfs_root *root,
866 u64 ino, u64 *size, u64 *gen,
867 u64 *mode, u64 *uid, u64 *gid,
870 struct btrfs_path *path;
873 path = alloc_path_for_send();
876 ret = __get_inode_info(root, path, ino, size, gen, mode, uid, gid,
878 btrfs_free_path(path);
882 typedef int (*iterate_inode_ref_t)(int num, u64 dir, int index,
887 * Helper function to iterate the entries in ONE btrfs_inode_ref or
888 * btrfs_inode_extref.
889 * The iterate callback may return a non zero value to stop iteration. This can
890 * be a negative value for error codes or 1 to simply stop it.
892 * path must point to the INODE_REF or INODE_EXTREF when called.
894 static int iterate_inode_ref(struct btrfs_root *root, struct btrfs_path *path,
895 struct btrfs_key *found_key, int resolve,
896 iterate_inode_ref_t iterate, void *ctx)
898 struct extent_buffer *eb = path->nodes[0];
899 struct btrfs_item *item;
900 struct btrfs_inode_ref *iref;
901 struct btrfs_inode_extref *extref;
902 struct btrfs_path *tmp_path;
906 int slot = path->slots[0];
913 unsigned long name_off;
914 unsigned long elem_size;
917 p = fs_path_alloc_reversed();
921 tmp_path = alloc_path_for_send();
928 if (found_key->type == BTRFS_INODE_REF_KEY) {
929 ptr = (unsigned long)btrfs_item_ptr(eb, slot,
930 struct btrfs_inode_ref);
931 item = btrfs_item_nr(slot);
932 total = btrfs_item_size(eb, item);
933 elem_size = sizeof(*iref);
935 ptr = btrfs_item_ptr_offset(eb, slot);
936 total = btrfs_item_size_nr(eb, slot);
937 elem_size = sizeof(*extref);
940 while (cur < total) {
943 if (found_key->type == BTRFS_INODE_REF_KEY) {
944 iref = (struct btrfs_inode_ref *)(ptr + cur);
945 name_len = btrfs_inode_ref_name_len(eb, iref);
946 name_off = (unsigned long)(iref + 1);
947 index = btrfs_inode_ref_index(eb, iref);
948 dir = found_key->offset;
950 extref = (struct btrfs_inode_extref *)(ptr + cur);
951 name_len = btrfs_inode_extref_name_len(eb, extref);
952 name_off = (unsigned long)&extref->name;
953 index = btrfs_inode_extref_index(eb, extref);
954 dir = btrfs_inode_extref_parent(eb, extref);
958 start = btrfs_ref_to_path(root, tmp_path, name_len,
962 ret = PTR_ERR(start);
965 if (start < p->buf) {
966 /* overflow , try again with larger buffer */
967 ret = fs_path_ensure_buf(p,
968 p->buf_len + p->buf - start);
971 start = btrfs_ref_to_path(root, tmp_path,
976 ret = PTR_ERR(start);
979 BUG_ON(start < p->buf);
983 ret = fs_path_add_from_extent_buffer(p, eb, name_off,
989 cur += elem_size + name_len;
990 ret = iterate(num, dir, index, p, ctx);
997 btrfs_free_path(tmp_path);
1002 typedef int (*iterate_dir_item_t)(int num, struct btrfs_key *di_key,
1003 const char *name, int name_len,
1004 const char *data, int data_len,
1005 u8 type, void *ctx);
1008 * Helper function to iterate the entries in ONE btrfs_dir_item.
1009 * The iterate callback may return a non zero value to stop iteration. This can
1010 * be a negative value for error codes or 1 to simply stop it.
1012 * path must point to the dir item when called.
1014 static int iterate_dir_item(struct btrfs_root *root, struct btrfs_path *path,
1015 iterate_dir_item_t iterate, void *ctx)
1018 struct extent_buffer *eb;
1019 struct btrfs_item *item;
1020 struct btrfs_dir_item *di;
1021 struct btrfs_key di_key;
1034 * Start with a small buffer (1 page). If later we end up needing more
1035 * space, which can happen for xattrs on a fs with a leaf size greater
1036 * then the page size, attempt to increase the buffer. Typically xattr
1040 buf = kmalloc(buf_len, GFP_KERNEL);
1046 eb = path->nodes[0];
1047 slot = path->slots[0];
1048 item = btrfs_item_nr(slot);
1049 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
1052 total = btrfs_item_size(eb, item);
1055 while (cur < total) {
1056 name_len = btrfs_dir_name_len(eb, di);
1057 data_len = btrfs_dir_data_len(eb, di);
1058 type = btrfs_dir_type(eb, di);
1059 btrfs_dir_item_key_to_cpu(eb, di, &di_key);
1061 if (type == BTRFS_FT_XATTR) {
1062 if (name_len > XATTR_NAME_MAX) {
1063 ret = -ENAMETOOLONG;
1066 if (name_len + data_len >
1067 BTRFS_MAX_XATTR_SIZE(root->fs_info)) {
1075 if (name_len + data_len > PATH_MAX) {
1076 ret = -ENAMETOOLONG;
1081 if (name_len + data_len > buf_len) {
1082 buf_len = name_len + data_len;
1083 if (is_vmalloc_addr(buf)) {
1087 char *tmp = krealloc(buf, buf_len,
1088 GFP_KERNEL | __GFP_NOWARN);
1095 buf = kvmalloc(buf_len, GFP_KERNEL);
1103 read_extent_buffer(eb, buf, (unsigned long)(di + 1),
1104 name_len + data_len);
1106 len = sizeof(*di) + name_len + data_len;
1107 di = (struct btrfs_dir_item *)((char *)di + len);
1110 ret = iterate(num, &di_key, buf, name_len, buf + name_len,
1111 data_len, type, ctx);
1127 static int __copy_first_ref(int num, u64 dir, int index,
1128 struct fs_path *p, void *ctx)
1131 struct fs_path *pt = ctx;
1133 ret = fs_path_copy(pt, p);
1137 /* we want the first only */
1142 * Retrieve the first path of an inode. If an inode has more then one
1143 * ref/hardlink, this is ignored.
1145 static int get_inode_path(struct btrfs_root *root,
1146 u64 ino, struct fs_path *path)
1149 struct btrfs_key key, found_key;
1150 struct btrfs_path *p;
1152 p = alloc_path_for_send();
1156 fs_path_reset(path);
1159 key.type = BTRFS_INODE_REF_KEY;
1162 ret = btrfs_search_slot_for_read(root, &key, p, 1, 0);
1169 btrfs_item_key_to_cpu(p->nodes[0], &found_key, p->slots[0]);
1170 if (found_key.objectid != ino ||
1171 (found_key.type != BTRFS_INODE_REF_KEY &&
1172 found_key.type != BTRFS_INODE_EXTREF_KEY)) {
1177 ret = iterate_inode_ref(root, p, &found_key, 1,
1178 __copy_first_ref, path);
1188 struct backref_ctx {
1189 struct send_ctx *sctx;
1191 /* number of total found references */
1195 * used for clones found in send_root. clones found behind cur_objectid
1196 * and cur_offset are not considered as allowed clones.
1201 /* may be truncated in case it's the last extent in a file */
1204 /* Just to check for bugs in backref resolving */
1208 static int __clone_root_cmp_bsearch(const void *key, const void *elt)
1210 u64 root = (u64)(uintptr_t)key;
1211 const struct clone_root *cr = elt;
1213 if (root < cr->root->root_key.objectid)
1215 if (root > cr->root->root_key.objectid)
1220 static int __clone_root_cmp_sort(const void *e1, const void *e2)
1222 const struct clone_root *cr1 = e1;
1223 const struct clone_root *cr2 = e2;
1225 if (cr1->root->root_key.objectid < cr2->root->root_key.objectid)
1227 if (cr1->root->root_key.objectid > cr2->root->root_key.objectid)
1233 * Called for every backref that is found for the current extent.
1234 * Results are collected in sctx->clone_roots->ino/offset/found_refs
1236 static int __iterate_backrefs(u64 ino, u64 offset, u64 root, void *ctx_)
1238 struct backref_ctx *bctx = ctx_;
1239 struct clone_root *found;
1241 /* First check if the root is in the list of accepted clone sources */
1242 found = bsearch((void *)(uintptr_t)root, bctx->sctx->clone_roots,
1243 bctx->sctx->clone_roots_cnt,
1244 sizeof(struct clone_root),
1245 __clone_root_cmp_bsearch);
1249 if (found->root == bctx->sctx->send_root &&
1250 ino == bctx->cur_objectid &&
1251 offset == bctx->cur_offset) {
1252 bctx->found_itself = 1;
1256 * Make sure we don't consider clones from send_root that are
1257 * behind the current inode/offset.
1259 if (found->root == bctx->sctx->send_root) {
1261 * If the source inode was not yet processed we can't issue a
1262 * clone operation, as the source extent does not exist yet at
1263 * the destination of the stream.
1265 if (ino > bctx->cur_objectid)
1268 * We clone from the inode currently being sent as long as the
1269 * source extent is already processed, otherwise we could try
1270 * to clone from an extent that does not exist yet at the
1271 * destination of the stream.
1273 if (ino == bctx->cur_objectid &&
1274 offset + bctx->extent_len >
1275 bctx->sctx->cur_inode_next_write_offset)
1280 found->found_refs++;
1281 if (ino < found->ino) {
1283 found->offset = offset;
1284 } else if (found->ino == ino) {
1286 * same extent found more then once in the same file.
1288 if (found->offset > offset + bctx->extent_len)
1289 found->offset = offset;
1296 * Given an inode, offset and extent item, it finds a good clone for a clone
1297 * instruction. Returns -ENOENT when none could be found. The function makes
1298 * sure that the returned clone is usable at the point where sending is at the
1299 * moment. This means, that no clones are accepted which lie behind the current
1302 * path must point to the extent item when called.
1304 static int find_extent_clone(struct send_ctx *sctx,
1305 struct btrfs_path *path,
1306 u64 ino, u64 data_offset,
1308 struct clone_root **found)
1310 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
1316 u64 extent_item_pos;
1318 struct btrfs_file_extent_item *fi;
1319 struct extent_buffer *eb = path->nodes[0];
1320 struct backref_ctx backref_ctx = {0};
1321 struct clone_root *cur_clone_root;
1322 struct btrfs_key found_key;
1323 struct btrfs_path *tmp_path;
1324 struct btrfs_extent_item *ei;
1328 tmp_path = alloc_path_for_send();
1332 /* We only use this path under the commit sem */
1333 tmp_path->need_commit_sem = 0;
1335 if (data_offset >= ino_size) {
1337 * There may be extents that lie behind the file's size.
1338 * I at least had this in combination with snapshotting while
1339 * writing large files.
1345 fi = btrfs_item_ptr(eb, path->slots[0],
1346 struct btrfs_file_extent_item);
1347 extent_type = btrfs_file_extent_type(eb, fi);
1348 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1352 compressed = btrfs_file_extent_compression(eb, fi);
1354 num_bytes = btrfs_file_extent_num_bytes(eb, fi);
1355 disk_byte = btrfs_file_extent_disk_bytenr(eb, fi);
1356 if (disk_byte == 0) {
1360 logical = disk_byte + btrfs_file_extent_offset(eb, fi);
1362 down_read(&fs_info->commit_root_sem);
1363 ret = extent_from_logical(fs_info, disk_byte, tmp_path,
1364 &found_key, &flags);
1365 up_read(&fs_info->commit_root_sem);
1369 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
1374 ei = btrfs_item_ptr(tmp_path->nodes[0], tmp_path->slots[0],
1375 struct btrfs_extent_item);
1377 * Backreference walking (iterate_extent_inodes() below) is currently
1378 * too expensive when an extent has a large number of references, both
1379 * in time spent and used memory. So for now just fallback to write
1380 * operations instead of clone operations when an extent has more than
1381 * a certain amount of references.
1383 if (btrfs_extent_refs(tmp_path->nodes[0], ei) > SEND_MAX_EXTENT_REFS) {
1387 btrfs_release_path(tmp_path);
1390 * Setup the clone roots.
1392 for (i = 0; i < sctx->clone_roots_cnt; i++) {
1393 cur_clone_root = sctx->clone_roots + i;
1394 cur_clone_root->ino = (u64)-1;
1395 cur_clone_root->offset = 0;
1396 cur_clone_root->found_refs = 0;
1399 backref_ctx.sctx = sctx;
1400 backref_ctx.found = 0;
1401 backref_ctx.cur_objectid = ino;
1402 backref_ctx.cur_offset = data_offset;
1403 backref_ctx.found_itself = 0;
1404 backref_ctx.extent_len = num_bytes;
1407 * The last extent of a file may be too large due to page alignment.
1408 * We need to adjust extent_len in this case so that the checks in
1409 * __iterate_backrefs work.
1411 if (data_offset + num_bytes >= ino_size)
1412 backref_ctx.extent_len = ino_size - data_offset;
1415 * Now collect all backrefs.
1417 if (compressed == BTRFS_COMPRESS_NONE)
1418 extent_item_pos = logical - found_key.objectid;
1420 extent_item_pos = 0;
1421 ret = iterate_extent_inodes(fs_info, found_key.objectid,
1422 extent_item_pos, 1, __iterate_backrefs,
1423 &backref_ctx, false);
1428 down_read(&fs_info->commit_root_sem);
1429 if (fs_info->last_reloc_trans > sctx->last_reloc_trans) {
1431 * A transaction commit for a transaction in which block group
1432 * relocation was done just happened.
1433 * The disk_bytenr of the file extent item we processed is
1434 * possibly stale, referring to the extent's location before
1435 * relocation. So act as if we haven't found any clone sources
1436 * and fallback to write commands, which will read the correct
1437 * data from the new extent location. Otherwise we will fail
1438 * below because we haven't found our own back reference or we
1439 * could be getting incorrect sources in case the old extent
1440 * was already reallocated after the relocation.
1442 up_read(&fs_info->commit_root_sem);
1446 up_read(&fs_info->commit_root_sem);
1448 if (!backref_ctx.found_itself) {
1449 /* found a bug in backref code? */
1452 "did not find backref in send_root. inode=%llu, offset=%llu, disk_byte=%llu found extent=%llu",
1453 ino, data_offset, disk_byte, found_key.objectid);
1457 btrfs_debug(fs_info,
1458 "find_extent_clone: data_offset=%llu, ino=%llu, num_bytes=%llu, logical=%llu",
1459 data_offset, ino, num_bytes, logical);
1461 if (!backref_ctx.found)
1462 btrfs_debug(fs_info, "no clones found");
1464 cur_clone_root = NULL;
1465 for (i = 0; i < sctx->clone_roots_cnt; i++) {
1466 if (sctx->clone_roots[i].found_refs) {
1467 if (!cur_clone_root)
1468 cur_clone_root = sctx->clone_roots + i;
1469 else if (sctx->clone_roots[i].root == sctx->send_root)
1470 /* prefer clones from send_root over others */
1471 cur_clone_root = sctx->clone_roots + i;
1476 if (cur_clone_root) {
1477 *found = cur_clone_root;
1484 btrfs_free_path(tmp_path);
1488 static int read_symlink(struct btrfs_root *root,
1490 struct fs_path *dest)
1493 struct btrfs_path *path;
1494 struct btrfs_key key;
1495 struct btrfs_file_extent_item *ei;
1501 path = alloc_path_for_send();
1506 key.type = BTRFS_EXTENT_DATA_KEY;
1508 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1513 * An empty symlink inode. Can happen in rare error paths when
1514 * creating a symlink (transaction committed before the inode
1515 * eviction handler removed the symlink inode items and a crash
1516 * happened in between or the subvol was snapshoted in between).
1517 * Print an informative message to dmesg/syslog so that the user
1518 * can delete the symlink.
1520 btrfs_err(root->fs_info,
1521 "Found empty symlink inode %llu at root %llu",
1522 ino, root->root_key.objectid);
1527 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
1528 struct btrfs_file_extent_item);
1529 type = btrfs_file_extent_type(path->nodes[0], ei);
1530 compression = btrfs_file_extent_compression(path->nodes[0], ei);
1531 BUG_ON(type != BTRFS_FILE_EXTENT_INLINE);
1532 BUG_ON(compression);
1534 off = btrfs_file_extent_inline_start(ei);
1535 len = btrfs_file_extent_ram_bytes(path->nodes[0], ei);
1537 ret = fs_path_add_from_extent_buffer(dest, path->nodes[0], off, len);
1540 btrfs_free_path(path);
1545 * Helper function to generate a file name that is unique in the root of
1546 * send_root and parent_root. This is used to generate names for orphan inodes.
1548 static int gen_unique_name(struct send_ctx *sctx,
1550 struct fs_path *dest)
1553 struct btrfs_path *path;
1554 struct btrfs_dir_item *di;
1559 path = alloc_path_for_send();
1564 len = snprintf(tmp, sizeof(tmp), "o%llu-%llu-%llu",
1566 ASSERT(len < sizeof(tmp));
1568 di = btrfs_lookup_dir_item(NULL, sctx->send_root,
1569 path, BTRFS_FIRST_FREE_OBJECTID,
1570 tmp, strlen(tmp), 0);
1571 btrfs_release_path(path);
1577 /* not unique, try again */
1582 if (!sctx->parent_root) {
1588 di = btrfs_lookup_dir_item(NULL, sctx->parent_root,
1589 path, BTRFS_FIRST_FREE_OBJECTID,
1590 tmp, strlen(tmp), 0);
1591 btrfs_release_path(path);
1597 /* not unique, try again */
1605 ret = fs_path_add(dest, tmp, strlen(tmp));
1608 btrfs_free_path(path);
1613 inode_state_no_change,
1614 inode_state_will_create,
1615 inode_state_did_create,
1616 inode_state_will_delete,
1617 inode_state_did_delete,
1620 static int get_cur_inode_state(struct send_ctx *sctx, u64 ino, u64 gen)
1628 ret = get_inode_info(sctx->send_root, ino, NULL, &left_gen, NULL, NULL,
1630 if (ret < 0 && ret != -ENOENT)
1634 if (!sctx->parent_root) {
1635 right_ret = -ENOENT;
1637 ret = get_inode_info(sctx->parent_root, ino, NULL, &right_gen,
1638 NULL, NULL, NULL, NULL);
1639 if (ret < 0 && ret != -ENOENT)
1644 if (!left_ret && !right_ret) {
1645 if (left_gen == gen && right_gen == gen) {
1646 ret = inode_state_no_change;
1647 } else if (left_gen == gen) {
1648 if (ino < sctx->send_progress)
1649 ret = inode_state_did_create;
1651 ret = inode_state_will_create;
1652 } else if (right_gen == gen) {
1653 if (ino < sctx->send_progress)
1654 ret = inode_state_did_delete;
1656 ret = inode_state_will_delete;
1660 } else if (!left_ret) {
1661 if (left_gen == gen) {
1662 if (ino < sctx->send_progress)
1663 ret = inode_state_did_create;
1665 ret = inode_state_will_create;
1669 } else if (!right_ret) {
1670 if (right_gen == gen) {
1671 if (ino < sctx->send_progress)
1672 ret = inode_state_did_delete;
1674 ret = inode_state_will_delete;
1686 static int is_inode_existent(struct send_ctx *sctx, u64 ino, u64 gen)
1690 if (ino == BTRFS_FIRST_FREE_OBJECTID)
1693 ret = get_cur_inode_state(sctx, ino, gen);
1697 if (ret == inode_state_no_change ||
1698 ret == inode_state_did_create ||
1699 ret == inode_state_will_delete)
1709 * Helper function to lookup a dir item in a dir.
1711 static int lookup_dir_item_inode(struct btrfs_root *root,
1712 u64 dir, const char *name, int name_len,
1717 struct btrfs_dir_item *di;
1718 struct btrfs_key key;
1719 struct btrfs_path *path;
1721 path = alloc_path_for_send();
1725 di = btrfs_lookup_dir_item(NULL, root, path,
1726 dir, name, name_len, 0);
1727 if (IS_ERR_OR_NULL(di)) {
1728 ret = di ? PTR_ERR(di) : -ENOENT;
1731 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
1732 if (key.type == BTRFS_ROOT_ITEM_KEY) {
1736 *found_inode = key.objectid;
1737 *found_type = btrfs_dir_type(path->nodes[0], di);
1740 btrfs_free_path(path);
1745 * Looks up the first btrfs_inode_ref of a given ino. It returns the parent dir,
1746 * generation of the parent dir and the name of the dir entry.
1748 static int get_first_ref(struct btrfs_root *root, u64 ino,
1749 u64 *dir, u64 *dir_gen, struct fs_path *name)
1752 struct btrfs_key key;
1753 struct btrfs_key found_key;
1754 struct btrfs_path *path;
1758 path = alloc_path_for_send();
1763 key.type = BTRFS_INODE_REF_KEY;
1766 ret = btrfs_search_slot_for_read(root, &key, path, 1, 0);
1770 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1772 if (ret || found_key.objectid != ino ||
1773 (found_key.type != BTRFS_INODE_REF_KEY &&
1774 found_key.type != BTRFS_INODE_EXTREF_KEY)) {
1779 if (found_key.type == BTRFS_INODE_REF_KEY) {
1780 struct btrfs_inode_ref *iref;
1781 iref = btrfs_item_ptr(path->nodes[0], path->slots[0],
1782 struct btrfs_inode_ref);
1783 len = btrfs_inode_ref_name_len(path->nodes[0], iref);
1784 ret = fs_path_add_from_extent_buffer(name, path->nodes[0],
1785 (unsigned long)(iref + 1),
1787 parent_dir = found_key.offset;
1789 struct btrfs_inode_extref *extref;
1790 extref = btrfs_item_ptr(path->nodes[0], path->slots[0],
1791 struct btrfs_inode_extref);
1792 len = btrfs_inode_extref_name_len(path->nodes[0], extref);
1793 ret = fs_path_add_from_extent_buffer(name, path->nodes[0],
1794 (unsigned long)&extref->name, len);
1795 parent_dir = btrfs_inode_extref_parent(path->nodes[0], extref);
1799 btrfs_release_path(path);
1802 ret = get_inode_info(root, parent_dir, NULL, dir_gen, NULL,
1811 btrfs_free_path(path);
1815 static int is_first_ref(struct btrfs_root *root,
1817 const char *name, int name_len)
1820 struct fs_path *tmp_name;
1823 tmp_name = fs_path_alloc();
1827 ret = get_first_ref(root, ino, &tmp_dir, NULL, tmp_name);
1831 if (dir != tmp_dir || name_len != fs_path_len(tmp_name)) {
1836 ret = !memcmp(tmp_name->start, name, name_len);
1839 fs_path_free(tmp_name);
1844 * Used by process_recorded_refs to determine if a new ref would overwrite an
1845 * already existing ref. In case it detects an overwrite, it returns the
1846 * inode/gen in who_ino/who_gen.
1847 * When an overwrite is detected, process_recorded_refs does proper orphanizing
1848 * to make sure later references to the overwritten inode are possible.
1849 * Orphanizing is however only required for the first ref of an inode.
1850 * process_recorded_refs does an additional is_first_ref check to see if
1851 * orphanizing is really required.
1853 static int will_overwrite_ref(struct send_ctx *sctx, u64 dir, u64 dir_gen,
1854 const char *name, int name_len,
1855 u64 *who_ino, u64 *who_gen, u64 *who_mode)
1859 u64 other_inode = 0;
1862 if (!sctx->parent_root)
1865 ret = is_inode_existent(sctx, dir, dir_gen);
1870 * If we have a parent root we need to verify that the parent dir was
1871 * not deleted and then re-created, if it was then we have no overwrite
1872 * and we can just unlink this entry.
1874 if (sctx->parent_root && dir != BTRFS_FIRST_FREE_OBJECTID) {
1875 ret = get_inode_info(sctx->parent_root, dir, NULL, &gen, NULL,
1877 if (ret < 0 && ret != -ENOENT)
1887 ret = lookup_dir_item_inode(sctx->parent_root, dir, name, name_len,
1888 &other_inode, &other_type);
1889 if (ret < 0 && ret != -ENOENT)
1897 * Check if the overwritten ref was already processed. If yes, the ref
1898 * was already unlinked/moved, so we can safely assume that we will not
1899 * overwrite anything at this point in time.
1901 if (other_inode > sctx->send_progress ||
1902 is_waiting_for_move(sctx, other_inode)) {
1903 ret = get_inode_info(sctx->parent_root, other_inode, NULL,
1904 who_gen, who_mode, NULL, NULL, NULL);
1909 *who_ino = other_inode;
1919 * Checks if the ref was overwritten by an already processed inode. This is
1920 * used by __get_cur_name_and_parent to find out if the ref was orphanized and
1921 * thus the orphan name needs be used.
1922 * process_recorded_refs also uses it to avoid unlinking of refs that were
1925 static int did_overwrite_ref(struct send_ctx *sctx,
1926 u64 dir, u64 dir_gen,
1927 u64 ino, u64 ino_gen,
1928 const char *name, int name_len)
1935 if (!sctx->parent_root)
1938 ret = is_inode_existent(sctx, dir, dir_gen);
1942 if (dir != BTRFS_FIRST_FREE_OBJECTID) {
1943 ret = get_inode_info(sctx->send_root, dir, NULL, &gen, NULL,
1945 if (ret < 0 && ret != -ENOENT)
1955 /* check if the ref was overwritten by another ref */
1956 ret = lookup_dir_item_inode(sctx->send_root, dir, name, name_len,
1957 &ow_inode, &other_type);
1958 if (ret < 0 && ret != -ENOENT)
1961 /* was never and will never be overwritten */
1966 ret = get_inode_info(sctx->send_root, ow_inode, NULL, &gen, NULL, NULL,
1971 if (ow_inode == ino && gen == ino_gen) {
1977 * We know that it is or will be overwritten. Check this now.
1978 * The current inode being processed might have been the one that caused
1979 * inode 'ino' to be orphanized, therefore check if ow_inode matches
1980 * the current inode being processed.
1982 if ((ow_inode < sctx->send_progress) ||
1983 (ino != sctx->cur_ino && ow_inode == sctx->cur_ino &&
1984 gen == sctx->cur_inode_gen))
1994 * Same as did_overwrite_ref, but also checks if it is the first ref of an inode
1995 * that got overwritten. This is used by process_recorded_refs to determine
1996 * if it has to use the path as returned by get_cur_path or the orphan name.
1998 static int did_overwrite_first_ref(struct send_ctx *sctx, u64 ino, u64 gen)
2001 struct fs_path *name = NULL;
2005 if (!sctx->parent_root)
2008 name = fs_path_alloc();
2012 ret = get_first_ref(sctx->parent_root, ino, &dir, &dir_gen, name);
2016 ret = did_overwrite_ref(sctx, dir, dir_gen, ino, gen,
2017 name->start, fs_path_len(name));
2025 * Insert a name cache entry. On 32bit kernels the radix tree index is 32bit,
2026 * so we need to do some special handling in case we have clashes. This function
2027 * takes care of this with the help of name_cache_entry::radix_list.
2028 * In case of error, nce is kfreed.
2030 static int name_cache_insert(struct send_ctx *sctx,
2031 struct name_cache_entry *nce)
2034 struct list_head *nce_head;
2036 nce_head = radix_tree_lookup(&sctx->name_cache,
2037 (unsigned long)nce->ino);
2039 nce_head = kmalloc(sizeof(*nce_head), GFP_KERNEL);
2044 INIT_LIST_HEAD(nce_head);
2046 ret = radix_tree_insert(&sctx->name_cache, nce->ino, nce_head);
2053 list_add_tail(&nce->radix_list, nce_head);
2054 list_add_tail(&nce->list, &sctx->name_cache_list);
2055 sctx->name_cache_size++;
2060 static void name_cache_delete(struct send_ctx *sctx,
2061 struct name_cache_entry *nce)
2063 struct list_head *nce_head;
2065 nce_head = radix_tree_lookup(&sctx->name_cache,
2066 (unsigned long)nce->ino);
2068 btrfs_err(sctx->send_root->fs_info,
2069 "name_cache_delete lookup failed ino %llu cache size %d, leaking memory",
2070 nce->ino, sctx->name_cache_size);
2073 list_del(&nce->radix_list);
2074 list_del(&nce->list);
2075 sctx->name_cache_size--;
2078 * We may not get to the final release of nce_head if the lookup fails
2080 if (nce_head && list_empty(nce_head)) {
2081 radix_tree_delete(&sctx->name_cache, (unsigned long)nce->ino);
2086 static struct name_cache_entry *name_cache_search(struct send_ctx *sctx,
2089 struct list_head *nce_head;
2090 struct name_cache_entry *cur;
2092 nce_head = radix_tree_lookup(&sctx->name_cache, (unsigned long)ino);
2096 list_for_each_entry(cur, nce_head, radix_list) {
2097 if (cur->ino == ino && cur->gen == gen)
2104 * Remove some entries from the beginning of name_cache_list.
2106 static void name_cache_clean_unused(struct send_ctx *sctx)
2108 struct name_cache_entry *nce;
2110 if (sctx->name_cache_size < SEND_CTX_NAME_CACHE_CLEAN_SIZE)
2113 while (sctx->name_cache_size > SEND_CTX_MAX_NAME_CACHE_SIZE) {
2114 nce = list_entry(sctx->name_cache_list.next,
2115 struct name_cache_entry, list);
2116 name_cache_delete(sctx, nce);
2121 static void name_cache_free(struct send_ctx *sctx)
2123 struct name_cache_entry *nce;
2125 while (!list_empty(&sctx->name_cache_list)) {
2126 nce = list_entry(sctx->name_cache_list.next,
2127 struct name_cache_entry, list);
2128 name_cache_delete(sctx, nce);
2134 * Used by get_cur_path for each ref up to the root.
2135 * Returns 0 if it succeeded.
2136 * Returns 1 if the inode is not existent or got overwritten. In that case, the
2137 * name is an orphan name. This instructs get_cur_path to stop iterating. If 1
2138 * is returned, parent_ino/parent_gen are not guaranteed to be valid.
2139 * Returns <0 in case of error.
2141 static int __get_cur_name_and_parent(struct send_ctx *sctx,
2145 struct fs_path *dest)
2149 struct name_cache_entry *nce = NULL;
2152 * First check if we already did a call to this function with the same
2153 * ino/gen. If yes, check if the cache entry is still up-to-date. If yes
2154 * return the cached result.
2156 nce = name_cache_search(sctx, ino, gen);
2158 if (ino < sctx->send_progress && nce->need_later_update) {
2159 name_cache_delete(sctx, nce);
2164 * Removes the entry from the list and adds it back to
2165 * the end. This marks the entry as recently used so
2166 * that name_cache_clean_unused does not remove it.
2168 list_move_tail(&nce->list, &sctx->name_cache_list);
2170 *parent_ino = nce->parent_ino;
2171 *parent_gen = nce->parent_gen;
2172 ret = fs_path_add(dest, nce->name, nce->name_len);
2181 * If the inode is not existent yet, add the orphan name and return 1.
2182 * This should only happen for the parent dir that we determine in
2185 ret = is_inode_existent(sctx, ino, gen);
2190 ret = gen_unique_name(sctx, ino, gen, dest);
2198 * Depending on whether the inode was already processed or not, use
2199 * send_root or parent_root for ref lookup.
2201 if (ino < sctx->send_progress)
2202 ret = get_first_ref(sctx->send_root, ino,
2203 parent_ino, parent_gen, dest);
2205 ret = get_first_ref(sctx->parent_root, ino,
2206 parent_ino, parent_gen, dest);
2211 * Check if the ref was overwritten by an inode's ref that was processed
2212 * earlier. If yes, treat as orphan and return 1.
2214 ret = did_overwrite_ref(sctx, *parent_ino, *parent_gen, ino, gen,
2215 dest->start, dest->end - dest->start);
2219 fs_path_reset(dest);
2220 ret = gen_unique_name(sctx, ino, gen, dest);
2228 * Store the result of the lookup in the name cache.
2230 nce = kmalloc(sizeof(*nce) + fs_path_len(dest) + 1, GFP_KERNEL);
2238 nce->parent_ino = *parent_ino;
2239 nce->parent_gen = *parent_gen;
2240 nce->name_len = fs_path_len(dest);
2242 strcpy(nce->name, dest->start);
2244 if (ino < sctx->send_progress)
2245 nce->need_later_update = 0;
2247 nce->need_later_update = 1;
2249 nce_ret = name_cache_insert(sctx, nce);
2252 name_cache_clean_unused(sctx);
2259 * Magic happens here. This function returns the first ref to an inode as it
2260 * would look like while receiving the stream at this point in time.
2261 * We walk the path up to the root. For every inode in between, we check if it
2262 * was already processed/sent. If yes, we continue with the parent as found
2263 * in send_root. If not, we continue with the parent as found in parent_root.
2264 * If we encounter an inode that was deleted at this point in time, we use the
2265 * inodes "orphan" name instead of the real name and stop. Same with new inodes
2266 * that were not created yet and overwritten inodes/refs.
2268 * When do we have orphan inodes:
2269 * 1. When an inode is freshly created and thus no valid refs are available yet
2270 * 2. When a directory lost all it's refs (deleted) but still has dir items
2271 * inside which were not processed yet (pending for move/delete). If anyone
2272 * tried to get the path to the dir items, it would get a path inside that
2274 * 3. When an inode is moved around or gets new links, it may overwrite the ref
2275 * of an unprocessed inode. If in that case the first ref would be
2276 * overwritten, the overwritten inode gets "orphanized". Later when we
2277 * process this overwritten inode, it is restored at a new place by moving
2280 * sctx->send_progress tells this function at which point in time receiving
2283 static int get_cur_path(struct send_ctx *sctx, u64 ino, u64 gen,
2284 struct fs_path *dest)
2287 struct fs_path *name = NULL;
2288 u64 parent_inode = 0;
2292 name = fs_path_alloc();
2299 fs_path_reset(dest);
2301 while (!stop && ino != BTRFS_FIRST_FREE_OBJECTID) {
2302 struct waiting_dir_move *wdm;
2304 fs_path_reset(name);
2306 if (is_waiting_for_rm(sctx, ino, gen)) {
2307 ret = gen_unique_name(sctx, ino, gen, name);
2310 ret = fs_path_add_path(dest, name);
2314 wdm = get_waiting_dir_move(sctx, ino);
2315 if (wdm && wdm->orphanized) {
2316 ret = gen_unique_name(sctx, ino, gen, name);
2319 ret = get_first_ref(sctx->parent_root, ino,
2320 &parent_inode, &parent_gen, name);
2322 ret = __get_cur_name_and_parent(sctx, ino, gen,
2332 ret = fs_path_add_path(dest, name);
2343 fs_path_unreverse(dest);
2348 * Sends a BTRFS_SEND_C_SUBVOL command/item to userspace
2350 static int send_subvol_begin(struct send_ctx *sctx)
2353 struct btrfs_root *send_root = sctx->send_root;
2354 struct btrfs_root *parent_root = sctx->parent_root;
2355 struct btrfs_path *path;
2356 struct btrfs_key key;
2357 struct btrfs_root_ref *ref;
2358 struct extent_buffer *leaf;
2362 path = btrfs_alloc_path();
2366 name = kmalloc(BTRFS_PATH_NAME_MAX, GFP_KERNEL);
2368 btrfs_free_path(path);
2372 key.objectid = send_root->root_key.objectid;
2373 key.type = BTRFS_ROOT_BACKREF_KEY;
2376 ret = btrfs_search_slot_for_read(send_root->fs_info->tree_root,
2385 leaf = path->nodes[0];
2386 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2387 if (key.type != BTRFS_ROOT_BACKREF_KEY ||
2388 key.objectid != send_root->root_key.objectid) {
2392 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
2393 namelen = btrfs_root_ref_name_len(leaf, ref);
2394 read_extent_buffer(leaf, name, (unsigned long)(ref + 1), namelen);
2395 btrfs_release_path(path);
2398 ret = begin_cmd(sctx, BTRFS_SEND_C_SNAPSHOT);
2402 ret = begin_cmd(sctx, BTRFS_SEND_C_SUBVOL);
2407 TLV_PUT_STRING(sctx, BTRFS_SEND_A_PATH, name, namelen);
2409 if (!btrfs_is_empty_uuid(sctx->send_root->root_item.received_uuid))
2410 TLV_PUT_UUID(sctx, BTRFS_SEND_A_UUID,
2411 sctx->send_root->root_item.received_uuid);
2413 TLV_PUT_UUID(sctx, BTRFS_SEND_A_UUID,
2414 sctx->send_root->root_item.uuid);
2416 TLV_PUT_U64(sctx, BTRFS_SEND_A_CTRANSID,
2417 btrfs_root_ctransid(&sctx->send_root->root_item));
2419 if (!btrfs_is_empty_uuid(parent_root->root_item.received_uuid))
2420 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
2421 parent_root->root_item.received_uuid);
2423 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
2424 parent_root->root_item.uuid);
2425 TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_CTRANSID,
2426 btrfs_root_ctransid(&sctx->parent_root->root_item));
2429 ret = send_cmd(sctx);
2433 btrfs_free_path(path);
2438 static int send_truncate(struct send_ctx *sctx, u64 ino, u64 gen, u64 size)
2440 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2444 btrfs_debug(fs_info, "send_truncate %llu size=%llu", ino, size);
2446 p = fs_path_alloc();
2450 ret = begin_cmd(sctx, BTRFS_SEND_C_TRUNCATE);
2454 ret = get_cur_path(sctx, ino, gen, p);
2457 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2458 TLV_PUT_U64(sctx, BTRFS_SEND_A_SIZE, size);
2460 ret = send_cmd(sctx);
2468 static int send_chmod(struct send_ctx *sctx, u64 ino, u64 gen, u64 mode)
2470 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2474 btrfs_debug(fs_info, "send_chmod %llu mode=%llu", ino, mode);
2476 p = fs_path_alloc();
2480 ret = begin_cmd(sctx, BTRFS_SEND_C_CHMOD);
2484 ret = get_cur_path(sctx, ino, gen, p);
2487 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2488 TLV_PUT_U64(sctx, BTRFS_SEND_A_MODE, mode & 07777);
2490 ret = send_cmd(sctx);
2498 static int send_chown(struct send_ctx *sctx, u64 ino, u64 gen, u64 uid, u64 gid)
2500 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2504 btrfs_debug(fs_info, "send_chown %llu uid=%llu, gid=%llu",
2507 p = fs_path_alloc();
2511 ret = begin_cmd(sctx, BTRFS_SEND_C_CHOWN);
2515 ret = get_cur_path(sctx, ino, gen, p);
2518 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2519 TLV_PUT_U64(sctx, BTRFS_SEND_A_UID, uid);
2520 TLV_PUT_U64(sctx, BTRFS_SEND_A_GID, gid);
2522 ret = send_cmd(sctx);
2530 static int send_utimes(struct send_ctx *sctx, u64 ino, u64 gen)
2532 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2534 struct fs_path *p = NULL;
2535 struct btrfs_inode_item *ii;
2536 struct btrfs_path *path = NULL;
2537 struct extent_buffer *eb;
2538 struct btrfs_key key;
2541 btrfs_debug(fs_info, "send_utimes %llu", ino);
2543 p = fs_path_alloc();
2547 path = alloc_path_for_send();
2554 key.type = BTRFS_INODE_ITEM_KEY;
2556 ret = btrfs_search_slot(NULL, sctx->send_root, &key, path, 0, 0);
2562 eb = path->nodes[0];
2563 slot = path->slots[0];
2564 ii = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
2566 ret = begin_cmd(sctx, BTRFS_SEND_C_UTIMES);
2570 ret = get_cur_path(sctx, ino, gen, p);
2573 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2574 TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_ATIME, eb, &ii->atime);
2575 TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_MTIME, eb, &ii->mtime);
2576 TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_CTIME, eb, &ii->ctime);
2577 /* TODO Add otime support when the otime patches get into upstream */
2579 ret = send_cmd(sctx);
2584 btrfs_free_path(path);
2589 * Sends a BTRFS_SEND_C_MKXXX or SYMLINK command to user space. We don't have
2590 * a valid path yet because we did not process the refs yet. So, the inode
2591 * is created as orphan.
2593 static int send_create_inode(struct send_ctx *sctx, u64 ino)
2595 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2603 btrfs_debug(fs_info, "send_create_inode %llu", ino);
2605 p = fs_path_alloc();
2609 if (ino != sctx->cur_ino) {
2610 ret = get_inode_info(sctx->send_root, ino, NULL, &gen, &mode,
2615 gen = sctx->cur_inode_gen;
2616 mode = sctx->cur_inode_mode;
2617 rdev = sctx->cur_inode_rdev;
2620 if (S_ISREG(mode)) {
2621 cmd = BTRFS_SEND_C_MKFILE;
2622 } else if (S_ISDIR(mode)) {
2623 cmd = BTRFS_SEND_C_MKDIR;
2624 } else if (S_ISLNK(mode)) {
2625 cmd = BTRFS_SEND_C_SYMLINK;
2626 } else if (S_ISCHR(mode) || S_ISBLK(mode)) {
2627 cmd = BTRFS_SEND_C_MKNOD;
2628 } else if (S_ISFIFO(mode)) {
2629 cmd = BTRFS_SEND_C_MKFIFO;
2630 } else if (S_ISSOCK(mode)) {
2631 cmd = BTRFS_SEND_C_MKSOCK;
2633 btrfs_warn(sctx->send_root->fs_info, "unexpected inode type %o",
2634 (int)(mode & S_IFMT));
2639 ret = begin_cmd(sctx, cmd);
2643 ret = gen_unique_name(sctx, ino, gen, p);
2647 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2648 TLV_PUT_U64(sctx, BTRFS_SEND_A_INO, ino);
2650 if (S_ISLNK(mode)) {
2652 ret = read_symlink(sctx->send_root, ino, p);
2655 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH_LINK, p);
2656 } else if (S_ISCHR(mode) || S_ISBLK(mode) ||
2657 S_ISFIFO(mode) || S_ISSOCK(mode)) {
2658 TLV_PUT_U64(sctx, BTRFS_SEND_A_RDEV, new_encode_dev(rdev));
2659 TLV_PUT_U64(sctx, BTRFS_SEND_A_MODE, mode);
2662 ret = send_cmd(sctx);
2674 * We need some special handling for inodes that get processed before the parent
2675 * directory got created. See process_recorded_refs for details.
2676 * This function does the check if we already created the dir out of order.
2678 static int did_create_dir(struct send_ctx *sctx, u64 dir)
2681 struct btrfs_path *path = NULL;
2682 struct btrfs_key key;
2683 struct btrfs_key found_key;
2684 struct btrfs_key di_key;
2685 struct extent_buffer *eb;
2686 struct btrfs_dir_item *di;
2689 path = alloc_path_for_send();
2696 key.type = BTRFS_DIR_INDEX_KEY;
2698 ret = btrfs_search_slot(NULL, sctx->send_root, &key, path, 0, 0);
2703 eb = path->nodes[0];
2704 slot = path->slots[0];
2705 if (slot >= btrfs_header_nritems(eb)) {
2706 ret = btrfs_next_leaf(sctx->send_root, path);
2709 } else if (ret > 0) {
2716 btrfs_item_key_to_cpu(eb, &found_key, slot);
2717 if (found_key.objectid != key.objectid ||
2718 found_key.type != key.type) {
2723 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
2724 btrfs_dir_item_key_to_cpu(eb, di, &di_key);
2726 if (di_key.type != BTRFS_ROOT_ITEM_KEY &&
2727 di_key.objectid < sctx->send_progress) {
2736 btrfs_free_path(path);
2741 * Only creates the inode if it is:
2742 * 1. Not a directory
2743 * 2. Or a directory which was not created already due to out of order
2744 * directories. See did_create_dir and process_recorded_refs for details.
2746 static int send_create_inode_if_needed(struct send_ctx *sctx)
2750 if (S_ISDIR(sctx->cur_inode_mode)) {
2751 ret = did_create_dir(sctx, sctx->cur_ino);
2760 ret = send_create_inode(sctx, sctx->cur_ino);
2768 struct recorded_ref {
2769 struct list_head list;
2771 struct fs_path *full_path;
2777 static void set_ref_path(struct recorded_ref *ref, struct fs_path *path)
2779 ref->full_path = path;
2780 ref->name = (char *)kbasename(ref->full_path->start);
2781 ref->name_len = ref->full_path->end - ref->name;
2785 * We need to process new refs before deleted refs, but compare_tree gives us
2786 * everything mixed. So we first record all refs and later process them.
2787 * This function is a helper to record one ref.
2789 static int __record_ref(struct list_head *head, u64 dir,
2790 u64 dir_gen, struct fs_path *path)
2792 struct recorded_ref *ref;
2794 ref = kmalloc(sizeof(*ref), GFP_KERNEL);
2799 ref->dir_gen = dir_gen;
2800 set_ref_path(ref, path);
2801 list_add_tail(&ref->list, head);
2805 static int dup_ref(struct recorded_ref *ref, struct list_head *list)
2807 struct recorded_ref *new;
2809 new = kmalloc(sizeof(*ref), GFP_KERNEL);
2813 new->dir = ref->dir;
2814 new->dir_gen = ref->dir_gen;
2815 new->full_path = NULL;
2816 INIT_LIST_HEAD(&new->list);
2817 list_add_tail(&new->list, list);
2821 static void __free_recorded_refs(struct list_head *head)
2823 struct recorded_ref *cur;
2825 while (!list_empty(head)) {
2826 cur = list_entry(head->next, struct recorded_ref, list);
2827 fs_path_free(cur->full_path);
2828 list_del(&cur->list);
2833 static void free_recorded_refs(struct send_ctx *sctx)
2835 __free_recorded_refs(&sctx->new_refs);
2836 __free_recorded_refs(&sctx->deleted_refs);
2840 * Renames/moves a file/dir to its orphan name. Used when the first
2841 * ref of an unprocessed inode gets overwritten and for all non empty
2844 static int orphanize_inode(struct send_ctx *sctx, u64 ino, u64 gen,
2845 struct fs_path *path)
2848 struct fs_path *orphan;
2850 orphan = fs_path_alloc();
2854 ret = gen_unique_name(sctx, ino, gen, orphan);
2858 ret = send_rename(sctx, path, orphan);
2861 fs_path_free(orphan);
2865 static struct orphan_dir_info *add_orphan_dir_info(struct send_ctx *sctx,
2866 u64 dir_ino, u64 dir_gen)
2868 struct rb_node **p = &sctx->orphan_dirs.rb_node;
2869 struct rb_node *parent = NULL;
2870 struct orphan_dir_info *entry, *odi;
2874 entry = rb_entry(parent, struct orphan_dir_info, node);
2875 if (dir_ino < entry->ino)
2877 else if (dir_ino > entry->ino)
2878 p = &(*p)->rb_right;
2879 else if (dir_gen < entry->gen)
2881 else if (dir_gen > entry->gen)
2882 p = &(*p)->rb_right;
2887 odi = kmalloc(sizeof(*odi), GFP_KERNEL);
2889 return ERR_PTR(-ENOMEM);
2892 odi->last_dir_index_offset = 0;
2894 rb_link_node(&odi->node, parent, p);
2895 rb_insert_color(&odi->node, &sctx->orphan_dirs);
2899 static struct orphan_dir_info *get_orphan_dir_info(struct send_ctx *sctx,
2900 u64 dir_ino, u64 gen)
2902 struct rb_node *n = sctx->orphan_dirs.rb_node;
2903 struct orphan_dir_info *entry;
2906 entry = rb_entry(n, struct orphan_dir_info, node);
2907 if (dir_ino < entry->ino)
2909 else if (dir_ino > entry->ino)
2911 else if (gen < entry->gen)
2913 else if (gen > entry->gen)
2921 static int is_waiting_for_rm(struct send_ctx *sctx, u64 dir_ino, u64 gen)
2923 struct orphan_dir_info *odi = get_orphan_dir_info(sctx, dir_ino, gen);
2928 static void free_orphan_dir_info(struct send_ctx *sctx,
2929 struct orphan_dir_info *odi)
2933 rb_erase(&odi->node, &sctx->orphan_dirs);
2938 * Returns 1 if a directory can be removed at this point in time.
2939 * We check this by iterating all dir items and checking if the inode behind
2940 * the dir item was already processed.
2942 static int can_rmdir(struct send_ctx *sctx, u64 dir, u64 dir_gen,
2946 struct btrfs_root *root = sctx->parent_root;
2947 struct btrfs_path *path;
2948 struct btrfs_key key;
2949 struct btrfs_key found_key;
2950 struct btrfs_key loc;
2951 struct btrfs_dir_item *di;
2952 struct orphan_dir_info *odi = NULL;
2955 * Don't try to rmdir the top/root subvolume dir.
2957 if (dir == BTRFS_FIRST_FREE_OBJECTID)
2960 path = alloc_path_for_send();
2965 key.type = BTRFS_DIR_INDEX_KEY;
2968 odi = get_orphan_dir_info(sctx, dir, dir_gen);
2970 key.offset = odi->last_dir_index_offset;
2972 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2977 struct waiting_dir_move *dm;
2979 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2980 ret = btrfs_next_leaf(root, path);
2987 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2989 if (found_key.objectid != key.objectid ||
2990 found_key.type != key.type)
2993 di = btrfs_item_ptr(path->nodes[0], path->slots[0],
2994 struct btrfs_dir_item);
2995 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &loc);
2997 dm = get_waiting_dir_move(sctx, loc.objectid);
2999 odi = add_orphan_dir_info(sctx, dir, dir_gen);
3005 odi->last_dir_index_offset = found_key.offset;
3006 dm->rmdir_ino = dir;
3007 dm->rmdir_gen = dir_gen;
3012 if (loc.objectid > send_progress) {
3013 odi = add_orphan_dir_info(sctx, dir, dir_gen);
3019 odi->last_dir_index_offset = found_key.offset;
3026 free_orphan_dir_info(sctx, odi);
3031 btrfs_free_path(path);
3035 static int is_waiting_for_move(struct send_ctx *sctx, u64 ino)
3037 struct waiting_dir_move *entry = get_waiting_dir_move(sctx, ino);
3039 return entry != NULL;
3042 static int add_waiting_dir_move(struct send_ctx *sctx, u64 ino, bool orphanized)
3044 struct rb_node **p = &sctx->waiting_dir_moves.rb_node;
3045 struct rb_node *parent = NULL;
3046 struct waiting_dir_move *entry, *dm;
3048 dm = kmalloc(sizeof(*dm), GFP_KERNEL);
3054 dm->orphanized = orphanized;
3058 entry = rb_entry(parent, struct waiting_dir_move, node);
3059 if (ino < entry->ino) {
3061 } else if (ino > entry->ino) {
3062 p = &(*p)->rb_right;
3069 rb_link_node(&dm->node, parent, p);
3070 rb_insert_color(&dm->node, &sctx->waiting_dir_moves);
3074 static struct waiting_dir_move *
3075 get_waiting_dir_move(struct send_ctx *sctx, u64 ino)
3077 struct rb_node *n = sctx->waiting_dir_moves.rb_node;
3078 struct waiting_dir_move *entry;
3081 entry = rb_entry(n, struct waiting_dir_move, node);
3082 if (ino < entry->ino)
3084 else if (ino > entry->ino)
3092 static void free_waiting_dir_move(struct send_ctx *sctx,
3093 struct waiting_dir_move *dm)
3097 rb_erase(&dm->node, &sctx->waiting_dir_moves);
3101 static int add_pending_dir_move(struct send_ctx *sctx,
3105 struct list_head *new_refs,
3106 struct list_head *deleted_refs,
3107 const bool is_orphan)
3109 struct rb_node **p = &sctx->pending_dir_moves.rb_node;
3110 struct rb_node *parent = NULL;
3111 struct pending_dir_move *entry = NULL, *pm;
3112 struct recorded_ref *cur;
3116 pm = kmalloc(sizeof(*pm), GFP_KERNEL);
3119 pm->parent_ino = parent_ino;
3122 INIT_LIST_HEAD(&pm->list);
3123 INIT_LIST_HEAD(&pm->update_refs);
3124 RB_CLEAR_NODE(&pm->node);
3128 entry = rb_entry(parent, struct pending_dir_move, node);
3129 if (parent_ino < entry->parent_ino) {
3131 } else if (parent_ino > entry->parent_ino) {
3132 p = &(*p)->rb_right;
3139 list_for_each_entry(cur, deleted_refs, list) {
3140 ret = dup_ref(cur, &pm->update_refs);
3144 list_for_each_entry(cur, new_refs, list) {
3145 ret = dup_ref(cur, &pm->update_refs);
3150 ret = add_waiting_dir_move(sctx, pm->ino, is_orphan);
3155 list_add_tail(&pm->list, &entry->list);
3157 rb_link_node(&pm->node, parent, p);
3158 rb_insert_color(&pm->node, &sctx->pending_dir_moves);
3163 __free_recorded_refs(&pm->update_refs);
3169 static struct pending_dir_move *get_pending_dir_moves(struct send_ctx *sctx,
3172 struct rb_node *n = sctx->pending_dir_moves.rb_node;
3173 struct pending_dir_move *entry;
3176 entry = rb_entry(n, struct pending_dir_move, node);
3177 if (parent_ino < entry->parent_ino)
3179 else if (parent_ino > entry->parent_ino)
3187 static int path_loop(struct send_ctx *sctx, struct fs_path *name,
3188 u64 ino, u64 gen, u64 *ancestor_ino)
3191 u64 parent_inode = 0;
3193 u64 start_ino = ino;
3196 while (ino != BTRFS_FIRST_FREE_OBJECTID) {
3197 fs_path_reset(name);
3199 if (is_waiting_for_rm(sctx, ino, gen))
3201 if (is_waiting_for_move(sctx, ino)) {
3202 if (*ancestor_ino == 0)
3203 *ancestor_ino = ino;
3204 ret = get_first_ref(sctx->parent_root, ino,
3205 &parent_inode, &parent_gen, name);
3207 ret = __get_cur_name_and_parent(sctx, ino, gen,
3217 if (parent_inode == start_ino) {
3219 if (*ancestor_ino == 0)
3220 *ancestor_ino = ino;
3229 static int apply_dir_move(struct send_ctx *sctx, struct pending_dir_move *pm)
3231 struct fs_path *from_path = NULL;
3232 struct fs_path *to_path = NULL;
3233 struct fs_path *name = NULL;
3234 u64 orig_progress = sctx->send_progress;
3235 struct recorded_ref *cur;
3236 u64 parent_ino, parent_gen;
3237 struct waiting_dir_move *dm = NULL;
3244 name = fs_path_alloc();
3245 from_path = fs_path_alloc();
3246 if (!name || !from_path) {
3251 dm = get_waiting_dir_move(sctx, pm->ino);
3253 rmdir_ino = dm->rmdir_ino;
3254 rmdir_gen = dm->rmdir_gen;
3255 is_orphan = dm->orphanized;
3256 free_waiting_dir_move(sctx, dm);
3259 ret = gen_unique_name(sctx, pm->ino,
3260 pm->gen, from_path);
3262 ret = get_first_ref(sctx->parent_root, pm->ino,
3263 &parent_ino, &parent_gen, name);
3266 ret = get_cur_path(sctx, parent_ino, parent_gen,
3270 ret = fs_path_add_path(from_path, name);
3275 sctx->send_progress = sctx->cur_ino + 1;
3276 ret = path_loop(sctx, name, pm->ino, pm->gen, &ancestor);
3280 LIST_HEAD(deleted_refs);
3281 ASSERT(ancestor > BTRFS_FIRST_FREE_OBJECTID);
3282 ret = add_pending_dir_move(sctx, pm->ino, pm->gen, ancestor,
3283 &pm->update_refs, &deleted_refs,
3288 dm = get_waiting_dir_move(sctx, pm->ino);
3290 dm->rmdir_ino = rmdir_ino;
3291 dm->rmdir_gen = rmdir_gen;
3295 fs_path_reset(name);
3298 ret = get_cur_path(sctx, pm->ino, pm->gen, to_path);
3302 ret = send_rename(sctx, from_path, to_path);
3307 struct orphan_dir_info *odi;
3310 odi = get_orphan_dir_info(sctx, rmdir_ino, rmdir_gen);
3312 /* already deleted */
3317 ret = can_rmdir(sctx, rmdir_ino, gen, sctx->cur_ino);
3323 name = fs_path_alloc();
3328 ret = get_cur_path(sctx, rmdir_ino, gen, name);
3331 ret = send_rmdir(sctx, name);
3337 ret = send_utimes(sctx, pm->ino, pm->gen);
3342 * After rename/move, need to update the utimes of both new parent(s)
3343 * and old parent(s).
3345 list_for_each_entry(cur, &pm->update_refs, list) {
3347 * The parent inode might have been deleted in the send snapshot
3349 ret = get_inode_info(sctx->send_root, cur->dir, NULL,
3350 NULL, NULL, NULL, NULL, NULL);
3351 if (ret == -ENOENT) {
3358 ret = send_utimes(sctx, cur->dir, cur->dir_gen);
3365 fs_path_free(from_path);
3366 fs_path_free(to_path);
3367 sctx->send_progress = orig_progress;
3372 static void free_pending_move(struct send_ctx *sctx, struct pending_dir_move *m)
3374 if (!list_empty(&m->list))
3376 if (!RB_EMPTY_NODE(&m->node))
3377 rb_erase(&m->node, &sctx->pending_dir_moves);
3378 __free_recorded_refs(&m->update_refs);
3382 static void tail_append_pending_moves(struct send_ctx *sctx,
3383 struct pending_dir_move *moves,
3384 struct list_head *stack)
3386 if (list_empty(&moves->list)) {
3387 list_add_tail(&moves->list, stack);
3390 list_splice_init(&moves->list, &list);
3391 list_add_tail(&moves->list, stack);
3392 list_splice_tail(&list, stack);
3394 if (!RB_EMPTY_NODE(&moves->node)) {
3395 rb_erase(&moves->node, &sctx->pending_dir_moves);
3396 RB_CLEAR_NODE(&moves->node);
3400 static int apply_children_dir_moves(struct send_ctx *sctx)
3402 struct pending_dir_move *pm;
3403 struct list_head stack;
3404 u64 parent_ino = sctx->cur_ino;
3407 pm = get_pending_dir_moves(sctx, parent_ino);
3411 INIT_LIST_HEAD(&stack);
3412 tail_append_pending_moves(sctx, pm, &stack);
3414 while (!list_empty(&stack)) {
3415 pm = list_first_entry(&stack, struct pending_dir_move, list);
3416 parent_ino = pm->ino;
3417 ret = apply_dir_move(sctx, pm);
3418 free_pending_move(sctx, pm);
3421 pm = get_pending_dir_moves(sctx, parent_ino);
3423 tail_append_pending_moves(sctx, pm, &stack);
3428 while (!list_empty(&stack)) {
3429 pm = list_first_entry(&stack, struct pending_dir_move, list);
3430 free_pending_move(sctx, pm);
3436 * We might need to delay a directory rename even when no ancestor directory
3437 * (in the send root) with a higher inode number than ours (sctx->cur_ino) was
3438 * renamed. This happens when we rename a directory to the old name (the name
3439 * in the parent root) of some other unrelated directory that got its rename
3440 * delayed due to some ancestor with higher number that got renamed.
3446 * |---- a/ (ino 257)
3447 * | |---- file (ino 260)
3449 * |---- b/ (ino 258)
3450 * |---- c/ (ino 259)
3454 * |---- a/ (ino 258)
3455 * |---- x/ (ino 259)
3456 * |---- y/ (ino 257)
3457 * |----- file (ino 260)
3459 * Here we can not rename 258 from 'b' to 'a' without the rename of inode 257
3460 * from 'a' to 'x/y' happening first, which in turn depends on the rename of
3461 * inode 259 from 'c' to 'x'. So the order of rename commands the send stream
3464 * 1 - rename 259 from 'c' to 'x'
3465 * 2 - rename 257 from 'a' to 'x/y'
3466 * 3 - rename 258 from 'b' to 'a'
3468 * Returns 1 if the rename of sctx->cur_ino needs to be delayed, 0 if it can
3469 * be done right away and < 0 on error.
3471 static int wait_for_dest_dir_move(struct send_ctx *sctx,
3472 struct recorded_ref *parent_ref,
3473 const bool is_orphan)
3475 struct btrfs_fs_info *fs_info = sctx->parent_root->fs_info;
3476 struct btrfs_path *path;
3477 struct btrfs_key key;
3478 struct btrfs_key di_key;
3479 struct btrfs_dir_item *di;
3483 struct waiting_dir_move *wdm;
3485 if (RB_EMPTY_ROOT(&sctx->waiting_dir_moves))
3488 path = alloc_path_for_send();
3492 key.objectid = parent_ref->dir;
3493 key.type = BTRFS_DIR_ITEM_KEY;
3494 key.offset = btrfs_name_hash(parent_ref->name, parent_ref->name_len);
3496 ret = btrfs_search_slot(NULL, sctx->parent_root, &key, path, 0, 0);
3499 } else if (ret > 0) {
3504 di = btrfs_match_dir_item_name(fs_info, path, parent_ref->name,
3505 parent_ref->name_len);
3511 * di_key.objectid has the number of the inode that has a dentry in the
3512 * parent directory with the same name that sctx->cur_ino is being
3513 * renamed to. We need to check if that inode is in the send root as
3514 * well and if it is currently marked as an inode with a pending rename,
3515 * if it is, we need to delay the rename of sctx->cur_ino as well, so
3516 * that it happens after that other inode is renamed.
3518 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &di_key);
3519 if (di_key.type != BTRFS_INODE_ITEM_KEY) {
3524 ret = get_inode_info(sctx->parent_root, di_key.objectid, NULL,
3525 &left_gen, NULL, NULL, NULL, NULL);
3528 ret = get_inode_info(sctx->send_root, di_key.objectid, NULL,
3529 &right_gen, NULL, NULL, NULL, NULL);
3536 /* Different inode, no need to delay the rename of sctx->cur_ino */
3537 if (right_gen != left_gen) {
3542 wdm = get_waiting_dir_move(sctx, di_key.objectid);
3543 if (wdm && !wdm->orphanized) {
3544 ret = add_pending_dir_move(sctx,
3546 sctx->cur_inode_gen,
3549 &sctx->deleted_refs,
3555 btrfs_free_path(path);
3560 * Check if inode ino2, or any of its ancestors, is inode ino1.
3561 * Return 1 if true, 0 if false and < 0 on error.
3563 static int check_ino_in_path(struct btrfs_root *root,
3568 struct fs_path *fs_path)
3573 return ino1_gen == ino2_gen;
3575 while (ino > BTRFS_FIRST_FREE_OBJECTID) {
3580 fs_path_reset(fs_path);
3581 ret = get_first_ref(root, ino, &parent, &parent_gen, fs_path);
3585 return parent_gen == ino1_gen;
3592 * Check if ino ino1 is an ancestor of inode ino2 in the given root for any
3593 * possible path (in case ino2 is not a directory and has multiple hard links).
3594 * Return 1 if true, 0 if false and < 0 on error.
3596 static int is_ancestor(struct btrfs_root *root,
3600 struct fs_path *fs_path)
3602 bool free_fs_path = false;
3604 struct btrfs_path *path = NULL;
3605 struct btrfs_key key;
3608 fs_path = fs_path_alloc();
3611 free_fs_path = true;
3614 path = alloc_path_for_send();
3620 key.objectid = ino2;
3621 key.type = BTRFS_INODE_REF_KEY;
3624 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3629 struct extent_buffer *leaf = path->nodes[0];
3630 int slot = path->slots[0];
3634 if (slot >= btrfs_header_nritems(leaf)) {
3635 ret = btrfs_next_leaf(root, path);
3643 btrfs_item_key_to_cpu(leaf, &key, slot);
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_nr(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);
3676 ret = check_ino_in_path(root, ino1, ino1_gen,
3677 parent, parent_gen, fs_path);
3685 btrfs_free_path(path);
3687 fs_path_free(fs_path);
3691 static int wait_for_parent_move(struct send_ctx *sctx,
3692 struct recorded_ref *parent_ref,
3693 const bool is_orphan)
3696 u64 ino = parent_ref->dir;
3697 u64 ino_gen = parent_ref->dir_gen;
3698 u64 parent_ino_before, parent_ino_after;
3699 struct fs_path *path_before = NULL;
3700 struct fs_path *path_after = NULL;
3703 path_after = fs_path_alloc();
3704 path_before = fs_path_alloc();
3705 if (!path_after || !path_before) {
3711 * Our current directory inode may not yet be renamed/moved because some
3712 * ancestor (immediate or not) has to be renamed/moved first. So find if
3713 * such ancestor exists and make sure our own rename/move happens after
3714 * that ancestor is processed to avoid path build infinite loops (done
3715 * at get_cur_path()).
3717 while (ino > BTRFS_FIRST_FREE_OBJECTID) {
3718 u64 parent_ino_after_gen;
3720 if (is_waiting_for_move(sctx, ino)) {
3722 * If the current inode is an ancestor of ino in the
3723 * parent root, we need to delay the rename of the
3724 * current inode, otherwise don't delayed the rename
3725 * because we can end up with a circular dependency
3726 * of renames, resulting in some directories never
3727 * getting the respective rename operations issued in
3728 * the send stream or getting into infinite path build
3731 ret = is_ancestor(sctx->parent_root,
3732 sctx->cur_ino, sctx->cur_inode_gen,
3738 fs_path_reset(path_before);
3739 fs_path_reset(path_after);
3741 ret = get_first_ref(sctx->send_root, ino, &parent_ino_after,
3742 &parent_ino_after_gen, path_after);
3745 ret = get_first_ref(sctx->parent_root, ino, &parent_ino_before,
3747 if (ret < 0 && ret != -ENOENT) {
3749 } else if (ret == -ENOENT) {
3754 len1 = fs_path_len(path_before);
3755 len2 = fs_path_len(path_after);
3756 if (ino > sctx->cur_ino &&
3757 (parent_ino_before != parent_ino_after || len1 != len2 ||
3758 memcmp(path_before->start, path_after->start, len1))) {
3761 ret = get_inode_info(sctx->parent_root, ino, NULL,
3762 &parent_ino_gen, NULL, NULL, NULL,
3766 if (ino_gen == parent_ino_gen) {
3771 ino = parent_ino_after;
3772 ino_gen = parent_ino_after_gen;
3776 fs_path_free(path_before);
3777 fs_path_free(path_after);
3780 ret = add_pending_dir_move(sctx,
3782 sctx->cur_inode_gen,
3785 &sctx->deleted_refs,
3794 static int update_ref_path(struct send_ctx *sctx, struct recorded_ref *ref)
3797 struct fs_path *new_path;
3800 * Our reference's name member points to its full_path member string, so
3801 * we use here a new path.
3803 new_path = fs_path_alloc();
3807 ret = get_cur_path(sctx, ref->dir, ref->dir_gen, new_path);
3809 fs_path_free(new_path);
3812 ret = fs_path_add(new_path, ref->name, ref->name_len);
3814 fs_path_free(new_path);
3818 fs_path_free(ref->full_path);
3819 set_ref_path(ref, new_path);
3825 * When processing the new references for an inode we may orphanize an existing
3826 * directory inode because its old name conflicts with one of the new references
3827 * of the current inode. Later, when processing another new reference of our
3828 * inode, we might need to orphanize another inode, but the path we have in the
3829 * reference reflects the pre-orphanization name of the directory we previously
3830 * orphanized. For example:
3832 * parent snapshot looks like:
3835 * |----- f1 (ino 257)
3836 * |----- f2 (ino 258)
3837 * |----- d1/ (ino 259)
3838 * |----- d2/ (ino 260)
3840 * send snapshot looks like:
3843 * |----- d1 (ino 258)
3844 * |----- f2/ (ino 259)
3845 * |----- f2_link/ (ino 260)
3846 * | |----- f1 (ino 257)
3848 * |----- d2 (ino 258)
3850 * When processing inode 257 we compute the name for inode 259 as "d1", and we
3851 * cache it in the name cache. Later when we start processing inode 258, when
3852 * collecting all its new references we set a full path of "d1/d2" for its new
3853 * reference with name "d2". When we start processing the new references we
3854 * start by processing the new reference with name "d1", and this results in
3855 * orphanizing inode 259, since its old reference causes a conflict. Then we
3856 * move on the next new reference, with name "d2", and we find out we must
3857 * orphanize inode 260, as its old reference conflicts with ours - but for the
3858 * orphanization we use a source path corresponding to the path we stored in the
3859 * new reference, which is "d1/d2" and not "o259-6-0/d2" - this makes the
3860 * receiver fail since the path component "d1/" no longer exists, it was renamed
3861 * to "o259-6-0/" when processing the previous new reference. So in this case we
3862 * must recompute the path in the new reference and use it for the new
3863 * orphanization operation.
3865 static int refresh_ref_path(struct send_ctx *sctx, struct recorded_ref *ref)
3870 name = kmemdup(ref->name, ref->name_len, GFP_KERNEL);
3874 fs_path_reset(ref->full_path);
3875 ret = get_cur_path(sctx, ref->dir, ref->dir_gen, ref->full_path);
3879 ret = fs_path_add(ref->full_path, name, ref->name_len);
3883 /* Update the reference's base name pointer. */
3884 set_ref_path(ref, ref->full_path);
3891 * This does all the move/link/unlink/rmdir magic.
3893 static int process_recorded_refs(struct send_ctx *sctx, int *pending_move)
3895 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
3897 struct recorded_ref *cur;
3898 struct recorded_ref *cur2;
3899 struct list_head check_dirs;
3900 struct fs_path *valid_path = NULL;
3904 int did_overwrite = 0;
3906 u64 last_dir_ino_rm = 0;
3907 bool can_rename = true;
3908 bool orphanized_dir = false;
3909 bool orphanized_ancestor = false;
3911 btrfs_debug(fs_info, "process_recorded_refs %llu", sctx->cur_ino);
3914 * This should never happen as the root dir always has the same ref
3915 * which is always '..'
3917 BUG_ON(sctx->cur_ino <= BTRFS_FIRST_FREE_OBJECTID);
3918 INIT_LIST_HEAD(&check_dirs);
3920 valid_path = fs_path_alloc();
3927 * First, check if the first ref of the current inode was overwritten
3928 * before. If yes, we know that the current inode was already orphanized
3929 * and thus use the orphan name. If not, we can use get_cur_path to
3930 * get the path of the first ref as it would like while receiving at
3931 * this point in time.
3932 * New inodes are always orphan at the beginning, so force to use the
3933 * orphan name in this case.
3934 * The first ref is stored in valid_path and will be updated if it
3935 * gets moved around.
3937 if (!sctx->cur_inode_new) {
3938 ret = did_overwrite_first_ref(sctx, sctx->cur_ino,
3939 sctx->cur_inode_gen);
3945 if (sctx->cur_inode_new || did_overwrite) {
3946 ret = gen_unique_name(sctx, sctx->cur_ino,
3947 sctx->cur_inode_gen, valid_path);
3952 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen,
3959 * Before doing any rename and link operations, do a first pass on the
3960 * new references to orphanize any unprocessed inodes that may have a
3961 * reference that conflicts with one of the new references of the current
3962 * inode. This needs to happen first because a new reference may conflict
3963 * with the old reference of a parent directory, so we must make sure
3964 * that the path used for link and rename commands don't use an
3965 * orphanized name when an ancestor was not yet orphanized.
3972 * |----- testdir/ (ino 259)
3973 * | |----- a (ino 257)
3975 * |----- b (ino 258)
3980 * |----- testdir_2/ (ino 259)
3981 * | |----- a (ino 260)
3983 * |----- testdir (ino 257)
3984 * |----- b (ino 257)
3985 * |----- b2 (ino 258)
3987 * Processing the new reference for inode 257 with name "b" may happen
3988 * before processing the new reference with name "testdir". If so, we
3989 * must make sure that by the time we send a link command to create the
3990 * hard link "b", inode 259 was already orphanized, since the generated
3991 * path in "valid_path" already contains the orphanized name for 259.
3992 * We are processing inode 257, so only later when processing 259 we do
3993 * the rename operation to change its temporary (orphanized) name to
3996 list_for_each_entry(cur, &sctx->new_refs, list) {
3997 ret = get_cur_inode_state(sctx, cur->dir, cur->dir_gen);
4000 if (ret == inode_state_will_create)
4004 * Check if this new ref would overwrite the first ref of another
4005 * unprocessed inode. If yes, orphanize the overwritten inode.
4006 * If we find an overwritten ref that is not the first ref,
4009 ret = will_overwrite_ref(sctx, cur->dir, cur->dir_gen,
4010 cur->name, cur->name_len,
4011 &ow_inode, &ow_gen, &ow_mode);
4015 ret = is_first_ref(sctx->parent_root,
4016 ow_inode, cur->dir, cur->name,
4021 struct name_cache_entry *nce;
4022 struct waiting_dir_move *wdm;
4024 if (orphanized_dir) {
4025 ret = refresh_ref_path(sctx, cur);
4030 ret = orphanize_inode(sctx, ow_inode, ow_gen,
4034 if (S_ISDIR(ow_mode))
4035 orphanized_dir = true;
4038 * If ow_inode has its rename operation delayed
4039 * make sure that its orphanized name is used in
4040 * the source path when performing its rename
4043 if (is_waiting_for_move(sctx, ow_inode)) {
4044 wdm = get_waiting_dir_move(sctx,
4047 wdm->orphanized = true;
4051 * Make sure we clear our orphanized inode's
4052 * name from the name cache. This is because the
4053 * inode ow_inode might be an ancestor of some
4054 * other inode that will be orphanized as well
4055 * later and has an inode number greater than
4056 * sctx->send_progress. We need to prevent
4057 * future name lookups from using the old name
4058 * and get instead the orphan name.
4060 nce = name_cache_search(sctx, ow_inode, ow_gen);
4062 name_cache_delete(sctx, nce);
4067 * ow_inode might currently be an ancestor of
4068 * cur_ino, therefore compute valid_path (the
4069 * current path of cur_ino) again because it
4070 * might contain the pre-orphanization name of
4071 * ow_inode, which is no longer valid.
4073 ret = is_ancestor(sctx->parent_root,
4075 sctx->cur_ino, NULL);
4077 orphanized_ancestor = true;
4078 fs_path_reset(valid_path);
4079 ret = get_cur_path(sctx, sctx->cur_ino,
4080 sctx->cur_inode_gen,
4087 * If we previously orphanized a directory that
4088 * collided with a new reference that we already
4089 * processed, recompute the current path because
4090 * that directory may be part of the path.
4092 if (orphanized_dir) {
4093 ret = refresh_ref_path(sctx, cur);
4097 ret = send_unlink(sctx, cur->full_path);
4105 list_for_each_entry(cur, &sctx->new_refs, list) {
4107 * We may have refs where the parent directory does not exist
4108 * yet. This happens if the parent directories inum is higher
4109 * than the current inum. To handle this case, we create the
4110 * parent directory out of order. But we need to check if this
4111 * did already happen before due to other refs in the same dir.
4113 ret = get_cur_inode_state(sctx, cur->dir, cur->dir_gen);
4116 if (ret == inode_state_will_create) {
4119 * First check if any of the current inodes refs did
4120 * already create the dir.
4122 list_for_each_entry(cur2, &sctx->new_refs, list) {
4125 if (cur2->dir == cur->dir) {
4132 * If that did not happen, check if a previous inode
4133 * did already create the dir.
4136 ret = did_create_dir(sctx, cur->dir);
4140 ret = send_create_inode(sctx, cur->dir);
4146 if (S_ISDIR(sctx->cur_inode_mode) && sctx->parent_root) {
4147 ret = wait_for_dest_dir_move(sctx, cur, is_orphan);
4156 if (S_ISDIR(sctx->cur_inode_mode) && sctx->parent_root &&
4158 ret = wait_for_parent_move(sctx, cur, is_orphan);
4168 * link/move the ref to the new place. If we have an orphan
4169 * inode, move it and update valid_path. If not, link or move
4170 * it depending on the inode mode.
4172 if (is_orphan && can_rename) {
4173 ret = send_rename(sctx, valid_path, cur->full_path);
4177 ret = fs_path_copy(valid_path, cur->full_path);
4180 } else if (can_rename) {
4181 if (S_ISDIR(sctx->cur_inode_mode)) {
4183 * Dirs can't be linked, so move it. For moved
4184 * dirs, we always have one new and one deleted
4185 * ref. The deleted ref is ignored later.
4187 ret = send_rename(sctx, valid_path,
4190 ret = fs_path_copy(valid_path,
4196 * We might have previously orphanized an inode
4197 * which is an ancestor of our current inode,
4198 * so our reference's full path, which was
4199 * computed before any such orphanizations, must
4202 if (orphanized_dir) {
4203 ret = update_ref_path(sctx, cur);
4207 ret = send_link(sctx, cur->full_path,
4213 ret = dup_ref(cur, &check_dirs);
4218 if (S_ISDIR(sctx->cur_inode_mode) && sctx->cur_inode_deleted) {
4220 * Check if we can already rmdir the directory. If not,
4221 * orphanize it. For every dir item inside that gets deleted
4222 * later, we do this check again and rmdir it then if possible.
4223 * See the use of check_dirs for more details.
4225 ret = can_rmdir(sctx, sctx->cur_ino, sctx->cur_inode_gen,
4230 ret = send_rmdir(sctx, valid_path);
4233 } else if (!is_orphan) {
4234 ret = orphanize_inode(sctx, sctx->cur_ino,
4235 sctx->cur_inode_gen, valid_path);
4241 list_for_each_entry(cur, &sctx->deleted_refs, list) {
4242 ret = dup_ref(cur, &check_dirs);
4246 } else if (S_ISDIR(sctx->cur_inode_mode) &&
4247 !list_empty(&sctx->deleted_refs)) {
4249 * We have a moved dir. Add the old parent to check_dirs
4251 cur = list_entry(sctx->deleted_refs.next, struct recorded_ref,
4253 ret = dup_ref(cur, &check_dirs);
4256 } else if (!S_ISDIR(sctx->cur_inode_mode)) {
4258 * We have a non dir inode. Go through all deleted refs and
4259 * unlink them if they were not already overwritten by other
4262 list_for_each_entry(cur, &sctx->deleted_refs, list) {
4263 ret = did_overwrite_ref(sctx, cur->dir, cur->dir_gen,
4264 sctx->cur_ino, sctx->cur_inode_gen,
4265 cur->name, cur->name_len);
4270 * If we orphanized any ancestor before, we need
4271 * to recompute the full path for deleted names,
4272 * since any such path was computed before we
4273 * processed any references and orphanized any
4276 if (orphanized_ancestor) {
4277 ret = update_ref_path(sctx, cur);
4281 ret = send_unlink(sctx, cur->full_path);
4285 ret = dup_ref(cur, &check_dirs);
4290 * If the inode is still orphan, unlink the orphan. This may
4291 * happen when a previous inode did overwrite the first ref
4292 * of this inode and no new refs were added for the current
4293 * inode. Unlinking does not mean that the inode is deleted in
4294 * all cases. There may still be links to this inode in other
4298 ret = send_unlink(sctx, valid_path);
4305 * We did collect all parent dirs where cur_inode was once located. We
4306 * now go through all these dirs and check if they are pending for
4307 * deletion and if it's finally possible to perform the rmdir now.
4308 * We also update the inode stats of the parent dirs here.
4310 list_for_each_entry(cur, &check_dirs, list) {
4312 * In case we had refs into dirs that were not processed yet,
4313 * we don't need to do the utime and rmdir logic for these dirs.
4314 * The dir will be processed later.
4316 if (cur->dir > sctx->cur_ino)
4319 ret = get_cur_inode_state(sctx, cur->dir, cur->dir_gen);
4323 if (ret == inode_state_did_create ||
4324 ret == inode_state_no_change) {
4325 /* TODO delayed utimes */
4326 ret = send_utimes(sctx, cur->dir, cur->dir_gen);
4329 } else if (ret == inode_state_did_delete &&
4330 cur->dir != last_dir_ino_rm) {
4331 ret = can_rmdir(sctx, cur->dir, cur->dir_gen,
4336 ret = get_cur_path(sctx, cur->dir,
4337 cur->dir_gen, valid_path);
4340 ret = send_rmdir(sctx, valid_path);
4343 last_dir_ino_rm = cur->dir;
4351 __free_recorded_refs(&check_dirs);
4352 free_recorded_refs(sctx);
4353 fs_path_free(valid_path);
4357 static int record_ref(struct btrfs_root *root, u64 dir, struct fs_path *name,
4358 void *ctx, struct list_head *refs)
4361 struct send_ctx *sctx = ctx;
4365 p = fs_path_alloc();
4369 ret = get_inode_info(root, dir, NULL, &gen, NULL, NULL,
4374 ret = get_cur_path(sctx, dir, gen, p);
4377 ret = fs_path_add_path(p, name);
4381 ret = __record_ref(refs, dir, gen, p);
4389 static int __record_new_ref(int num, u64 dir, int index,
4390 struct fs_path *name,
4393 struct send_ctx *sctx = ctx;
4394 return record_ref(sctx->send_root, dir, name, ctx, &sctx->new_refs);
4398 static int __record_deleted_ref(int num, u64 dir, int index,
4399 struct fs_path *name,
4402 struct send_ctx *sctx = ctx;
4403 return record_ref(sctx->parent_root, dir, name, ctx,
4404 &sctx->deleted_refs);
4407 static int record_new_ref(struct send_ctx *sctx)
4411 ret = iterate_inode_ref(sctx->send_root, sctx->left_path,
4412 sctx->cmp_key, 0, __record_new_ref, sctx);
4421 static int record_deleted_ref(struct send_ctx *sctx)
4425 ret = iterate_inode_ref(sctx->parent_root, sctx->right_path,
4426 sctx->cmp_key, 0, __record_deleted_ref, sctx);
4435 struct find_ref_ctx {
4438 struct btrfs_root *root;
4439 struct fs_path *name;
4443 static int __find_iref(int num, u64 dir, int index,
4444 struct fs_path *name,
4447 struct find_ref_ctx *ctx = ctx_;
4451 if (dir == ctx->dir && fs_path_len(name) == fs_path_len(ctx->name) &&
4452 strncmp(name->start, ctx->name->start, fs_path_len(name)) == 0) {
4454 * To avoid doing extra lookups we'll only do this if everything
4457 ret = get_inode_info(ctx->root, dir, NULL, &dir_gen, NULL,
4461 if (dir_gen != ctx->dir_gen)
4463 ctx->found_idx = num;
4469 static int find_iref(struct btrfs_root *root,
4470 struct btrfs_path *path,
4471 struct btrfs_key *key,
4472 u64 dir, u64 dir_gen, struct fs_path *name)
4475 struct find_ref_ctx ctx;
4479 ctx.dir_gen = dir_gen;
4483 ret = iterate_inode_ref(root, path, key, 0, __find_iref, &ctx);
4487 if (ctx.found_idx == -1)
4490 return ctx.found_idx;
4493 static int __record_changed_new_ref(int num, u64 dir, int index,
4494 struct fs_path *name,
4499 struct send_ctx *sctx = ctx;
4501 ret = get_inode_info(sctx->send_root, dir, NULL, &dir_gen, NULL,
4506 ret = find_iref(sctx->parent_root, sctx->right_path,
4507 sctx->cmp_key, dir, dir_gen, name);
4509 ret = __record_new_ref(num, dir, index, name, sctx);
4516 static int __record_changed_deleted_ref(int num, u64 dir, int index,
4517 struct fs_path *name,
4522 struct send_ctx *sctx = ctx;
4524 ret = get_inode_info(sctx->parent_root, dir, NULL, &dir_gen, NULL,
4529 ret = find_iref(sctx->send_root, sctx->left_path, sctx->cmp_key,
4530 dir, dir_gen, name);
4532 ret = __record_deleted_ref(num, dir, index, name, sctx);
4539 static int record_changed_ref(struct send_ctx *sctx)
4543 ret = iterate_inode_ref(sctx->send_root, sctx->left_path,
4544 sctx->cmp_key, 0, __record_changed_new_ref, sctx);
4547 ret = iterate_inode_ref(sctx->parent_root, sctx->right_path,
4548 sctx->cmp_key, 0, __record_changed_deleted_ref, sctx);
4558 * Record and process all refs at once. Needed when an inode changes the
4559 * generation number, which means that it was deleted and recreated.
4561 static int process_all_refs(struct send_ctx *sctx,
4562 enum btrfs_compare_tree_result cmd)
4565 struct btrfs_root *root;
4566 struct btrfs_path *path;
4567 struct btrfs_key key;
4568 struct btrfs_key found_key;
4569 struct extent_buffer *eb;
4571 iterate_inode_ref_t cb;
4572 int pending_move = 0;
4574 path = alloc_path_for_send();
4578 if (cmd == BTRFS_COMPARE_TREE_NEW) {
4579 root = sctx->send_root;
4580 cb = __record_new_ref;
4581 } else if (cmd == BTRFS_COMPARE_TREE_DELETED) {
4582 root = sctx->parent_root;
4583 cb = __record_deleted_ref;
4585 btrfs_err(sctx->send_root->fs_info,
4586 "Wrong command %d in process_all_refs", cmd);
4591 key.objectid = sctx->cmp_key->objectid;
4592 key.type = BTRFS_INODE_REF_KEY;
4594 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4599 eb = path->nodes[0];
4600 slot = path->slots[0];
4601 if (slot >= btrfs_header_nritems(eb)) {
4602 ret = btrfs_next_leaf(root, path);
4610 btrfs_item_key_to_cpu(eb, &found_key, slot);
4612 if (found_key.objectid != key.objectid ||
4613 (found_key.type != BTRFS_INODE_REF_KEY &&
4614 found_key.type != BTRFS_INODE_EXTREF_KEY))
4617 ret = iterate_inode_ref(root, path, &found_key, 0, cb, sctx);
4623 btrfs_release_path(path);
4626 * We don't actually care about pending_move as we are simply
4627 * re-creating this inode and will be rename'ing it into place once we
4628 * rename the parent directory.
4630 ret = process_recorded_refs(sctx, &pending_move);
4632 btrfs_free_path(path);
4636 static int send_set_xattr(struct send_ctx *sctx,
4637 struct fs_path *path,
4638 const char *name, int name_len,
4639 const char *data, int data_len)
4643 ret = begin_cmd(sctx, BTRFS_SEND_C_SET_XATTR);
4647 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
4648 TLV_PUT_STRING(sctx, BTRFS_SEND_A_XATTR_NAME, name, name_len);
4649 TLV_PUT(sctx, BTRFS_SEND_A_XATTR_DATA, data, data_len);
4651 ret = send_cmd(sctx);
4658 static int send_remove_xattr(struct send_ctx *sctx,
4659 struct fs_path *path,
4660 const char *name, int name_len)
4664 ret = begin_cmd(sctx, BTRFS_SEND_C_REMOVE_XATTR);
4668 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
4669 TLV_PUT_STRING(sctx, BTRFS_SEND_A_XATTR_NAME, name, name_len);
4671 ret = send_cmd(sctx);
4678 static int __process_new_xattr(int num, struct btrfs_key *di_key,
4679 const char *name, int name_len,
4680 const char *data, int data_len,
4684 struct send_ctx *sctx = ctx;
4686 struct posix_acl_xattr_header dummy_acl;
4688 /* Capabilities are emitted by finish_inode_if_needed */
4689 if (!strncmp(name, XATTR_NAME_CAPS, name_len))
4692 p = fs_path_alloc();
4697 * This hack is needed because empty acls are stored as zero byte
4698 * data in xattrs. Problem with that is, that receiving these zero byte
4699 * acls will fail later. To fix this, we send a dummy acl list that
4700 * only contains the version number and no entries.
4702 if (!strncmp(name, XATTR_NAME_POSIX_ACL_ACCESS, name_len) ||
4703 !strncmp(name, XATTR_NAME_POSIX_ACL_DEFAULT, name_len)) {
4704 if (data_len == 0) {
4705 dummy_acl.a_version =
4706 cpu_to_le32(POSIX_ACL_XATTR_VERSION);
4707 data = (char *)&dummy_acl;
4708 data_len = sizeof(dummy_acl);
4712 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
4716 ret = send_set_xattr(sctx, p, name, name_len, data, data_len);
4723 static int __process_deleted_xattr(int num, struct btrfs_key *di_key,
4724 const char *name, int name_len,
4725 const char *data, int data_len,
4729 struct send_ctx *sctx = ctx;
4732 p = fs_path_alloc();
4736 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
4740 ret = send_remove_xattr(sctx, p, name, name_len);
4747 static int process_new_xattr(struct send_ctx *sctx)
4751 ret = iterate_dir_item(sctx->send_root, sctx->left_path,
4752 __process_new_xattr, sctx);
4757 static int process_deleted_xattr(struct send_ctx *sctx)
4759 return iterate_dir_item(sctx->parent_root, sctx->right_path,
4760 __process_deleted_xattr, sctx);
4763 struct find_xattr_ctx {
4771 static int __find_xattr(int num, struct btrfs_key *di_key,
4772 const char *name, int name_len,
4773 const char *data, int data_len,
4774 u8 type, void *vctx)
4776 struct find_xattr_ctx *ctx = vctx;
4778 if (name_len == ctx->name_len &&
4779 strncmp(name, ctx->name, name_len) == 0) {
4780 ctx->found_idx = num;
4781 ctx->found_data_len = data_len;
4782 ctx->found_data = kmemdup(data, data_len, GFP_KERNEL);
4783 if (!ctx->found_data)
4790 static int find_xattr(struct btrfs_root *root,
4791 struct btrfs_path *path,
4792 struct btrfs_key *key,
4793 const char *name, int name_len,
4794 char **data, int *data_len)
4797 struct find_xattr_ctx ctx;
4800 ctx.name_len = name_len;
4802 ctx.found_data = NULL;
4803 ctx.found_data_len = 0;
4805 ret = iterate_dir_item(root, path, __find_xattr, &ctx);
4809 if (ctx.found_idx == -1)
4812 *data = ctx.found_data;
4813 *data_len = ctx.found_data_len;
4815 kfree(ctx.found_data);
4817 return ctx.found_idx;
4821 static int __process_changed_new_xattr(int num, struct btrfs_key *di_key,
4822 const char *name, int name_len,
4823 const char *data, int data_len,
4827 struct send_ctx *sctx = ctx;
4828 char *found_data = NULL;
4829 int found_data_len = 0;
4831 ret = find_xattr(sctx->parent_root, sctx->right_path,
4832 sctx->cmp_key, name, name_len, &found_data,
4834 if (ret == -ENOENT) {
4835 ret = __process_new_xattr(num, di_key, name, name_len, data,
4836 data_len, type, ctx);
4837 } else if (ret >= 0) {
4838 if (data_len != found_data_len ||
4839 memcmp(data, found_data, data_len)) {
4840 ret = __process_new_xattr(num, di_key, name, name_len,
4841 data, data_len, type, ctx);
4851 static int __process_changed_deleted_xattr(int num, struct btrfs_key *di_key,
4852 const char *name, int name_len,
4853 const char *data, int data_len,
4857 struct send_ctx *sctx = ctx;
4859 ret = find_xattr(sctx->send_root, sctx->left_path, sctx->cmp_key,
4860 name, name_len, NULL, NULL);
4862 ret = __process_deleted_xattr(num, di_key, name, name_len, data,
4863 data_len, type, ctx);
4870 static int process_changed_xattr(struct send_ctx *sctx)
4874 ret = iterate_dir_item(sctx->send_root, sctx->left_path,
4875 __process_changed_new_xattr, sctx);
4878 ret = iterate_dir_item(sctx->parent_root, sctx->right_path,
4879 __process_changed_deleted_xattr, sctx);
4885 static int process_all_new_xattrs(struct send_ctx *sctx)
4888 struct btrfs_root *root;
4889 struct btrfs_path *path;
4890 struct btrfs_key key;
4891 struct btrfs_key found_key;
4892 struct extent_buffer *eb;
4895 path = alloc_path_for_send();
4899 root = sctx->send_root;
4901 key.objectid = sctx->cmp_key->objectid;
4902 key.type = BTRFS_XATTR_ITEM_KEY;
4904 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4909 eb = path->nodes[0];
4910 slot = path->slots[0];
4911 if (slot >= btrfs_header_nritems(eb)) {
4912 ret = btrfs_next_leaf(root, path);
4915 } else if (ret > 0) {
4922 btrfs_item_key_to_cpu(eb, &found_key, slot);
4923 if (found_key.objectid != key.objectid ||
4924 found_key.type != key.type) {
4929 ret = iterate_dir_item(root, path, __process_new_xattr, sctx);
4937 btrfs_free_path(path);
4941 static inline u64 max_send_read_size(const struct send_ctx *sctx)
4943 return sctx->send_max_size - SZ_16K;
4946 static int put_data_header(struct send_ctx *sctx, u32 len)
4948 struct btrfs_tlv_header *hdr;
4950 if (sctx->send_max_size - sctx->send_size < sizeof(*hdr) + len)
4952 hdr = (struct btrfs_tlv_header *)(sctx->send_buf + sctx->send_size);
4953 put_unaligned_le16(BTRFS_SEND_A_DATA, &hdr->tlv_type);
4954 put_unaligned_le16(len, &hdr->tlv_len);
4955 sctx->send_size += sizeof(*hdr);
4959 static int put_file_data(struct send_ctx *sctx, u64 offset, u32 len)
4961 struct btrfs_root *root = sctx->send_root;
4962 struct btrfs_fs_info *fs_info = root->fs_info;
4963 struct inode *inode;
4965 pgoff_t index = offset >> PAGE_SHIFT;
4967 unsigned pg_offset = offset_in_page(offset);
4970 ret = put_data_header(sctx, len);
4974 inode = btrfs_iget(fs_info->sb, sctx->cur_ino, root);
4976 return PTR_ERR(inode);
4978 last_index = (offset + len - 1) >> PAGE_SHIFT;
4980 /* initial readahead */
4981 memset(&sctx->ra, 0, sizeof(struct file_ra_state));
4982 file_ra_state_init(&sctx->ra, inode->i_mapping);
4984 while (index <= last_index) {
4985 unsigned cur_len = min_t(unsigned, len,
4986 PAGE_SIZE - pg_offset);
4988 page = find_lock_page(inode->i_mapping, index);
4990 page_cache_sync_readahead(inode->i_mapping, &sctx->ra,
4991 NULL, index, last_index + 1 - index);
4993 page = find_or_create_page(inode->i_mapping, index,
5001 if (PageReadahead(page)) {
5002 page_cache_async_readahead(inode->i_mapping, &sctx->ra,
5003 NULL, page, index, last_index + 1 - index);
5006 if (!PageUptodate(page)) {
5007 btrfs_readpage(NULL, page);
5009 if (!PageUptodate(page)) {
5012 "send: IO error at offset %llu for inode %llu root %llu",
5013 page_offset(page), sctx->cur_ino,
5014 sctx->send_root->root_key.objectid);
5021 memcpy_from_page(sctx->send_buf + sctx->send_size, page,
5022 pg_offset, cur_len);
5028 sctx->send_size += cur_len;
5035 * Read some bytes from the current inode/file and send a write command to
5038 static int send_write(struct send_ctx *sctx, u64 offset, u32 len)
5040 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
5044 p = fs_path_alloc();
5048 btrfs_debug(fs_info, "send_write offset=%llu, len=%d", offset, len);
5050 ret = begin_cmd(sctx, BTRFS_SEND_C_WRITE);
5054 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5058 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5059 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5060 ret = put_file_data(sctx, offset, len);
5064 ret = send_cmd(sctx);
5073 * Send a clone command to user space.
5075 static int send_clone(struct send_ctx *sctx,
5076 u64 offset, u32 len,
5077 struct clone_root *clone_root)
5083 btrfs_debug(sctx->send_root->fs_info,
5084 "send_clone offset=%llu, len=%d, clone_root=%llu, clone_inode=%llu, clone_offset=%llu",
5085 offset, len, clone_root->root->root_key.objectid,
5086 clone_root->ino, clone_root->offset);
5088 p = fs_path_alloc();
5092 ret = begin_cmd(sctx, BTRFS_SEND_C_CLONE);
5096 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5100 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5101 TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_LEN, len);
5102 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5104 if (clone_root->root == sctx->send_root) {
5105 ret = get_inode_info(sctx->send_root, clone_root->ino, NULL,
5106 &gen, NULL, NULL, NULL, NULL);
5109 ret = get_cur_path(sctx, clone_root->ino, gen, p);
5111 ret = get_inode_path(clone_root->root, clone_root->ino, p);
5117 * If the parent we're using has a received_uuid set then use that as
5118 * our clone source as that is what we will look for when doing a
5121 * This covers the case that we create a snapshot off of a received
5122 * subvolume and then use that as the parent and try to receive on a
5125 if (!btrfs_is_empty_uuid(clone_root->root->root_item.received_uuid))
5126 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
5127 clone_root->root->root_item.received_uuid);
5129 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
5130 clone_root->root->root_item.uuid);
5131 TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_CTRANSID,
5132 btrfs_root_ctransid(&clone_root->root->root_item));
5133 TLV_PUT_PATH(sctx, BTRFS_SEND_A_CLONE_PATH, p);
5134 TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_OFFSET,
5135 clone_root->offset);
5137 ret = send_cmd(sctx);
5146 * Send an update extent command to user space.
5148 static int send_update_extent(struct send_ctx *sctx,
5149 u64 offset, u32 len)
5154 p = fs_path_alloc();
5158 ret = begin_cmd(sctx, BTRFS_SEND_C_UPDATE_EXTENT);
5162 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5166 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5167 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5168 TLV_PUT_U64(sctx, BTRFS_SEND_A_SIZE, len);
5170 ret = send_cmd(sctx);
5178 static int send_hole(struct send_ctx *sctx, u64 end)
5180 struct fs_path *p = NULL;
5181 u64 read_size = max_send_read_size(sctx);
5182 u64 offset = sctx->cur_inode_last_extent;
5186 * A hole that starts at EOF or beyond it. Since we do not yet support
5187 * fallocate (for extent preallocation and hole punching), sending a
5188 * write of zeroes starting at EOF or beyond would later require issuing
5189 * a truncate operation which would undo the write and achieve nothing.
5191 if (offset >= sctx->cur_inode_size)
5195 * Don't go beyond the inode's i_size due to prealloc extents that start
5198 end = min_t(u64, end, sctx->cur_inode_size);
5200 if (sctx->flags & BTRFS_SEND_FLAG_NO_FILE_DATA)
5201 return send_update_extent(sctx, offset, end - offset);
5203 p = fs_path_alloc();
5206 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5208 goto tlv_put_failure;
5209 while (offset < end) {
5210 u64 len = min(end - offset, read_size);
5212 ret = begin_cmd(sctx, BTRFS_SEND_C_WRITE);
5215 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5216 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5217 ret = put_data_header(sctx, len);
5220 memset(sctx->send_buf + sctx->send_size, 0, len);
5221 sctx->send_size += len;
5222 ret = send_cmd(sctx);
5227 sctx->cur_inode_next_write_offset = offset;
5233 static int send_extent_data(struct send_ctx *sctx,
5237 u64 read_size = max_send_read_size(sctx);
5240 if (sctx->flags & BTRFS_SEND_FLAG_NO_FILE_DATA)
5241 return send_update_extent(sctx, offset, len);
5243 while (sent < len) {
5244 u64 size = min(len - sent, read_size);
5247 ret = send_write(sctx, offset + sent, size);
5256 * Search for a capability xattr related to sctx->cur_ino. If the capability is
5257 * found, call send_set_xattr function to emit it.
5259 * Return 0 if there isn't a capability, or when the capability was emitted
5260 * successfully, or < 0 if an error occurred.
5262 static int send_capabilities(struct send_ctx *sctx)
5264 struct fs_path *fspath = NULL;
5265 struct btrfs_path *path;
5266 struct btrfs_dir_item *di;
5267 struct extent_buffer *leaf;
5268 unsigned long data_ptr;
5273 path = alloc_path_for_send();
5277 di = btrfs_lookup_xattr(NULL, sctx->send_root, path, sctx->cur_ino,
5278 XATTR_NAME_CAPS, strlen(XATTR_NAME_CAPS), 0);
5280 /* There is no xattr for this inode */
5282 } else if (IS_ERR(di)) {
5287 leaf = path->nodes[0];
5288 buf_len = btrfs_dir_data_len(leaf, di);
5290 fspath = fs_path_alloc();
5291 buf = kmalloc(buf_len, GFP_KERNEL);
5292 if (!fspath || !buf) {
5297 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, fspath);
5301 data_ptr = (unsigned long)(di + 1) + btrfs_dir_name_len(leaf, di);
5302 read_extent_buffer(leaf, buf, data_ptr, buf_len);
5304 ret = send_set_xattr(sctx, fspath, XATTR_NAME_CAPS,
5305 strlen(XATTR_NAME_CAPS), buf, buf_len);
5308 fs_path_free(fspath);
5309 btrfs_free_path(path);
5313 static int clone_range(struct send_ctx *sctx,
5314 struct clone_root *clone_root,
5315 const u64 disk_byte,
5320 struct btrfs_path *path;
5321 struct btrfs_key key;
5323 u64 clone_src_i_size = 0;
5326 * Prevent cloning from a zero offset with a length matching the sector
5327 * size because in some scenarios this will make the receiver fail.
5329 * For example, if in the source filesystem the extent at offset 0
5330 * has a length of sectorsize and it was written using direct IO, then
5331 * it can never be an inline extent (even if compression is enabled).
5332 * Then this extent can be cloned in the original filesystem to a non
5333 * zero file offset, but it may not be possible to clone in the
5334 * destination filesystem because it can be inlined due to compression
5335 * on the destination filesystem (as the receiver's write operations are
5336 * always done using buffered IO). The same happens when the original
5337 * filesystem does not have compression enabled but the destination
5340 if (clone_root->offset == 0 &&
5341 len == sctx->send_root->fs_info->sectorsize)
5342 return send_extent_data(sctx, offset, len);
5344 path = alloc_path_for_send();
5349 * There are inodes that have extents that lie behind its i_size. Don't
5350 * accept clones from these extents.
5352 ret = __get_inode_info(clone_root->root, path, clone_root->ino,
5353 &clone_src_i_size, NULL, NULL, NULL, NULL, NULL);
5354 btrfs_release_path(path);
5359 * We can't send a clone operation for the entire range if we find
5360 * extent items in the respective range in the source file that
5361 * refer to different extents or if we find holes.
5362 * So check for that and do a mix of clone and regular write/copy
5363 * operations if needed.
5367 * mkfs.btrfs -f /dev/sda
5368 * mount /dev/sda /mnt
5369 * xfs_io -f -c "pwrite -S 0xaa 0K 100K" /mnt/foo
5370 * cp --reflink=always /mnt/foo /mnt/bar
5371 * xfs_io -c "pwrite -S 0xbb 50K 50K" /mnt/foo
5372 * btrfs subvolume snapshot -r /mnt /mnt/snap
5374 * If when we send the snapshot and we are processing file bar (which
5375 * has a higher inode number than foo) we blindly send a clone operation
5376 * for the [0, 100K[ range from foo to bar, the receiver ends up getting
5377 * a file bar that matches the content of file foo - iow, doesn't match
5378 * the content from bar in the original filesystem.
5380 key.objectid = clone_root->ino;
5381 key.type = BTRFS_EXTENT_DATA_KEY;
5382 key.offset = clone_root->offset;
5383 ret = btrfs_search_slot(NULL, clone_root->root, &key, path, 0, 0);
5386 if (ret > 0 && path->slots[0] > 0) {
5387 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1);
5388 if (key.objectid == clone_root->ino &&
5389 key.type == BTRFS_EXTENT_DATA_KEY)
5394 struct extent_buffer *leaf = path->nodes[0];
5395 int slot = path->slots[0];
5396 struct btrfs_file_extent_item *ei;
5400 u64 clone_data_offset;
5402 if (slot >= btrfs_header_nritems(leaf)) {
5403 ret = btrfs_next_leaf(clone_root->root, path);
5411 btrfs_item_key_to_cpu(leaf, &key, slot);
5414 * We might have an implicit trailing hole (NO_HOLES feature
5415 * enabled). We deal with it after leaving this loop.
5417 if (key.objectid != clone_root->ino ||
5418 key.type != BTRFS_EXTENT_DATA_KEY)
5421 ei = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5422 type = btrfs_file_extent_type(leaf, ei);
5423 if (type == BTRFS_FILE_EXTENT_INLINE) {
5424 ext_len = btrfs_file_extent_ram_bytes(leaf, ei);
5425 ext_len = PAGE_ALIGN(ext_len);
5427 ext_len = btrfs_file_extent_num_bytes(leaf, ei);
5430 if (key.offset + ext_len <= clone_root->offset)
5433 if (key.offset > clone_root->offset) {
5434 /* Implicit hole, NO_HOLES feature enabled. */
5435 u64 hole_len = key.offset - clone_root->offset;
5439 ret = send_extent_data(sctx, offset, hole_len);
5447 clone_root->offset += hole_len;
5448 data_offset += hole_len;
5451 if (key.offset >= clone_root->offset + len)
5454 if (key.offset >= clone_src_i_size)
5457 if (key.offset + ext_len > clone_src_i_size)
5458 ext_len = clone_src_i_size - key.offset;
5460 clone_data_offset = btrfs_file_extent_offset(leaf, ei);
5461 if (btrfs_file_extent_disk_bytenr(leaf, ei) == disk_byte) {
5462 clone_root->offset = key.offset;
5463 if (clone_data_offset < data_offset &&
5464 clone_data_offset + ext_len > data_offset) {
5467 extent_offset = data_offset - clone_data_offset;
5468 ext_len -= extent_offset;
5469 clone_data_offset += extent_offset;
5470 clone_root->offset += extent_offset;
5474 clone_len = min_t(u64, ext_len, len);
5476 if (btrfs_file_extent_disk_bytenr(leaf, ei) == disk_byte &&
5477 clone_data_offset == data_offset) {
5478 const u64 src_end = clone_root->offset + clone_len;
5479 const u64 sectorsize = SZ_64K;
5482 * We can't clone the last block, when its size is not
5483 * sector size aligned, into the middle of a file. If we
5484 * do so, the receiver will get a failure (-EINVAL) when
5485 * trying to clone or will silently corrupt the data in
5486 * the destination file if it's on a kernel without the
5487 * fix introduced by commit ac765f83f1397646
5488 * ("Btrfs: fix data corruption due to cloning of eof
5491 * So issue a clone of the aligned down range plus a
5492 * regular write for the eof block, if we hit that case.
5494 * Also, we use the maximum possible sector size, 64K,
5495 * because we don't know what's the sector size of the
5496 * filesystem that receives the stream, so we have to
5497 * assume the largest possible sector size.
5499 if (src_end == clone_src_i_size &&
5500 !IS_ALIGNED(src_end, sectorsize) &&
5501 offset + clone_len < sctx->cur_inode_size) {
5504 slen = ALIGN_DOWN(src_end - clone_root->offset,
5507 ret = send_clone(sctx, offset, slen,
5512 ret = send_extent_data(sctx, offset + slen,
5515 ret = send_clone(sctx, offset, clone_len,
5519 ret = send_extent_data(sctx, offset, clone_len);
5528 offset += clone_len;
5529 clone_root->offset += clone_len;
5532 * If we are cloning from the file we are currently processing,
5533 * and using the send root as the clone root, we must stop once
5534 * the current clone offset reaches the current eof of the file
5535 * at the receiver, otherwise we would issue an invalid clone
5536 * operation (source range going beyond eof) and cause the
5537 * receiver to fail. So if we reach the current eof, bail out
5538 * and fallback to a regular write.
5540 if (clone_root->root == sctx->send_root &&
5541 clone_root->ino == sctx->cur_ino &&
5542 clone_root->offset >= sctx->cur_inode_next_write_offset)
5545 data_offset += clone_len;
5551 ret = send_extent_data(sctx, offset, len);
5555 btrfs_free_path(path);
5559 static int send_write_or_clone(struct send_ctx *sctx,
5560 struct btrfs_path *path,
5561 struct btrfs_key *key,
5562 struct clone_root *clone_root)
5565 u64 offset = key->offset;
5567 u64 bs = sctx->send_root->fs_info->sb->s_blocksize;
5569 end = min_t(u64, btrfs_file_extent_end(path), sctx->cur_inode_size);
5573 if (clone_root && IS_ALIGNED(end, bs)) {
5574 struct btrfs_file_extent_item *ei;
5578 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
5579 struct btrfs_file_extent_item);
5580 disk_byte = btrfs_file_extent_disk_bytenr(path->nodes[0], ei);
5581 data_offset = btrfs_file_extent_offset(path->nodes[0], ei);
5582 ret = clone_range(sctx, clone_root, disk_byte, data_offset,
5583 offset, end - offset);
5585 ret = send_extent_data(sctx, offset, end - offset);
5587 sctx->cur_inode_next_write_offset = end;
5591 static int is_extent_unchanged(struct send_ctx *sctx,
5592 struct btrfs_path *left_path,
5593 struct btrfs_key *ekey)
5596 struct btrfs_key key;
5597 struct btrfs_path *path = NULL;
5598 struct extent_buffer *eb;
5600 struct btrfs_key found_key;
5601 struct btrfs_file_extent_item *ei;
5606 u64 left_offset_fixed;
5614 path = alloc_path_for_send();
5618 eb = left_path->nodes[0];
5619 slot = left_path->slots[0];
5620 ei = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
5621 left_type = btrfs_file_extent_type(eb, ei);
5623 if (left_type != BTRFS_FILE_EXTENT_REG) {
5627 left_disknr = btrfs_file_extent_disk_bytenr(eb, ei);
5628 left_len = btrfs_file_extent_num_bytes(eb, ei);
5629 left_offset = btrfs_file_extent_offset(eb, ei);
5630 left_gen = btrfs_file_extent_generation(eb, ei);
5633 * Following comments will refer to these graphics. L is the left
5634 * extents which we are checking at the moment. 1-8 are the right
5635 * extents that we iterate.
5638 * |-1-|-2a-|-3-|-4-|-5-|-6-|
5641 * |--1--|-2b-|...(same as above)
5643 * Alternative situation. Happens on files where extents got split.
5645 * |-----------7-----------|-6-|
5647 * Alternative situation. Happens on files which got larger.
5650 * Nothing follows after 8.
5653 key.objectid = ekey->objectid;
5654 key.type = BTRFS_EXTENT_DATA_KEY;
5655 key.offset = ekey->offset;
5656 ret = btrfs_search_slot_for_read(sctx->parent_root, &key, path, 0, 0);
5665 * Handle special case where the right side has no extents at all.
5667 eb = path->nodes[0];
5668 slot = path->slots[0];
5669 btrfs_item_key_to_cpu(eb, &found_key, slot);
5670 if (found_key.objectid != key.objectid ||
5671 found_key.type != key.type) {
5672 /* If we're a hole then just pretend nothing changed */
5673 ret = (left_disknr) ? 0 : 1;
5678 * We're now on 2a, 2b or 7.
5681 while (key.offset < ekey->offset + left_len) {
5682 ei = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
5683 right_type = btrfs_file_extent_type(eb, ei);
5684 if (right_type != BTRFS_FILE_EXTENT_REG &&
5685 right_type != BTRFS_FILE_EXTENT_INLINE) {
5690 if (right_type == BTRFS_FILE_EXTENT_INLINE) {
5691 right_len = btrfs_file_extent_ram_bytes(eb, ei);
5692 right_len = PAGE_ALIGN(right_len);
5694 right_len = btrfs_file_extent_num_bytes(eb, ei);
5698 * Are we at extent 8? If yes, we know the extent is changed.
5699 * This may only happen on the first iteration.
5701 if (found_key.offset + right_len <= ekey->offset) {
5702 /* If we're a hole just pretend nothing changed */
5703 ret = (left_disknr) ? 0 : 1;
5708 * We just wanted to see if when we have an inline extent, what
5709 * follows it is a regular extent (wanted to check the above
5710 * condition for inline extents too). This should normally not
5711 * happen but it's possible for example when we have an inline
5712 * compressed extent representing data with a size matching
5713 * the page size (currently the same as sector size).
5715 if (right_type == BTRFS_FILE_EXTENT_INLINE) {
5720 right_disknr = btrfs_file_extent_disk_bytenr(eb, ei);
5721 right_offset = btrfs_file_extent_offset(eb, ei);
5722 right_gen = btrfs_file_extent_generation(eb, ei);
5724 left_offset_fixed = left_offset;
5725 if (key.offset < ekey->offset) {
5726 /* Fix the right offset for 2a and 7. */
5727 right_offset += ekey->offset - key.offset;
5729 /* Fix the left offset for all behind 2a and 2b */
5730 left_offset_fixed += key.offset - ekey->offset;
5734 * Check if we have the same extent.
5736 if (left_disknr != right_disknr ||
5737 left_offset_fixed != right_offset ||
5738 left_gen != right_gen) {
5744 * Go to the next extent.
5746 ret = btrfs_next_item(sctx->parent_root, path);
5750 eb = path->nodes[0];
5751 slot = path->slots[0];
5752 btrfs_item_key_to_cpu(eb, &found_key, slot);
5754 if (ret || found_key.objectid != key.objectid ||
5755 found_key.type != key.type) {
5756 key.offset += right_len;
5759 if (found_key.offset != key.offset + right_len) {
5767 * We're now behind the left extent (treat as unchanged) or at the end
5768 * of the right side (treat as changed).
5770 if (key.offset >= ekey->offset + left_len)
5777 btrfs_free_path(path);
5781 static int get_last_extent(struct send_ctx *sctx, u64 offset)
5783 struct btrfs_path *path;
5784 struct btrfs_root *root = sctx->send_root;
5785 struct btrfs_key key;
5788 path = alloc_path_for_send();
5792 sctx->cur_inode_last_extent = 0;
5794 key.objectid = sctx->cur_ino;
5795 key.type = BTRFS_EXTENT_DATA_KEY;
5796 key.offset = offset;
5797 ret = btrfs_search_slot_for_read(root, &key, path, 0, 1);
5801 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
5802 if (key.objectid != sctx->cur_ino || key.type != BTRFS_EXTENT_DATA_KEY)
5805 sctx->cur_inode_last_extent = btrfs_file_extent_end(path);
5807 btrfs_free_path(path);
5811 static int range_is_hole_in_parent(struct send_ctx *sctx,
5815 struct btrfs_path *path;
5816 struct btrfs_key key;
5817 struct btrfs_root *root = sctx->parent_root;
5818 u64 search_start = start;
5821 path = alloc_path_for_send();
5825 key.objectid = sctx->cur_ino;
5826 key.type = BTRFS_EXTENT_DATA_KEY;
5827 key.offset = search_start;
5828 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5831 if (ret > 0 && path->slots[0] > 0)
5834 while (search_start < end) {
5835 struct extent_buffer *leaf = path->nodes[0];
5836 int slot = path->slots[0];
5837 struct btrfs_file_extent_item *fi;
5840 if (slot >= btrfs_header_nritems(leaf)) {
5841 ret = btrfs_next_leaf(root, path);
5849 btrfs_item_key_to_cpu(leaf, &key, slot);
5850 if (key.objectid < sctx->cur_ino ||
5851 key.type < BTRFS_EXTENT_DATA_KEY)
5853 if (key.objectid > sctx->cur_ino ||
5854 key.type > BTRFS_EXTENT_DATA_KEY ||
5858 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5859 extent_end = btrfs_file_extent_end(path);
5860 if (extent_end <= start)
5862 if (btrfs_file_extent_disk_bytenr(leaf, fi) == 0) {
5863 search_start = extent_end;
5873 btrfs_free_path(path);
5877 static int maybe_send_hole(struct send_ctx *sctx, struct btrfs_path *path,
5878 struct btrfs_key *key)
5882 if (sctx->cur_ino != key->objectid || !need_send_hole(sctx))
5885 if (sctx->cur_inode_last_extent == (u64)-1) {
5886 ret = get_last_extent(sctx, key->offset - 1);
5891 if (path->slots[0] == 0 &&
5892 sctx->cur_inode_last_extent < key->offset) {
5894 * We might have skipped entire leafs that contained only
5895 * file extent items for our current inode. These leafs have
5896 * a generation number smaller (older) than the one in the
5897 * current leaf and the leaf our last extent came from, and
5898 * are located between these 2 leafs.
5900 ret = get_last_extent(sctx, key->offset - 1);
5905 if (sctx->cur_inode_last_extent < key->offset) {
5906 ret = range_is_hole_in_parent(sctx,
5907 sctx->cur_inode_last_extent,
5912 ret = send_hole(sctx, key->offset);
5916 sctx->cur_inode_last_extent = btrfs_file_extent_end(path);
5920 static int process_extent(struct send_ctx *sctx,
5921 struct btrfs_path *path,
5922 struct btrfs_key *key)
5924 struct clone_root *found_clone = NULL;
5927 if (S_ISLNK(sctx->cur_inode_mode))
5930 if (sctx->parent_root && !sctx->cur_inode_new) {
5931 ret = is_extent_unchanged(sctx, path, key);
5939 struct btrfs_file_extent_item *ei;
5942 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
5943 struct btrfs_file_extent_item);
5944 type = btrfs_file_extent_type(path->nodes[0], ei);
5945 if (type == BTRFS_FILE_EXTENT_PREALLOC ||
5946 type == BTRFS_FILE_EXTENT_REG) {
5948 * The send spec does not have a prealloc command yet,
5949 * so just leave a hole for prealloc'ed extents until
5950 * we have enough commands queued up to justify rev'ing
5953 if (type == BTRFS_FILE_EXTENT_PREALLOC) {
5958 /* Have a hole, just skip it. */
5959 if (btrfs_file_extent_disk_bytenr(path->nodes[0], ei) == 0) {
5966 ret = find_extent_clone(sctx, path, key->objectid, key->offset,
5967 sctx->cur_inode_size, &found_clone);
5968 if (ret != -ENOENT && ret < 0)
5971 ret = send_write_or_clone(sctx, path, key, found_clone);
5975 ret = maybe_send_hole(sctx, path, key);
5980 static int process_all_extents(struct send_ctx *sctx)
5983 struct btrfs_root *root;
5984 struct btrfs_path *path;
5985 struct btrfs_key key;
5986 struct btrfs_key found_key;
5987 struct extent_buffer *eb;
5990 root = sctx->send_root;
5991 path = alloc_path_for_send();
5995 key.objectid = sctx->cmp_key->objectid;
5996 key.type = BTRFS_EXTENT_DATA_KEY;
5998 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6003 eb = path->nodes[0];
6004 slot = path->slots[0];
6006 if (slot >= btrfs_header_nritems(eb)) {
6007 ret = btrfs_next_leaf(root, path);
6010 } else if (ret > 0) {
6017 btrfs_item_key_to_cpu(eb, &found_key, slot);
6019 if (found_key.objectid != key.objectid ||
6020 found_key.type != key.type) {
6025 ret = process_extent(sctx, path, &found_key);
6033 btrfs_free_path(path);
6037 static int process_recorded_refs_if_needed(struct send_ctx *sctx, int at_end,
6039 int *refs_processed)
6043 if (sctx->cur_ino == 0)
6045 if (!at_end && sctx->cur_ino == sctx->cmp_key->objectid &&
6046 sctx->cmp_key->type <= BTRFS_INODE_EXTREF_KEY)
6048 if (list_empty(&sctx->new_refs) && list_empty(&sctx->deleted_refs))
6051 ret = process_recorded_refs(sctx, pending_move);
6055 *refs_processed = 1;
6060 static int finish_inode_if_needed(struct send_ctx *sctx, int at_end)
6071 int need_truncate = 1;
6072 int pending_move = 0;
6073 int refs_processed = 0;
6075 if (sctx->ignore_cur_inode)
6078 ret = process_recorded_refs_if_needed(sctx, at_end, &pending_move,
6084 * We have processed the refs and thus need to advance send_progress.
6085 * Now, calls to get_cur_xxx will take the updated refs of the current
6086 * inode into account.
6088 * On the other hand, if our current inode is a directory and couldn't
6089 * be moved/renamed because its parent was renamed/moved too and it has
6090 * a higher inode number, we can only move/rename our current inode
6091 * after we moved/renamed its parent. Therefore in this case operate on
6092 * the old path (pre move/rename) of our current inode, and the
6093 * move/rename will be performed later.
6095 if (refs_processed && !pending_move)
6096 sctx->send_progress = sctx->cur_ino + 1;
6098 if (sctx->cur_ino == 0 || sctx->cur_inode_deleted)
6100 if (!at_end && sctx->cmp_key->objectid == sctx->cur_ino)
6103 ret = get_inode_info(sctx->send_root, sctx->cur_ino, NULL, NULL,
6104 &left_mode, &left_uid, &left_gid, NULL);
6108 if (!sctx->parent_root || sctx->cur_inode_new) {
6110 if (!S_ISLNK(sctx->cur_inode_mode))
6112 if (sctx->cur_inode_next_write_offset == sctx->cur_inode_size)
6117 ret = get_inode_info(sctx->parent_root, sctx->cur_ino,
6118 &old_size, NULL, &right_mode, &right_uid,
6123 if (left_uid != right_uid || left_gid != right_gid)
6125 if (!S_ISLNK(sctx->cur_inode_mode) && left_mode != right_mode)
6127 if ((old_size == sctx->cur_inode_size) ||
6128 (sctx->cur_inode_size > old_size &&
6129 sctx->cur_inode_next_write_offset == sctx->cur_inode_size))
6133 if (S_ISREG(sctx->cur_inode_mode)) {
6134 if (need_send_hole(sctx)) {
6135 if (sctx->cur_inode_last_extent == (u64)-1 ||
6136 sctx->cur_inode_last_extent <
6137 sctx->cur_inode_size) {
6138 ret = get_last_extent(sctx, (u64)-1);
6142 if (sctx->cur_inode_last_extent <
6143 sctx->cur_inode_size) {
6144 ret = send_hole(sctx, sctx->cur_inode_size);
6149 if (need_truncate) {
6150 ret = send_truncate(sctx, sctx->cur_ino,
6151 sctx->cur_inode_gen,
6152 sctx->cur_inode_size);
6159 ret = send_chown(sctx, sctx->cur_ino, sctx->cur_inode_gen,
6160 left_uid, left_gid);
6165 ret = send_chmod(sctx, sctx->cur_ino, sctx->cur_inode_gen,
6171 ret = send_capabilities(sctx);
6176 * If other directory inodes depended on our current directory
6177 * inode's move/rename, now do their move/rename operations.
6179 if (!is_waiting_for_move(sctx, sctx->cur_ino)) {
6180 ret = apply_children_dir_moves(sctx);
6184 * Need to send that every time, no matter if it actually
6185 * changed between the two trees as we have done changes to
6186 * the inode before. If our inode is a directory and it's
6187 * waiting to be moved/renamed, we will send its utimes when
6188 * it's moved/renamed, therefore we don't need to do it here.
6190 sctx->send_progress = sctx->cur_ino + 1;
6191 ret = send_utimes(sctx, sctx->cur_ino, sctx->cur_inode_gen);
6200 struct parent_paths_ctx {
6201 struct list_head *refs;
6202 struct send_ctx *sctx;
6205 static int record_parent_ref(int num, u64 dir, int index, struct fs_path *name,
6208 struct parent_paths_ctx *ppctx = ctx;
6210 return record_ref(ppctx->sctx->parent_root, dir, name, ppctx->sctx,
6215 * Issue unlink operations for all paths of the current inode found in the
6218 static int btrfs_unlink_all_paths(struct send_ctx *sctx)
6220 LIST_HEAD(deleted_refs);
6221 struct btrfs_path *path;
6222 struct btrfs_key key;
6223 struct parent_paths_ctx ctx;
6226 path = alloc_path_for_send();
6230 key.objectid = sctx->cur_ino;
6231 key.type = BTRFS_INODE_REF_KEY;
6233 ret = btrfs_search_slot(NULL, sctx->parent_root, &key, path, 0, 0);
6237 ctx.refs = &deleted_refs;
6241 struct extent_buffer *eb = path->nodes[0];
6242 int slot = path->slots[0];
6244 if (slot >= btrfs_header_nritems(eb)) {
6245 ret = btrfs_next_leaf(sctx->parent_root, path);
6253 btrfs_item_key_to_cpu(eb, &key, slot);
6254 if (key.objectid != sctx->cur_ino)
6256 if (key.type != BTRFS_INODE_REF_KEY &&
6257 key.type != BTRFS_INODE_EXTREF_KEY)
6260 ret = iterate_inode_ref(sctx->parent_root, path, &key, 1,
6261 record_parent_ref, &ctx);
6268 while (!list_empty(&deleted_refs)) {
6269 struct recorded_ref *ref;
6271 ref = list_first_entry(&deleted_refs, struct recorded_ref, list);
6272 ret = send_unlink(sctx, ref->full_path);
6275 fs_path_free(ref->full_path);
6276 list_del(&ref->list);
6281 btrfs_free_path(path);
6283 __free_recorded_refs(&deleted_refs);
6287 static int changed_inode(struct send_ctx *sctx,
6288 enum btrfs_compare_tree_result result)
6291 struct btrfs_key *key = sctx->cmp_key;
6292 struct btrfs_inode_item *left_ii = NULL;
6293 struct btrfs_inode_item *right_ii = NULL;
6297 sctx->cur_ino = key->objectid;
6298 sctx->cur_inode_new_gen = 0;
6299 sctx->cur_inode_last_extent = (u64)-1;
6300 sctx->cur_inode_next_write_offset = 0;
6301 sctx->ignore_cur_inode = false;
6304 * Set send_progress to current inode. This will tell all get_cur_xxx
6305 * functions that the current inode's refs are not updated yet. Later,
6306 * when process_recorded_refs is finished, it is set to cur_ino + 1.
6308 sctx->send_progress = sctx->cur_ino;
6310 if (result == BTRFS_COMPARE_TREE_NEW ||
6311 result == BTRFS_COMPARE_TREE_CHANGED) {
6312 left_ii = btrfs_item_ptr(sctx->left_path->nodes[0],
6313 sctx->left_path->slots[0],
6314 struct btrfs_inode_item);
6315 left_gen = btrfs_inode_generation(sctx->left_path->nodes[0],
6318 right_ii = btrfs_item_ptr(sctx->right_path->nodes[0],
6319 sctx->right_path->slots[0],
6320 struct btrfs_inode_item);
6321 right_gen = btrfs_inode_generation(sctx->right_path->nodes[0],
6324 if (result == BTRFS_COMPARE_TREE_CHANGED) {
6325 right_ii = btrfs_item_ptr(sctx->right_path->nodes[0],
6326 sctx->right_path->slots[0],
6327 struct btrfs_inode_item);
6329 right_gen = btrfs_inode_generation(sctx->right_path->nodes[0],
6333 * The cur_ino = root dir case is special here. We can't treat
6334 * the inode as deleted+reused because it would generate a
6335 * stream that tries to delete/mkdir the root dir.
6337 if (left_gen != right_gen &&
6338 sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID)
6339 sctx->cur_inode_new_gen = 1;
6343 * Normally we do not find inodes with a link count of zero (orphans)
6344 * because the most common case is to create a snapshot and use it
6345 * for a send operation. However other less common use cases involve
6346 * using a subvolume and send it after turning it to RO mode just
6347 * after deleting all hard links of a file while holding an open
6348 * file descriptor against it or turning a RO snapshot into RW mode,
6349 * keep an open file descriptor against a file, delete it and then
6350 * turn the snapshot back to RO mode before using it for a send
6351 * operation. So if we find such cases, ignore the inode and all its
6352 * items completely if it's a new inode, or if it's a changed inode
6353 * make sure all its previous paths (from the parent snapshot) are all
6354 * unlinked and all other the inode items are ignored.
6356 if (result == BTRFS_COMPARE_TREE_NEW ||
6357 result == BTRFS_COMPARE_TREE_CHANGED) {
6360 nlinks = btrfs_inode_nlink(sctx->left_path->nodes[0], left_ii);
6362 sctx->ignore_cur_inode = true;
6363 if (result == BTRFS_COMPARE_TREE_CHANGED)
6364 ret = btrfs_unlink_all_paths(sctx);
6369 if (result == BTRFS_COMPARE_TREE_NEW) {
6370 sctx->cur_inode_gen = left_gen;
6371 sctx->cur_inode_new = 1;
6372 sctx->cur_inode_deleted = 0;
6373 sctx->cur_inode_size = btrfs_inode_size(
6374 sctx->left_path->nodes[0], left_ii);
6375 sctx->cur_inode_mode = btrfs_inode_mode(
6376 sctx->left_path->nodes[0], left_ii);
6377 sctx->cur_inode_rdev = btrfs_inode_rdev(
6378 sctx->left_path->nodes[0], left_ii);
6379 if (sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID)
6380 ret = send_create_inode_if_needed(sctx);
6381 } else if (result == BTRFS_COMPARE_TREE_DELETED) {
6382 sctx->cur_inode_gen = right_gen;
6383 sctx->cur_inode_new = 0;
6384 sctx->cur_inode_deleted = 1;
6385 sctx->cur_inode_size = btrfs_inode_size(
6386 sctx->right_path->nodes[0], right_ii);
6387 sctx->cur_inode_mode = btrfs_inode_mode(
6388 sctx->right_path->nodes[0], right_ii);
6389 } else if (result == BTRFS_COMPARE_TREE_CHANGED) {
6391 * We need to do some special handling in case the inode was
6392 * reported as changed with a changed generation number. This
6393 * means that the original inode was deleted and new inode
6394 * reused the same inum. So we have to treat the old inode as
6395 * deleted and the new one as new.
6397 if (sctx->cur_inode_new_gen) {
6399 * First, process the inode as if it was deleted.
6401 sctx->cur_inode_gen = right_gen;
6402 sctx->cur_inode_new = 0;
6403 sctx->cur_inode_deleted = 1;
6404 sctx->cur_inode_size = btrfs_inode_size(
6405 sctx->right_path->nodes[0], right_ii);
6406 sctx->cur_inode_mode = btrfs_inode_mode(
6407 sctx->right_path->nodes[0], right_ii);
6408 ret = process_all_refs(sctx,
6409 BTRFS_COMPARE_TREE_DELETED);
6414 * Now process the inode as if it was new.
6416 sctx->cur_inode_gen = left_gen;
6417 sctx->cur_inode_new = 1;
6418 sctx->cur_inode_deleted = 0;
6419 sctx->cur_inode_size = btrfs_inode_size(
6420 sctx->left_path->nodes[0], left_ii);
6421 sctx->cur_inode_mode = btrfs_inode_mode(
6422 sctx->left_path->nodes[0], left_ii);
6423 sctx->cur_inode_rdev = btrfs_inode_rdev(
6424 sctx->left_path->nodes[0], left_ii);
6425 ret = send_create_inode_if_needed(sctx);
6429 ret = process_all_refs(sctx, BTRFS_COMPARE_TREE_NEW);
6433 * Advance send_progress now as we did not get into
6434 * process_recorded_refs_if_needed in the new_gen case.
6436 sctx->send_progress = sctx->cur_ino + 1;
6439 * Now process all extents and xattrs of the inode as if
6440 * they were all new.
6442 ret = process_all_extents(sctx);
6445 ret = process_all_new_xattrs(sctx);
6449 sctx->cur_inode_gen = left_gen;
6450 sctx->cur_inode_new = 0;
6451 sctx->cur_inode_new_gen = 0;
6452 sctx->cur_inode_deleted = 0;
6453 sctx->cur_inode_size = btrfs_inode_size(
6454 sctx->left_path->nodes[0], left_ii);
6455 sctx->cur_inode_mode = btrfs_inode_mode(
6456 sctx->left_path->nodes[0], left_ii);
6465 * We have to process new refs before deleted refs, but compare_trees gives us
6466 * the new and deleted refs mixed. To fix this, we record the new/deleted refs
6467 * first and later process them in process_recorded_refs.
6468 * For the cur_inode_new_gen case, we skip recording completely because
6469 * changed_inode did already initiate processing of refs. The reason for this is
6470 * that in this case, compare_tree actually compares the refs of 2 different
6471 * inodes. To fix this, process_all_refs is used in changed_inode to handle all
6472 * refs of the right tree as deleted and all refs of the left tree as new.
6474 static int changed_ref(struct send_ctx *sctx,
6475 enum btrfs_compare_tree_result result)
6479 if (sctx->cur_ino != sctx->cmp_key->objectid) {
6480 inconsistent_snapshot_error(sctx, result, "reference");
6484 if (!sctx->cur_inode_new_gen &&
6485 sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID) {
6486 if (result == BTRFS_COMPARE_TREE_NEW)
6487 ret = record_new_ref(sctx);
6488 else if (result == BTRFS_COMPARE_TREE_DELETED)
6489 ret = record_deleted_ref(sctx);
6490 else if (result == BTRFS_COMPARE_TREE_CHANGED)
6491 ret = record_changed_ref(sctx);
6498 * Process new/deleted/changed xattrs. We skip processing in the
6499 * cur_inode_new_gen case because changed_inode did already initiate processing
6500 * of xattrs. The reason is the same as in changed_ref
6502 static int changed_xattr(struct send_ctx *sctx,
6503 enum btrfs_compare_tree_result result)
6507 if (sctx->cur_ino != sctx->cmp_key->objectid) {
6508 inconsistent_snapshot_error(sctx, result, "xattr");
6512 if (!sctx->cur_inode_new_gen && !sctx->cur_inode_deleted) {
6513 if (result == BTRFS_COMPARE_TREE_NEW)
6514 ret = process_new_xattr(sctx);
6515 else if (result == BTRFS_COMPARE_TREE_DELETED)
6516 ret = process_deleted_xattr(sctx);
6517 else if (result == BTRFS_COMPARE_TREE_CHANGED)
6518 ret = process_changed_xattr(sctx);
6525 * Process new/deleted/changed extents. We skip processing in the
6526 * cur_inode_new_gen case because changed_inode did already initiate processing
6527 * of extents. The reason is the same as in changed_ref
6529 static int changed_extent(struct send_ctx *sctx,
6530 enum btrfs_compare_tree_result result)
6535 * We have found an extent item that changed without the inode item
6536 * having changed. This can happen either after relocation (where the
6537 * disk_bytenr of an extent item is replaced at
6538 * relocation.c:replace_file_extents()) or after deduplication into a
6539 * file in both the parent and send snapshots (where an extent item can
6540 * get modified or replaced with a new one). Note that deduplication
6541 * updates the inode item, but it only changes the iversion (sequence
6542 * field in the inode item) of the inode, so if a file is deduplicated
6543 * the same amount of times in both the parent and send snapshots, its
6544 * iversion becomes the same in both snapshots, whence the inode item is
6545 * the same on both snapshots.
6547 if (sctx->cur_ino != sctx->cmp_key->objectid)
6550 if (!sctx->cur_inode_new_gen && !sctx->cur_inode_deleted) {
6551 if (result != BTRFS_COMPARE_TREE_DELETED)
6552 ret = process_extent(sctx, sctx->left_path,
6559 static int dir_changed(struct send_ctx *sctx, u64 dir)
6561 u64 orig_gen, new_gen;
6564 ret = get_inode_info(sctx->send_root, dir, NULL, &new_gen, NULL, NULL,
6569 ret = get_inode_info(sctx->parent_root, dir, NULL, &orig_gen, NULL,
6574 return (orig_gen != new_gen) ? 1 : 0;
6577 static int compare_refs(struct send_ctx *sctx, struct btrfs_path *path,
6578 struct btrfs_key *key)
6580 struct btrfs_inode_extref *extref;
6581 struct extent_buffer *leaf;
6582 u64 dirid = 0, last_dirid = 0;
6589 /* Easy case, just check this one dirid */
6590 if (key->type == BTRFS_INODE_REF_KEY) {
6591 dirid = key->offset;
6593 ret = dir_changed(sctx, dirid);
6597 leaf = path->nodes[0];
6598 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
6599 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
6600 while (cur_offset < item_size) {
6601 extref = (struct btrfs_inode_extref *)(ptr +
6603 dirid = btrfs_inode_extref_parent(leaf, extref);
6604 ref_name_len = btrfs_inode_extref_name_len(leaf, extref);
6605 cur_offset += ref_name_len + sizeof(*extref);
6606 if (dirid == last_dirid)
6608 ret = dir_changed(sctx, dirid);
6618 * Updates compare related fields in sctx and simply forwards to the actual
6619 * changed_xxx functions.
6621 static int changed_cb(struct btrfs_path *left_path,
6622 struct btrfs_path *right_path,
6623 struct btrfs_key *key,
6624 enum btrfs_compare_tree_result result,
6625 struct send_ctx *sctx)
6630 * We can not hold the commit root semaphore here. This is because in
6631 * the case of sending and receiving to the same filesystem, using a
6632 * pipe, could result in a deadlock:
6634 * 1) The task running send blocks on the pipe because it's full;
6636 * 2) The task running receive, which is the only consumer of the pipe,
6637 * is waiting for a transaction commit (for example due to a space
6638 * reservation when doing a write or triggering a transaction commit
6639 * when creating a subvolume);
6641 * 3) The transaction is waiting to write lock the commit root semaphore,
6642 * but can not acquire it since it's being held at 1).
6644 * Down this call chain we write to the pipe through kernel_write().
6645 * The same type of problem can also happen when sending to a file that
6646 * is stored in the same filesystem - when reserving space for a write
6647 * into the file, we can trigger a transaction commit.
6649 * Our caller has supplied us with clones of leaves from the send and
6650 * parent roots, so we're safe here from a concurrent relocation and
6651 * further reallocation of metadata extents while we are here. Below we
6652 * also assert that the leaves are clones.
6654 lockdep_assert_not_held(&sctx->send_root->fs_info->commit_root_sem);
6657 * We always have a send root, so left_path is never NULL. We will not
6658 * have a leaf when we have reached the end of the send root but have
6659 * not yet reached the end of the parent root.
6661 if (left_path->nodes[0])
6662 ASSERT(test_bit(EXTENT_BUFFER_UNMAPPED,
6663 &left_path->nodes[0]->bflags));
6665 * When doing a full send we don't have a parent root, so right_path is
6666 * NULL. When doing an incremental send, we may have reached the end of
6667 * the parent root already, so we don't have a leaf at right_path.
6669 if (right_path && right_path->nodes[0])
6670 ASSERT(test_bit(EXTENT_BUFFER_UNMAPPED,
6671 &right_path->nodes[0]->bflags));
6673 if (result == BTRFS_COMPARE_TREE_SAME) {
6674 if (key->type == BTRFS_INODE_REF_KEY ||
6675 key->type == BTRFS_INODE_EXTREF_KEY) {
6676 ret = compare_refs(sctx, left_path, key);
6681 } else if (key->type == BTRFS_EXTENT_DATA_KEY) {
6682 return maybe_send_hole(sctx, left_path, key);
6686 result = BTRFS_COMPARE_TREE_CHANGED;
6690 sctx->left_path = left_path;
6691 sctx->right_path = right_path;
6692 sctx->cmp_key = key;
6694 ret = finish_inode_if_needed(sctx, 0);
6698 /* Ignore non-FS objects */
6699 if (key->objectid == BTRFS_FREE_INO_OBJECTID ||
6700 key->objectid == BTRFS_FREE_SPACE_OBJECTID)
6703 if (key->type == BTRFS_INODE_ITEM_KEY) {
6704 ret = changed_inode(sctx, result);
6705 } else if (!sctx->ignore_cur_inode) {
6706 if (key->type == BTRFS_INODE_REF_KEY ||
6707 key->type == BTRFS_INODE_EXTREF_KEY)
6708 ret = changed_ref(sctx, result);
6709 else if (key->type == BTRFS_XATTR_ITEM_KEY)
6710 ret = changed_xattr(sctx, result);
6711 else if (key->type == BTRFS_EXTENT_DATA_KEY)
6712 ret = changed_extent(sctx, result);
6719 static int search_key_again(const struct send_ctx *sctx,
6720 struct btrfs_root *root,
6721 struct btrfs_path *path,
6722 const struct btrfs_key *key)
6726 if (!path->need_commit_sem)
6727 lockdep_assert_held_read(&root->fs_info->commit_root_sem);
6730 * Roots used for send operations are readonly and no one can add,
6731 * update or remove keys from them, so we should be able to find our
6732 * key again. The only exception is deduplication, which can operate on
6733 * readonly roots and add, update or remove keys to/from them - but at
6734 * the moment we don't allow it to run in parallel with send.
6736 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
6739 btrfs_print_tree(path->nodes[path->lowest_level], false);
6740 btrfs_err(root->fs_info,
6741 "send: key (%llu %u %llu) not found in %s root %llu, lowest_level %d, slot %d",
6742 key->objectid, key->type, key->offset,
6743 (root == sctx->parent_root ? "parent" : "send"),
6744 root->root_key.objectid, path->lowest_level,
6745 path->slots[path->lowest_level]);
6752 static int full_send_tree(struct send_ctx *sctx)
6755 struct btrfs_root *send_root = sctx->send_root;
6756 struct btrfs_key key;
6757 struct btrfs_fs_info *fs_info = send_root->fs_info;
6758 struct btrfs_path *path;
6760 path = alloc_path_for_send();
6763 path->reada = READA_FORWARD_ALWAYS;
6765 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
6766 key.type = BTRFS_INODE_ITEM_KEY;
6769 down_read(&fs_info->commit_root_sem);
6770 sctx->last_reloc_trans = fs_info->last_reloc_trans;
6771 up_read(&fs_info->commit_root_sem);
6773 ret = btrfs_search_slot_for_read(send_root, &key, path, 1, 0);
6780 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
6782 ret = changed_cb(path, NULL, &key,
6783 BTRFS_COMPARE_TREE_NEW, sctx);
6787 down_read(&fs_info->commit_root_sem);
6788 if (fs_info->last_reloc_trans > sctx->last_reloc_trans) {
6789 sctx->last_reloc_trans = fs_info->last_reloc_trans;
6790 up_read(&fs_info->commit_root_sem);
6792 * A transaction used for relocating a block group was
6793 * committed or is about to finish its commit. Release
6794 * our path (leaf) and restart the search, so that we
6795 * avoid operating on any file extent items that are
6796 * stale, with a disk_bytenr that reflects a pre
6797 * relocation value. This way we avoid as much as
6798 * possible to fallback to regular writes when checking
6799 * if we can clone file ranges.
6801 btrfs_release_path(path);
6802 ret = search_key_again(sctx, send_root, path, &key);
6806 up_read(&fs_info->commit_root_sem);
6809 ret = btrfs_next_item(send_root, path);
6819 ret = finish_inode_if_needed(sctx, 1);
6822 btrfs_free_path(path);
6826 static int replace_node_with_clone(struct btrfs_path *path, int level)
6828 struct extent_buffer *clone;
6830 clone = btrfs_clone_extent_buffer(path->nodes[level]);
6834 free_extent_buffer(path->nodes[level]);
6835 path->nodes[level] = clone;
6840 static int tree_move_down(struct btrfs_path *path, int *level, u64 reada_min_gen)
6842 struct extent_buffer *eb;
6843 struct extent_buffer *parent = path->nodes[*level];
6844 int slot = path->slots[*level];
6845 const int nritems = btrfs_header_nritems(parent);
6849 lockdep_assert_held_read(&parent->fs_info->commit_root_sem);
6851 BUG_ON(*level == 0);
6852 eb = btrfs_read_node_slot(parent, slot);
6857 * Trigger readahead for the next leaves we will process, so that it is
6858 * very likely that when we need them they are already in memory and we
6859 * will not block on disk IO. For nodes we only do readahead for one,
6860 * since the time window between processing nodes is typically larger.
6862 reada_max = (*level == 1 ? SZ_128K : eb->fs_info->nodesize);
6864 for (slot++; slot < nritems && reada_done < reada_max; slot++) {
6865 if (btrfs_node_ptr_generation(parent, slot) > reada_min_gen) {
6866 btrfs_readahead_node_child(parent, slot);
6867 reada_done += eb->fs_info->nodesize;
6871 path->nodes[*level - 1] = eb;
6872 path->slots[*level - 1] = 0;
6876 return replace_node_with_clone(path, 0);
6881 static int tree_move_next_or_upnext(struct btrfs_path *path,
6882 int *level, int root_level)
6886 nritems = btrfs_header_nritems(path->nodes[*level]);
6888 path->slots[*level]++;
6890 while (path->slots[*level] >= nritems) {
6891 if (*level == root_level) {
6892 path->slots[*level] = nritems - 1;
6897 path->slots[*level] = 0;
6898 free_extent_buffer(path->nodes[*level]);
6899 path->nodes[*level] = NULL;
6901 path->slots[*level]++;
6903 nritems = btrfs_header_nritems(path->nodes[*level]);
6910 * Returns 1 if it had to move up and next. 0 is returned if it moved only next
6913 static int tree_advance(struct btrfs_path *path,
6914 int *level, int root_level,
6916 struct btrfs_key *key,
6921 if (*level == 0 || !allow_down) {
6922 ret = tree_move_next_or_upnext(path, level, root_level);
6924 ret = tree_move_down(path, level, reada_min_gen);
6928 * Even if we have reached the end of a tree, ret is -1, update the key
6929 * anyway, so that in case we need to restart due to a block group
6930 * relocation, we can assert that the last key of the root node still
6931 * exists in the tree.
6934 btrfs_item_key_to_cpu(path->nodes[*level], key,
6935 path->slots[*level]);
6937 btrfs_node_key_to_cpu(path->nodes[*level], key,
6938 path->slots[*level]);
6943 static int tree_compare_item(struct btrfs_path *left_path,
6944 struct btrfs_path *right_path,
6949 unsigned long off1, off2;
6951 len1 = btrfs_item_size_nr(left_path->nodes[0], left_path->slots[0]);
6952 len2 = btrfs_item_size_nr(right_path->nodes[0], right_path->slots[0]);
6956 off1 = btrfs_item_ptr_offset(left_path->nodes[0], left_path->slots[0]);
6957 off2 = btrfs_item_ptr_offset(right_path->nodes[0],
6958 right_path->slots[0]);
6960 read_extent_buffer(left_path->nodes[0], tmp_buf, off1, len1);
6962 cmp = memcmp_extent_buffer(right_path->nodes[0], tmp_buf, off2, len1);
6969 * A transaction used for relocating a block group was committed or is about to
6970 * finish its commit. Release our paths and restart the search, so that we are
6971 * not using stale extent buffers:
6973 * 1) For levels > 0, we are only holding references of extent buffers, without
6974 * any locks on them, which does not prevent them from having been relocated
6975 * and reallocated after the last time we released the commit root semaphore.
6976 * The exception are the root nodes, for which we always have a clone, see
6977 * the comment at btrfs_compare_trees();
6979 * 2) For leaves, level 0, we are holding copies (clones) of extent buffers, so
6980 * we are safe from the concurrent relocation and reallocation. However they
6981 * can have file extent items with a pre relocation disk_bytenr value, so we
6982 * restart the start from the current commit roots and clone the new leaves so
6983 * that we get the post relocation disk_bytenr values. Not doing so, could
6984 * make us clone the wrong data in case there are new extents using the old
6985 * disk_bytenr that happen to be shared.
6987 static int restart_after_relocation(struct btrfs_path *left_path,
6988 struct btrfs_path *right_path,
6989 const struct btrfs_key *left_key,
6990 const struct btrfs_key *right_key,
6993 const struct send_ctx *sctx)
6998 lockdep_assert_held_read(&sctx->send_root->fs_info->commit_root_sem);
7000 btrfs_release_path(left_path);
7001 btrfs_release_path(right_path);
7004 * Since keys can not be added or removed to/from our roots because they
7005 * are readonly and we do not allow deduplication to run in parallel
7006 * (which can add, remove or change keys), the layout of the trees should
7009 left_path->lowest_level = left_level;
7010 ret = search_key_again(sctx, sctx->send_root, left_path, left_key);
7014 right_path->lowest_level = right_level;
7015 ret = search_key_again(sctx, sctx->parent_root, right_path, right_key);
7020 * If the lowest level nodes are leaves, clone them so that they can be
7021 * safely used by changed_cb() while not under the protection of the
7022 * commit root semaphore, even if relocation and reallocation happens in
7025 if (left_level == 0) {
7026 ret = replace_node_with_clone(left_path, 0);
7031 if (right_level == 0) {
7032 ret = replace_node_with_clone(right_path, 0);
7038 * Now clone the root nodes (unless they happen to be the leaves we have
7039 * already cloned). This is to protect against concurrent snapshotting of
7040 * the send and parent roots (see the comment at btrfs_compare_trees()).
7042 root_level = btrfs_header_level(sctx->send_root->commit_root);
7043 if (root_level > 0) {
7044 ret = replace_node_with_clone(left_path, root_level);
7049 root_level = btrfs_header_level(sctx->parent_root->commit_root);
7050 if (root_level > 0) {
7051 ret = replace_node_with_clone(right_path, root_level);
7060 * This function compares two trees and calls the provided callback for
7061 * every changed/new/deleted item it finds.
7062 * If shared tree blocks are encountered, whole subtrees are skipped, making
7063 * the compare pretty fast on snapshotted subvolumes.
7065 * This currently works on commit roots only. As commit roots are read only,
7066 * we don't do any locking. The commit roots are protected with transactions.
7067 * Transactions are ended and rejoined when a commit is tried in between.
7069 * This function checks for modifications done to the trees while comparing.
7070 * If it detects a change, it aborts immediately.
7072 static int btrfs_compare_trees(struct btrfs_root *left_root,
7073 struct btrfs_root *right_root, struct send_ctx *sctx)
7075 struct btrfs_fs_info *fs_info = left_root->fs_info;
7078 struct btrfs_path *left_path = NULL;
7079 struct btrfs_path *right_path = NULL;
7080 struct btrfs_key left_key;
7081 struct btrfs_key right_key;
7082 char *tmp_buf = NULL;
7083 int left_root_level;
7084 int right_root_level;
7087 int left_end_reached = 0;
7088 int right_end_reached = 0;
7089 int advance_left = 0;
7090 int advance_right = 0;
7097 left_path = btrfs_alloc_path();
7102 right_path = btrfs_alloc_path();
7108 tmp_buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
7114 left_path->search_commit_root = 1;
7115 left_path->skip_locking = 1;
7116 right_path->search_commit_root = 1;
7117 right_path->skip_locking = 1;
7120 * Strategy: Go to the first items of both trees. Then do
7122 * If both trees are at level 0
7123 * Compare keys of current items
7124 * If left < right treat left item as new, advance left tree
7126 * If left > right treat right item as deleted, advance right tree
7128 * If left == right do deep compare of items, treat as changed if
7129 * needed, advance both trees and repeat
7130 * If both trees are at the same level but not at level 0
7131 * Compare keys of current nodes/leafs
7132 * If left < right advance left tree and repeat
7133 * If left > right advance right tree and repeat
7134 * If left == right compare blockptrs of the next nodes/leafs
7135 * If they match advance both trees but stay at the same level
7137 * If they don't match advance both trees while allowing to go
7139 * If tree levels are different
7140 * Advance the tree that needs it and repeat
7142 * Advancing a tree means:
7143 * If we are at level 0, try to go to the next slot. If that's not
7144 * possible, go one level up and repeat. Stop when we found a level
7145 * where we could go to the next slot. We may at this point be on a
7148 * If we are not at level 0 and not on shared tree blocks, go one
7151 * If we are not at level 0 and on shared tree blocks, go one slot to
7152 * the right if possible or go up and right.
7155 down_read(&fs_info->commit_root_sem);
7156 left_level = btrfs_header_level(left_root->commit_root);
7157 left_root_level = left_level;
7159 * We clone the root node of the send and parent roots to prevent races
7160 * with snapshot creation of these roots. Snapshot creation COWs the
7161 * root node of a tree, so after the transaction is committed the old
7162 * extent can be reallocated while this send operation is still ongoing.
7163 * So we clone them, under the commit root semaphore, to be race free.
7165 left_path->nodes[left_level] =
7166 btrfs_clone_extent_buffer(left_root->commit_root);
7167 if (!left_path->nodes[left_level]) {
7172 right_level = btrfs_header_level(right_root->commit_root);
7173 right_root_level = right_level;
7174 right_path->nodes[right_level] =
7175 btrfs_clone_extent_buffer(right_root->commit_root);
7176 if (!right_path->nodes[right_level]) {
7181 * Our right root is the parent root, while the left root is the "send"
7182 * root. We know that all new nodes/leaves in the left root must have
7183 * a generation greater than the right root's generation, so we trigger
7184 * readahead for those nodes and leaves of the left root, as we know we
7185 * will need to read them at some point.
7187 reada_min_gen = btrfs_header_generation(right_root->commit_root);
7189 if (left_level == 0)
7190 btrfs_item_key_to_cpu(left_path->nodes[left_level],
7191 &left_key, left_path->slots[left_level]);
7193 btrfs_node_key_to_cpu(left_path->nodes[left_level],
7194 &left_key, left_path->slots[left_level]);
7195 if (right_level == 0)
7196 btrfs_item_key_to_cpu(right_path->nodes[right_level],
7197 &right_key, right_path->slots[right_level]);
7199 btrfs_node_key_to_cpu(right_path->nodes[right_level],
7200 &right_key, right_path->slots[right_level]);
7202 sctx->last_reloc_trans = fs_info->last_reloc_trans;
7205 if (need_resched() ||
7206 rwsem_is_contended(&fs_info->commit_root_sem)) {
7207 up_read(&fs_info->commit_root_sem);
7209 down_read(&fs_info->commit_root_sem);
7212 if (fs_info->last_reloc_trans > sctx->last_reloc_trans) {
7213 ret = restart_after_relocation(left_path, right_path,
7214 &left_key, &right_key,
7215 left_level, right_level,
7219 sctx->last_reloc_trans = fs_info->last_reloc_trans;
7222 if (advance_left && !left_end_reached) {
7223 ret = tree_advance(left_path, &left_level,
7225 advance_left != ADVANCE_ONLY_NEXT,
7226 &left_key, reada_min_gen);
7228 left_end_reached = ADVANCE;
7233 if (advance_right && !right_end_reached) {
7234 ret = tree_advance(right_path, &right_level,
7236 advance_right != ADVANCE_ONLY_NEXT,
7237 &right_key, reada_min_gen);
7239 right_end_reached = ADVANCE;
7245 if (left_end_reached && right_end_reached) {
7248 } else if (left_end_reached) {
7249 if (right_level == 0) {
7250 up_read(&fs_info->commit_root_sem);
7251 ret = changed_cb(left_path, right_path,
7253 BTRFS_COMPARE_TREE_DELETED,
7257 down_read(&fs_info->commit_root_sem);
7259 advance_right = ADVANCE;
7261 } else if (right_end_reached) {
7262 if (left_level == 0) {
7263 up_read(&fs_info->commit_root_sem);
7264 ret = changed_cb(left_path, right_path,
7266 BTRFS_COMPARE_TREE_NEW,
7270 down_read(&fs_info->commit_root_sem);
7272 advance_left = ADVANCE;
7276 if (left_level == 0 && right_level == 0) {
7277 up_read(&fs_info->commit_root_sem);
7278 cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
7280 ret = changed_cb(left_path, right_path,
7282 BTRFS_COMPARE_TREE_NEW,
7284 advance_left = ADVANCE;
7285 } else if (cmp > 0) {
7286 ret = changed_cb(left_path, right_path,
7288 BTRFS_COMPARE_TREE_DELETED,
7290 advance_right = ADVANCE;
7292 enum btrfs_compare_tree_result result;
7294 WARN_ON(!extent_buffer_uptodate(left_path->nodes[0]));
7295 ret = tree_compare_item(left_path, right_path,
7298 result = BTRFS_COMPARE_TREE_CHANGED;
7300 result = BTRFS_COMPARE_TREE_SAME;
7301 ret = changed_cb(left_path, right_path,
7302 &left_key, result, sctx);
7303 advance_left = ADVANCE;
7304 advance_right = ADVANCE;
7309 down_read(&fs_info->commit_root_sem);
7310 } else if (left_level == right_level) {
7311 cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
7313 advance_left = ADVANCE;
7314 } else if (cmp > 0) {
7315 advance_right = ADVANCE;
7317 left_blockptr = btrfs_node_blockptr(
7318 left_path->nodes[left_level],
7319 left_path->slots[left_level]);
7320 right_blockptr = btrfs_node_blockptr(
7321 right_path->nodes[right_level],
7322 right_path->slots[right_level]);
7323 left_gen = btrfs_node_ptr_generation(
7324 left_path->nodes[left_level],
7325 left_path->slots[left_level]);
7326 right_gen = btrfs_node_ptr_generation(
7327 right_path->nodes[right_level],
7328 right_path->slots[right_level]);
7329 if (left_blockptr == right_blockptr &&
7330 left_gen == right_gen) {
7332 * As we're on a shared block, don't
7333 * allow to go deeper.
7335 advance_left = ADVANCE_ONLY_NEXT;
7336 advance_right = ADVANCE_ONLY_NEXT;
7338 advance_left = ADVANCE;
7339 advance_right = ADVANCE;
7342 } else if (left_level < right_level) {
7343 advance_right = ADVANCE;
7345 advance_left = ADVANCE;
7350 up_read(&fs_info->commit_root_sem);
7352 btrfs_free_path(left_path);
7353 btrfs_free_path(right_path);
7358 static int send_subvol(struct send_ctx *sctx)
7362 if (!(sctx->flags & BTRFS_SEND_FLAG_OMIT_STREAM_HEADER)) {
7363 ret = send_header(sctx);
7368 ret = send_subvol_begin(sctx);
7372 if (sctx->parent_root) {
7373 ret = btrfs_compare_trees(sctx->send_root, sctx->parent_root, sctx);
7376 ret = finish_inode_if_needed(sctx, 1);
7380 ret = full_send_tree(sctx);
7386 free_recorded_refs(sctx);
7391 * If orphan cleanup did remove any orphans from a root, it means the tree
7392 * was modified and therefore the commit root is not the same as the current
7393 * root anymore. This is a problem, because send uses the commit root and
7394 * therefore can see inode items that don't exist in the current root anymore,
7395 * and for example make calls to btrfs_iget, which will do tree lookups based
7396 * on the current root and not on the commit root. Those lookups will fail,
7397 * returning a -ESTALE error, and making send fail with that error. So make
7398 * sure a send does not see any orphans we have just removed, and that it will
7399 * see the same inodes regardless of whether a transaction commit happened
7400 * before it started (meaning that the commit root will be the same as the
7401 * current root) or not.
7403 static int ensure_commit_roots_uptodate(struct send_ctx *sctx)
7406 struct btrfs_trans_handle *trans = NULL;
7409 if (sctx->parent_root &&
7410 sctx->parent_root->node != sctx->parent_root->commit_root)
7413 for (i = 0; i < sctx->clone_roots_cnt; i++)
7414 if (sctx->clone_roots[i].root->node !=
7415 sctx->clone_roots[i].root->commit_root)
7419 return btrfs_end_transaction(trans);
7424 /* Use any root, all fs roots will get their commit roots updated. */
7426 trans = btrfs_join_transaction(sctx->send_root);
7428 return PTR_ERR(trans);
7432 return btrfs_commit_transaction(trans);
7436 * Make sure any existing dellaloc is flushed for any root used by a send
7437 * operation so that we do not miss any data and we do not race with writeback
7438 * finishing and changing a tree while send is using the tree. This could
7439 * happen if a subvolume is in RW mode, has delalloc, is turned to RO mode and
7440 * a send operation then uses the subvolume.
7441 * After flushing delalloc ensure_commit_roots_uptodate() must be called.
7443 static int flush_delalloc_roots(struct send_ctx *sctx)
7445 struct btrfs_root *root = sctx->parent_root;
7450 ret = btrfs_start_delalloc_snapshot(root, false);
7453 btrfs_wait_ordered_extents(root, U64_MAX, 0, U64_MAX);
7456 for (i = 0; i < sctx->clone_roots_cnt; i++) {
7457 root = sctx->clone_roots[i].root;
7458 ret = btrfs_start_delalloc_snapshot(root, false);
7461 btrfs_wait_ordered_extents(root, U64_MAX, 0, U64_MAX);
7467 static void btrfs_root_dec_send_in_progress(struct btrfs_root* root)
7469 spin_lock(&root->root_item_lock);
7470 root->send_in_progress--;
7472 * Not much left to do, we don't know why it's unbalanced and
7473 * can't blindly reset it to 0.
7475 if (root->send_in_progress < 0)
7476 btrfs_err(root->fs_info,
7477 "send_in_progress unbalanced %d root %llu",
7478 root->send_in_progress, root->root_key.objectid);
7479 spin_unlock(&root->root_item_lock);
7482 static void dedupe_in_progress_warn(const struct btrfs_root *root)
7484 btrfs_warn_rl(root->fs_info,
7485 "cannot use root %llu for send while deduplications on it are in progress (%d in progress)",
7486 root->root_key.objectid, root->dedupe_in_progress);
7489 long btrfs_ioctl_send(struct file *mnt_file, struct btrfs_ioctl_send_args *arg)
7492 struct btrfs_root *send_root = BTRFS_I(file_inode(mnt_file))->root;
7493 struct btrfs_fs_info *fs_info = send_root->fs_info;
7494 struct btrfs_root *clone_root;
7495 struct send_ctx *sctx = NULL;
7497 u64 *clone_sources_tmp = NULL;
7498 int clone_sources_to_rollback = 0;
7500 int sort_clone_roots = 0;
7502 if (!capable(CAP_SYS_ADMIN))
7506 * The subvolume must remain read-only during send, protect against
7507 * making it RW. This also protects against deletion.
7509 spin_lock(&send_root->root_item_lock);
7510 if (btrfs_root_readonly(send_root) && send_root->dedupe_in_progress) {
7511 dedupe_in_progress_warn(send_root);
7512 spin_unlock(&send_root->root_item_lock);
7515 send_root->send_in_progress++;
7516 spin_unlock(&send_root->root_item_lock);
7519 * Userspace tools do the checks and warn the user if it's
7522 if (!btrfs_root_readonly(send_root)) {
7528 * Check that we don't overflow at later allocations, we request
7529 * clone_sources_count + 1 items, and compare to unsigned long inside
7532 if (arg->clone_sources_count >
7533 ULONG_MAX / sizeof(struct clone_root) - 1) {
7538 if (arg->flags & ~BTRFS_SEND_FLAG_MASK) {
7543 sctx = kzalloc(sizeof(struct send_ctx), GFP_KERNEL);
7549 INIT_LIST_HEAD(&sctx->new_refs);
7550 INIT_LIST_HEAD(&sctx->deleted_refs);
7551 INIT_RADIX_TREE(&sctx->name_cache, GFP_KERNEL);
7552 INIT_LIST_HEAD(&sctx->name_cache_list);
7554 sctx->flags = arg->flags;
7556 sctx->send_filp = fget(arg->send_fd);
7557 if (!sctx->send_filp) {
7562 sctx->send_root = send_root;
7564 * Unlikely but possible, if the subvolume is marked for deletion but
7565 * is slow to remove the directory entry, send can still be started
7567 if (btrfs_root_dead(sctx->send_root)) {
7572 sctx->clone_roots_cnt = arg->clone_sources_count;
7574 sctx->send_max_size = BTRFS_SEND_BUF_SIZE;
7575 sctx->send_buf = kvmalloc(sctx->send_max_size, GFP_KERNEL);
7576 if (!sctx->send_buf) {
7581 sctx->pending_dir_moves = RB_ROOT;
7582 sctx->waiting_dir_moves = RB_ROOT;
7583 sctx->orphan_dirs = RB_ROOT;
7585 sctx->clone_roots = kvcalloc(sizeof(*sctx->clone_roots),
7586 arg->clone_sources_count + 1,
7588 if (!sctx->clone_roots) {
7593 alloc_size = array_size(sizeof(*arg->clone_sources),
7594 arg->clone_sources_count);
7596 if (arg->clone_sources_count) {
7597 clone_sources_tmp = kvmalloc(alloc_size, GFP_KERNEL);
7598 if (!clone_sources_tmp) {
7603 ret = copy_from_user(clone_sources_tmp, arg->clone_sources,
7610 for (i = 0; i < arg->clone_sources_count; i++) {
7611 clone_root = btrfs_get_fs_root(fs_info,
7612 clone_sources_tmp[i], true);
7613 if (IS_ERR(clone_root)) {
7614 ret = PTR_ERR(clone_root);
7617 spin_lock(&clone_root->root_item_lock);
7618 if (!btrfs_root_readonly(clone_root) ||
7619 btrfs_root_dead(clone_root)) {
7620 spin_unlock(&clone_root->root_item_lock);
7621 btrfs_put_root(clone_root);
7625 if (clone_root->dedupe_in_progress) {
7626 dedupe_in_progress_warn(clone_root);
7627 spin_unlock(&clone_root->root_item_lock);
7628 btrfs_put_root(clone_root);
7632 clone_root->send_in_progress++;
7633 spin_unlock(&clone_root->root_item_lock);
7635 sctx->clone_roots[i].root = clone_root;
7636 clone_sources_to_rollback = i + 1;
7638 kvfree(clone_sources_tmp);
7639 clone_sources_tmp = NULL;
7642 if (arg->parent_root) {
7643 sctx->parent_root = btrfs_get_fs_root(fs_info, arg->parent_root,
7645 if (IS_ERR(sctx->parent_root)) {
7646 ret = PTR_ERR(sctx->parent_root);
7650 spin_lock(&sctx->parent_root->root_item_lock);
7651 sctx->parent_root->send_in_progress++;
7652 if (!btrfs_root_readonly(sctx->parent_root) ||
7653 btrfs_root_dead(sctx->parent_root)) {
7654 spin_unlock(&sctx->parent_root->root_item_lock);
7658 if (sctx->parent_root->dedupe_in_progress) {
7659 dedupe_in_progress_warn(sctx->parent_root);
7660 spin_unlock(&sctx->parent_root->root_item_lock);
7664 spin_unlock(&sctx->parent_root->root_item_lock);
7668 * Clones from send_root are allowed, but only if the clone source
7669 * is behind the current send position. This is checked while searching
7670 * for possible clone sources.
7672 sctx->clone_roots[sctx->clone_roots_cnt++].root =
7673 btrfs_grab_root(sctx->send_root);
7675 /* We do a bsearch later */
7676 sort(sctx->clone_roots, sctx->clone_roots_cnt,
7677 sizeof(*sctx->clone_roots), __clone_root_cmp_sort,
7679 sort_clone_roots = 1;
7681 ret = flush_delalloc_roots(sctx);
7685 ret = ensure_commit_roots_uptodate(sctx);
7689 ret = send_subvol(sctx);
7693 if (!(sctx->flags & BTRFS_SEND_FLAG_OMIT_END_CMD)) {
7694 ret = begin_cmd(sctx, BTRFS_SEND_C_END);
7697 ret = send_cmd(sctx);
7703 WARN_ON(sctx && !ret && !RB_EMPTY_ROOT(&sctx->pending_dir_moves));
7704 while (sctx && !RB_EMPTY_ROOT(&sctx->pending_dir_moves)) {
7706 struct pending_dir_move *pm;
7708 n = rb_first(&sctx->pending_dir_moves);
7709 pm = rb_entry(n, struct pending_dir_move, node);
7710 while (!list_empty(&pm->list)) {
7711 struct pending_dir_move *pm2;
7713 pm2 = list_first_entry(&pm->list,
7714 struct pending_dir_move, list);
7715 free_pending_move(sctx, pm2);
7717 free_pending_move(sctx, pm);
7720 WARN_ON(sctx && !ret && !RB_EMPTY_ROOT(&sctx->waiting_dir_moves));
7721 while (sctx && !RB_EMPTY_ROOT(&sctx->waiting_dir_moves)) {
7723 struct waiting_dir_move *dm;
7725 n = rb_first(&sctx->waiting_dir_moves);
7726 dm = rb_entry(n, struct waiting_dir_move, node);
7727 rb_erase(&dm->node, &sctx->waiting_dir_moves);
7731 WARN_ON(sctx && !ret && !RB_EMPTY_ROOT(&sctx->orphan_dirs));
7732 while (sctx && !RB_EMPTY_ROOT(&sctx->orphan_dirs)) {
7734 struct orphan_dir_info *odi;
7736 n = rb_first(&sctx->orphan_dirs);
7737 odi = rb_entry(n, struct orphan_dir_info, node);
7738 free_orphan_dir_info(sctx, odi);
7741 if (sort_clone_roots) {
7742 for (i = 0; i < sctx->clone_roots_cnt; i++) {
7743 btrfs_root_dec_send_in_progress(
7744 sctx->clone_roots[i].root);
7745 btrfs_put_root(sctx->clone_roots[i].root);
7748 for (i = 0; sctx && i < clone_sources_to_rollback; i++) {
7749 btrfs_root_dec_send_in_progress(
7750 sctx->clone_roots[i].root);
7751 btrfs_put_root(sctx->clone_roots[i].root);
7754 btrfs_root_dec_send_in_progress(send_root);
7756 if (sctx && !IS_ERR_OR_NULL(sctx->parent_root)) {
7757 btrfs_root_dec_send_in_progress(sctx->parent_root);
7758 btrfs_put_root(sctx->parent_root);
7761 kvfree(clone_sources_tmp);
7764 if (sctx->send_filp)
7765 fput(sctx->send_filp);
7767 kvfree(sctx->clone_roots);
7768 kvfree(sctx->send_buf);
7770 name_cache_free(sctx);