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"
29 * Maximum number of references an extent can have in order for us to attempt to
30 * issue clone operations instead of write operations. This currently exists to
31 * avoid hitting limitations of the backreference walking code (taking a lot of
32 * time and using too much memory for extents with large number of references).
34 #define SEND_MAX_EXTENT_REFS 64
37 * A fs_path is a helper to dynamically build path names with unknown size.
38 * It reallocates the internal buffer on demand.
39 * It allows fast adding of path elements on the right side (normal path) and
40 * fast adding to the left side (reversed path). A reversed path can also be
41 * unreversed if needed.
50 unsigned short buf_len:15;
51 unsigned short reversed:1;
55 * Average path length does not exceed 200 bytes, we'll have
56 * better packing in the slab and higher chance to satisfy
57 * a allocation later during send.
62 #define FS_PATH_INLINE_SIZE \
63 (sizeof(struct fs_path) - offsetof(struct fs_path, inline_buf))
66 /* reused for each extent */
68 struct btrfs_root *root;
75 #define SEND_CTX_MAX_NAME_CACHE_SIZE 128
76 #define SEND_CTX_NAME_CACHE_CLEAN_SIZE (SEND_CTX_MAX_NAME_CACHE_SIZE * 2)
79 struct file *send_filp;
85 u64 cmd_send_size[BTRFS_SEND_C_MAX + 1];
86 u64 flags; /* 'flags' member of btrfs_ioctl_send_args is u64 */
88 struct btrfs_root *send_root;
89 struct btrfs_root *parent_root;
90 struct clone_root *clone_roots;
93 /* current state of the compare_tree call */
94 struct btrfs_path *left_path;
95 struct btrfs_path *right_path;
96 struct btrfs_key *cmp_key;
99 * infos of the currently processed inode. In case of deleted inodes,
100 * these are the values from the deleted inode.
105 int cur_inode_new_gen;
106 int cur_inode_deleted;
110 u64 cur_inode_last_extent;
111 u64 cur_inode_next_write_offset;
112 bool ignore_cur_inode;
116 struct list_head new_refs;
117 struct list_head deleted_refs;
119 struct radix_tree_root name_cache;
120 struct list_head name_cache_list;
123 struct file_ra_state ra;
128 * We process inodes by their increasing order, so if before an
129 * incremental send we reverse the parent/child relationship of
130 * directories such that a directory with a lower inode number was
131 * the parent of a directory with a higher inode number, and the one
132 * becoming the new parent got renamed too, we can't rename/move the
133 * directory with lower inode number when we finish processing it - we
134 * must process the directory with higher inode number first, then
135 * rename/move it and then rename/move the directory with lower inode
136 * number. Example follows.
138 * Tree state when the first send was performed:
150 * Tree state when the second (incremental) send is performed:
159 * The sequence of steps that lead to the second state was:
161 * mv /a/b/c/d /a/b/c2/d2
162 * mv /a/b/c /a/b/c2/d2/cc
164 * "c" has lower inode number, but we can't move it (2nd mv operation)
165 * before we move "d", which has higher inode number.
167 * So we just memorize which move/rename operations must be performed
168 * later when their respective parent is processed and moved/renamed.
171 /* Indexed by parent directory inode number. */
172 struct rb_root pending_dir_moves;
175 * Reverse index, indexed by the inode number of a directory that
176 * is waiting for the move/rename of its immediate parent before its
177 * own move/rename can be performed.
179 struct rb_root waiting_dir_moves;
182 * A directory that is going to be rm'ed might have a child directory
183 * which is in the pending directory moves index above. In this case,
184 * the directory can only be removed after the move/rename of its child
185 * is performed. Example:
205 * Sequence of steps that lead to the send snapshot:
206 * rm -f /a/b/c/foo.txt
208 * mv /a/b/c/x /a/b/YY
211 * When the child is processed, its move/rename is delayed until its
212 * parent is processed (as explained above), but all other operations
213 * like update utimes, chown, chgrp, etc, are performed and the paths
214 * that it uses for those operations must use the orphanized name of
215 * its parent (the directory we're going to rm later), so we need to
216 * memorize that name.
218 * Indexed by the inode number of the directory to be deleted.
220 struct rb_root orphan_dirs;
223 struct pending_dir_move {
225 struct list_head list;
229 struct list_head update_refs;
232 struct waiting_dir_move {
236 * There might be some directory that could not be removed because it
237 * was waiting for this directory inode to be moved first. Therefore
238 * after this directory is moved, we can try to rmdir the ino rmdir_ino.
245 struct orphan_dir_info {
249 u64 last_dir_index_offset;
252 struct name_cache_entry {
253 struct list_head list;
255 * radix_tree has only 32bit entries but we need to handle 64bit inums.
256 * We use the lower 32bit of the 64bit inum to store it in the tree. If
257 * more then one inum would fall into the same entry, we use radix_list
258 * to store the additional entries. radix_list is also used to store
259 * entries where two entries have the same inum but different
262 struct list_head radix_list;
268 int need_later_update;
274 #define ADVANCE_ONLY_NEXT -1
276 enum btrfs_compare_tree_result {
277 BTRFS_COMPARE_TREE_NEW,
278 BTRFS_COMPARE_TREE_DELETED,
279 BTRFS_COMPARE_TREE_CHANGED,
280 BTRFS_COMPARE_TREE_SAME,
282 typedef int (*btrfs_changed_cb_t)(struct btrfs_path *left_path,
283 struct btrfs_path *right_path,
284 struct btrfs_key *key,
285 enum btrfs_compare_tree_result result,
289 static void inconsistent_snapshot_error(struct send_ctx *sctx,
290 enum btrfs_compare_tree_result result,
293 const char *result_string;
296 case BTRFS_COMPARE_TREE_NEW:
297 result_string = "new";
299 case BTRFS_COMPARE_TREE_DELETED:
300 result_string = "deleted";
302 case BTRFS_COMPARE_TREE_CHANGED:
303 result_string = "updated";
305 case BTRFS_COMPARE_TREE_SAME:
307 result_string = "unchanged";
311 result_string = "unexpected";
314 btrfs_err(sctx->send_root->fs_info,
315 "Send: inconsistent snapshot, found %s %s for inode %llu without updated inode item, send root is %llu, parent root is %llu",
316 result_string, what, sctx->cmp_key->objectid,
317 sctx->send_root->root_key.objectid,
319 sctx->parent_root->root_key.objectid : 0));
322 static int is_waiting_for_move(struct send_ctx *sctx, u64 ino);
324 static struct waiting_dir_move *
325 get_waiting_dir_move(struct send_ctx *sctx, u64 ino);
327 static int is_waiting_for_rm(struct send_ctx *sctx, u64 dir_ino, u64 gen);
329 static int need_send_hole(struct send_ctx *sctx)
331 return (sctx->parent_root && !sctx->cur_inode_new &&
332 !sctx->cur_inode_new_gen && !sctx->cur_inode_deleted &&
333 S_ISREG(sctx->cur_inode_mode));
336 static void fs_path_reset(struct fs_path *p)
339 p->start = p->buf + p->buf_len - 1;
349 static struct fs_path *fs_path_alloc(void)
353 p = kmalloc(sizeof(*p), GFP_KERNEL);
357 p->buf = p->inline_buf;
358 p->buf_len = FS_PATH_INLINE_SIZE;
363 static struct fs_path *fs_path_alloc_reversed(void)
375 static void fs_path_free(struct fs_path *p)
379 if (p->buf != p->inline_buf)
384 static int fs_path_len(struct fs_path *p)
386 return p->end - p->start;
389 static int fs_path_ensure_buf(struct fs_path *p, int len)
397 if (p->buf_len >= len)
400 if (len > PATH_MAX) {
405 path_len = p->end - p->start;
406 old_buf_len = p->buf_len;
409 * First time the inline_buf does not suffice
411 if (p->buf == p->inline_buf) {
412 tmp_buf = kmalloc(len, GFP_KERNEL);
414 memcpy(tmp_buf, p->buf, old_buf_len);
416 tmp_buf = krealloc(p->buf, len, GFP_KERNEL);
422 * The real size of the buffer is bigger, this will let the fast path
423 * happen most of the time
425 p->buf_len = ksize(p->buf);
428 tmp_buf = p->buf + old_buf_len - path_len - 1;
429 p->end = p->buf + p->buf_len - 1;
430 p->start = p->end - path_len;
431 memmove(p->start, tmp_buf, path_len + 1);
434 p->end = p->start + path_len;
439 static int fs_path_prepare_for_add(struct fs_path *p, int name_len,
445 new_len = p->end - p->start + name_len;
446 if (p->start != p->end)
448 ret = fs_path_ensure_buf(p, new_len);
453 if (p->start != p->end)
455 p->start -= name_len;
456 *prepared = p->start;
458 if (p->start != p->end)
469 static int fs_path_add(struct fs_path *p, const char *name, int name_len)
474 ret = fs_path_prepare_for_add(p, name_len, &prepared);
477 memcpy(prepared, name, name_len);
483 static int fs_path_add_path(struct fs_path *p, struct fs_path *p2)
488 ret = fs_path_prepare_for_add(p, p2->end - p2->start, &prepared);
491 memcpy(prepared, p2->start, p2->end - p2->start);
497 static int fs_path_add_from_extent_buffer(struct fs_path *p,
498 struct extent_buffer *eb,
499 unsigned long off, int len)
504 ret = fs_path_prepare_for_add(p, len, &prepared);
508 read_extent_buffer(eb, prepared, off, len);
514 static int fs_path_copy(struct fs_path *p, struct fs_path *from)
518 p->reversed = from->reversed;
521 ret = fs_path_add_path(p, from);
527 static void fs_path_unreverse(struct fs_path *p)
536 len = p->end - p->start;
538 p->end = p->start + len;
539 memmove(p->start, tmp, len + 1);
543 static struct btrfs_path *alloc_path_for_send(void)
545 struct btrfs_path *path;
547 path = btrfs_alloc_path();
550 path->search_commit_root = 1;
551 path->skip_locking = 1;
552 path->need_commit_sem = 1;
556 static int write_buf(struct file *filp, const void *buf, u32 len, loff_t *off)
562 ret = kernel_write(filp, buf + pos, len - pos, off);
563 /* TODO handle that correctly */
564 /*if (ret == -ERESTARTSYS) {
578 static int tlv_put(struct send_ctx *sctx, u16 attr, const void *data, int len)
580 struct btrfs_tlv_header *hdr;
581 int total_len = sizeof(*hdr) + len;
582 int left = sctx->send_max_size - sctx->send_size;
584 if (unlikely(left < total_len))
587 hdr = (struct btrfs_tlv_header *) (sctx->send_buf + sctx->send_size);
588 hdr->tlv_type = cpu_to_le16(attr);
589 hdr->tlv_len = cpu_to_le16(len);
590 memcpy(hdr + 1, data, len);
591 sctx->send_size += total_len;
596 #define TLV_PUT_DEFINE_INT(bits) \
597 static int tlv_put_u##bits(struct send_ctx *sctx, \
598 u##bits attr, u##bits value) \
600 __le##bits __tmp = cpu_to_le##bits(value); \
601 return tlv_put(sctx, attr, &__tmp, sizeof(__tmp)); \
604 TLV_PUT_DEFINE_INT(64)
606 static int tlv_put_string(struct send_ctx *sctx, u16 attr,
607 const char *str, int len)
611 return tlv_put(sctx, attr, str, len);
614 static int tlv_put_uuid(struct send_ctx *sctx, u16 attr,
617 return tlv_put(sctx, attr, uuid, BTRFS_UUID_SIZE);
620 static int tlv_put_btrfs_timespec(struct send_ctx *sctx, u16 attr,
621 struct extent_buffer *eb,
622 struct btrfs_timespec *ts)
624 struct btrfs_timespec bts;
625 read_extent_buffer(eb, &bts, (unsigned long)ts, sizeof(bts));
626 return tlv_put(sctx, attr, &bts, sizeof(bts));
630 #define TLV_PUT(sctx, attrtype, data, attrlen) \
632 ret = tlv_put(sctx, attrtype, data, attrlen); \
634 goto tlv_put_failure; \
637 #define TLV_PUT_INT(sctx, attrtype, bits, value) \
639 ret = tlv_put_u##bits(sctx, attrtype, value); \
641 goto tlv_put_failure; \
644 #define TLV_PUT_U8(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 8, data)
645 #define TLV_PUT_U16(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 16, data)
646 #define TLV_PUT_U32(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 32, data)
647 #define TLV_PUT_U64(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 64, data)
648 #define TLV_PUT_STRING(sctx, attrtype, str, len) \
650 ret = tlv_put_string(sctx, attrtype, str, len); \
652 goto tlv_put_failure; \
654 #define TLV_PUT_PATH(sctx, attrtype, p) \
656 ret = tlv_put_string(sctx, attrtype, p->start, \
657 p->end - p->start); \
659 goto tlv_put_failure; \
661 #define TLV_PUT_UUID(sctx, attrtype, uuid) \
663 ret = tlv_put_uuid(sctx, attrtype, uuid); \
665 goto tlv_put_failure; \
667 #define TLV_PUT_BTRFS_TIMESPEC(sctx, attrtype, eb, ts) \
669 ret = tlv_put_btrfs_timespec(sctx, attrtype, eb, ts); \
671 goto tlv_put_failure; \
674 static int send_header(struct send_ctx *sctx)
676 struct btrfs_stream_header hdr;
678 strcpy(hdr.magic, BTRFS_SEND_STREAM_MAGIC);
679 hdr.version = cpu_to_le32(BTRFS_SEND_STREAM_VERSION);
681 return write_buf(sctx->send_filp, &hdr, sizeof(hdr),
686 * For each command/item we want to send to userspace, we call this function.
688 static int begin_cmd(struct send_ctx *sctx, int cmd)
690 struct btrfs_cmd_header *hdr;
692 if (WARN_ON(!sctx->send_buf))
695 BUG_ON(sctx->send_size);
697 sctx->send_size += sizeof(*hdr);
698 hdr = (struct btrfs_cmd_header *)sctx->send_buf;
699 hdr->cmd = cpu_to_le16(cmd);
704 static int send_cmd(struct send_ctx *sctx)
707 struct btrfs_cmd_header *hdr;
710 hdr = (struct btrfs_cmd_header *)sctx->send_buf;
711 hdr->len = cpu_to_le32(sctx->send_size - sizeof(*hdr));
714 crc = btrfs_crc32c(0, (unsigned char *)sctx->send_buf, sctx->send_size);
715 hdr->crc = cpu_to_le32(crc);
717 ret = write_buf(sctx->send_filp, sctx->send_buf, sctx->send_size,
720 sctx->total_send_size += sctx->send_size;
721 sctx->cmd_send_size[le16_to_cpu(hdr->cmd)] += sctx->send_size;
728 * Sends a move instruction to user space
730 static int send_rename(struct send_ctx *sctx,
731 struct fs_path *from, struct fs_path *to)
733 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
736 btrfs_debug(fs_info, "send_rename %s -> %s", from->start, to->start);
738 ret = begin_cmd(sctx, BTRFS_SEND_C_RENAME);
742 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, from);
743 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH_TO, to);
745 ret = send_cmd(sctx);
753 * Sends a link instruction to user space
755 static int send_link(struct send_ctx *sctx,
756 struct fs_path *path, struct fs_path *lnk)
758 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
761 btrfs_debug(fs_info, "send_link %s -> %s", path->start, lnk->start);
763 ret = begin_cmd(sctx, BTRFS_SEND_C_LINK);
767 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
768 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH_LINK, lnk);
770 ret = send_cmd(sctx);
778 * Sends an unlink instruction to user space
780 static int send_unlink(struct send_ctx *sctx, struct fs_path *path)
782 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
785 btrfs_debug(fs_info, "send_unlink %s", path->start);
787 ret = begin_cmd(sctx, BTRFS_SEND_C_UNLINK);
791 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
793 ret = send_cmd(sctx);
801 * Sends a rmdir instruction to user space
803 static int send_rmdir(struct send_ctx *sctx, struct fs_path *path)
805 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
808 btrfs_debug(fs_info, "send_rmdir %s", path->start);
810 ret = begin_cmd(sctx, BTRFS_SEND_C_RMDIR);
814 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
816 ret = send_cmd(sctx);
824 * Helper function to retrieve some fields from an inode item.
826 static int __get_inode_info(struct btrfs_root *root, struct btrfs_path *path,
827 u64 ino, u64 *size, u64 *gen, u64 *mode, u64 *uid,
831 struct btrfs_inode_item *ii;
832 struct btrfs_key key;
835 key.type = BTRFS_INODE_ITEM_KEY;
837 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
844 ii = btrfs_item_ptr(path->nodes[0], path->slots[0],
845 struct btrfs_inode_item);
847 *size = btrfs_inode_size(path->nodes[0], ii);
849 *gen = btrfs_inode_generation(path->nodes[0], ii);
851 *mode = btrfs_inode_mode(path->nodes[0], ii);
853 *uid = btrfs_inode_uid(path->nodes[0], ii);
855 *gid = btrfs_inode_gid(path->nodes[0], ii);
857 *rdev = btrfs_inode_rdev(path->nodes[0], ii);
862 static int get_inode_info(struct btrfs_root *root,
863 u64 ino, u64 *size, u64 *gen,
864 u64 *mode, u64 *uid, u64 *gid,
867 struct btrfs_path *path;
870 path = alloc_path_for_send();
873 ret = __get_inode_info(root, path, ino, size, gen, mode, uid, gid,
875 btrfs_free_path(path);
879 typedef int (*iterate_inode_ref_t)(int num, u64 dir, int index,
884 * Helper function to iterate the entries in ONE btrfs_inode_ref or
885 * btrfs_inode_extref.
886 * The iterate callback may return a non zero value to stop iteration. This can
887 * be a negative value for error codes or 1 to simply stop it.
889 * path must point to the INODE_REF or INODE_EXTREF when called.
891 static int iterate_inode_ref(struct btrfs_root *root, struct btrfs_path *path,
892 struct btrfs_key *found_key, int resolve,
893 iterate_inode_ref_t iterate, void *ctx)
895 struct extent_buffer *eb = path->nodes[0];
896 struct btrfs_item *item;
897 struct btrfs_inode_ref *iref;
898 struct btrfs_inode_extref *extref;
899 struct btrfs_path *tmp_path;
903 int slot = path->slots[0];
910 unsigned long name_off;
911 unsigned long elem_size;
914 p = fs_path_alloc_reversed();
918 tmp_path = alloc_path_for_send();
925 if (found_key->type == BTRFS_INODE_REF_KEY) {
926 ptr = (unsigned long)btrfs_item_ptr(eb, slot,
927 struct btrfs_inode_ref);
928 item = btrfs_item_nr(slot);
929 total = btrfs_item_size(eb, item);
930 elem_size = sizeof(*iref);
932 ptr = btrfs_item_ptr_offset(eb, slot);
933 total = btrfs_item_size_nr(eb, slot);
934 elem_size = sizeof(*extref);
937 while (cur < total) {
940 if (found_key->type == BTRFS_INODE_REF_KEY) {
941 iref = (struct btrfs_inode_ref *)(ptr + cur);
942 name_len = btrfs_inode_ref_name_len(eb, iref);
943 name_off = (unsigned long)(iref + 1);
944 index = btrfs_inode_ref_index(eb, iref);
945 dir = found_key->offset;
947 extref = (struct btrfs_inode_extref *)(ptr + cur);
948 name_len = btrfs_inode_extref_name_len(eb, extref);
949 name_off = (unsigned long)&extref->name;
950 index = btrfs_inode_extref_index(eb, extref);
951 dir = btrfs_inode_extref_parent(eb, extref);
955 start = btrfs_ref_to_path(root, tmp_path, name_len,
959 ret = PTR_ERR(start);
962 if (start < p->buf) {
963 /* overflow , try again with larger buffer */
964 ret = fs_path_ensure_buf(p,
965 p->buf_len + p->buf - start);
968 start = btrfs_ref_to_path(root, tmp_path,
973 ret = PTR_ERR(start);
976 BUG_ON(start < p->buf);
980 ret = fs_path_add_from_extent_buffer(p, eb, name_off,
986 cur += elem_size + name_len;
987 ret = iterate(num, dir, index, p, ctx);
994 btrfs_free_path(tmp_path);
999 typedef int (*iterate_dir_item_t)(int num, struct btrfs_key *di_key,
1000 const char *name, int name_len,
1001 const char *data, int data_len,
1002 u8 type, void *ctx);
1005 * Helper function to iterate the entries in ONE btrfs_dir_item.
1006 * The iterate callback may return a non zero value to stop iteration. This can
1007 * be a negative value for error codes or 1 to simply stop it.
1009 * path must point to the dir item when called.
1011 static int iterate_dir_item(struct btrfs_root *root, struct btrfs_path *path,
1012 iterate_dir_item_t iterate, void *ctx)
1015 struct extent_buffer *eb;
1016 struct btrfs_item *item;
1017 struct btrfs_dir_item *di;
1018 struct btrfs_key di_key;
1031 * Start with a small buffer (1 page). If later we end up needing more
1032 * space, which can happen for xattrs on a fs with a leaf size greater
1033 * then the page size, attempt to increase the buffer. Typically xattr
1037 buf = kmalloc(buf_len, GFP_KERNEL);
1043 eb = path->nodes[0];
1044 slot = path->slots[0];
1045 item = btrfs_item_nr(slot);
1046 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
1049 total = btrfs_item_size(eb, item);
1052 while (cur < total) {
1053 name_len = btrfs_dir_name_len(eb, di);
1054 data_len = btrfs_dir_data_len(eb, di);
1055 type = btrfs_dir_type(eb, di);
1056 btrfs_dir_item_key_to_cpu(eb, di, &di_key);
1058 if (type == BTRFS_FT_XATTR) {
1059 if (name_len > XATTR_NAME_MAX) {
1060 ret = -ENAMETOOLONG;
1063 if (name_len + data_len >
1064 BTRFS_MAX_XATTR_SIZE(root->fs_info)) {
1072 if (name_len + data_len > PATH_MAX) {
1073 ret = -ENAMETOOLONG;
1078 if (name_len + data_len > buf_len) {
1079 buf_len = name_len + data_len;
1080 if (is_vmalloc_addr(buf)) {
1084 char *tmp = krealloc(buf, buf_len,
1085 GFP_KERNEL | __GFP_NOWARN);
1092 buf = kvmalloc(buf_len, GFP_KERNEL);
1100 read_extent_buffer(eb, buf, (unsigned long)(di + 1),
1101 name_len + data_len);
1103 len = sizeof(*di) + name_len + data_len;
1104 di = (struct btrfs_dir_item *)((char *)di + len);
1107 ret = iterate(num, &di_key, buf, name_len, buf + name_len,
1108 data_len, type, ctx);
1124 static int __copy_first_ref(int num, u64 dir, int index,
1125 struct fs_path *p, void *ctx)
1128 struct fs_path *pt = ctx;
1130 ret = fs_path_copy(pt, p);
1134 /* we want the first only */
1139 * Retrieve the first path of an inode. If an inode has more then one
1140 * ref/hardlink, this is ignored.
1142 static int get_inode_path(struct btrfs_root *root,
1143 u64 ino, struct fs_path *path)
1146 struct btrfs_key key, found_key;
1147 struct btrfs_path *p;
1149 p = alloc_path_for_send();
1153 fs_path_reset(path);
1156 key.type = BTRFS_INODE_REF_KEY;
1159 ret = btrfs_search_slot_for_read(root, &key, p, 1, 0);
1166 btrfs_item_key_to_cpu(p->nodes[0], &found_key, p->slots[0]);
1167 if (found_key.objectid != ino ||
1168 (found_key.type != BTRFS_INODE_REF_KEY &&
1169 found_key.type != BTRFS_INODE_EXTREF_KEY)) {
1174 ret = iterate_inode_ref(root, p, &found_key, 1,
1175 __copy_first_ref, path);
1185 struct backref_ctx {
1186 struct send_ctx *sctx;
1188 /* number of total found references */
1192 * used for clones found in send_root. clones found behind cur_objectid
1193 * and cur_offset are not considered as allowed clones.
1198 /* may be truncated in case it's the last extent in a file */
1201 /* data offset in the file extent item */
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 struct clone_root *cr = (struct clone_root *)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 struct clone_root *cr1 = (struct clone_root *)e1;
1223 struct clone_root *cr2 = (struct clone_root *)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 = NULL;
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 backref_ctx = kmalloc(sizeof(*backref_ctx), GFP_KERNEL);
1341 if (data_offset >= ino_size) {
1343 * There may be extents that lie behind the file's size.
1344 * I at least had this in combination with snapshotting while
1345 * writing large files.
1351 fi = btrfs_item_ptr(eb, path->slots[0],
1352 struct btrfs_file_extent_item);
1353 extent_type = btrfs_file_extent_type(eb, fi);
1354 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1358 compressed = btrfs_file_extent_compression(eb, fi);
1360 num_bytes = btrfs_file_extent_num_bytes(eb, fi);
1361 disk_byte = btrfs_file_extent_disk_bytenr(eb, fi);
1362 if (disk_byte == 0) {
1366 logical = disk_byte + btrfs_file_extent_offset(eb, fi);
1368 down_read(&fs_info->commit_root_sem);
1369 ret = extent_from_logical(fs_info, disk_byte, tmp_path,
1370 &found_key, &flags);
1371 up_read(&fs_info->commit_root_sem);
1375 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
1380 ei = btrfs_item_ptr(tmp_path->nodes[0], tmp_path->slots[0],
1381 struct btrfs_extent_item);
1383 * Backreference walking (iterate_extent_inodes() below) is currently
1384 * too expensive when an extent has a large number of references, both
1385 * in time spent and used memory. So for now just fallback to write
1386 * operations instead of clone operations when an extent has more than
1387 * a certain amount of references.
1389 if (btrfs_extent_refs(tmp_path->nodes[0], ei) > SEND_MAX_EXTENT_REFS) {
1393 btrfs_release_path(tmp_path);
1396 * Setup the clone roots.
1398 for (i = 0; i < sctx->clone_roots_cnt; i++) {
1399 cur_clone_root = sctx->clone_roots + i;
1400 cur_clone_root->ino = (u64)-1;
1401 cur_clone_root->offset = 0;
1402 cur_clone_root->found_refs = 0;
1405 backref_ctx->sctx = sctx;
1406 backref_ctx->found = 0;
1407 backref_ctx->cur_objectid = ino;
1408 backref_ctx->cur_offset = data_offset;
1409 backref_ctx->found_itself = 0;
1410 backref_ctx->extent_len = num_bytes;
1412 * For non-compressed extents iterate_extent_inodes() gives us extent
1413 * offsets that already take into account the data offset, but not for
1414 * compressed extents, since the offset is logical and not relative to
1415 * the physical extent locations. We must take this into account to
1416 * avoid sending clone offsets that go beyond the source file's size,
1417 * which would result in the clone ioctl failing with -EINVAL on the
1420 if (compressed == BTRFS_COMPRESS_NONE)
1421 backref_ctx->data_offset = 0;
1423 backref_ctx->data_offset = btrfs_file_extent_offset(eb, fi);
1426 * The last extent of a file may be too large due to page alignment.
1427 * We need to adjust extent_len in this case so that the checks in
1428 * __iterate_backrefs work.
1430 if (data_offset + num_bytes >= ino_size)
1431 backref_ctx->extent_len = ino_size - data_offset;
1434 * Now collect all backrefs.
1436 if (compressed == BTRFS_COMPRESS_NONE)
1437 extent_item_pos = logical - found_key.objectid;
1439 extent_item_pos = 0;
1440 ret = iterate_extent_inodes(fs_info, found_key.objectid,
1441 extent_item_pos, 1, __iterate_backrefs,
1442 backref_ctx, false);
1447 if (!backref_ctx->found_itself) {
1448 /* found a bug in backref code? */
1451 "did not find backref in send_root. inode=%llu, offset=%llu, disk_byte=%llu found extent=%llu",
1452 ino, data_offset, disk_byte, found_key.objectid);
1456 btrfs_debug(fs_info,
1457 "find_extent_clone: data_offset=%llu, ino=%llu, num_bytes=%llu, logical=%llu",
1458 data_offset, ino, num_bytes, logical);
1460 if (!backref_ctx->found)
1461 btrfs_debug(fs_info, "no clones found");
1463 cur_clone_root = NULL;
1464 for (i = 0; i < sctx->clone_roots_cnt; i++) {
1465 if (sctx->clone_roots[i].found_refs) {
1466 if (!cur_clone_root)
1467 cur_clone_root = sctx->clone_roots + i;
1468 else if (sctx->clone_roots[i].root == sctx->send_root)
1469 /* prefer clones from send_root over others */
1470 cur_clone_root = sctx->clone_roots + i;
1475 if (cur_clone_root) {
1476 *found = cur_clone_root;
1483 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 * Removes the entry from the list and adds it back to the end. This marks the
2105 * entry as recently used so that name_cache_clean_unused does not remove it.
2107 static void name_cache_used(struct send_ctx *sctx, struct name_cache_entry *nce)
2109 list_del(&nce->list);
2110 list_add_tail(&nce->list, &sctx->name_cache_list);
2114 * Remove some entries from the beginning of name_cache_list.
2116 static void name_cache_clean_unused(struct send_ctx *sctx)
2118 struct name_cache_entry *nce;
2120 if (sctx->name_cache_size < SEND_CTX_NAME_CACHE_CLEAN_SIZE)
2123 while (sctx->name_cache_size > SEND_CTX_MAX_NAME_CACHE_SIZE) {
2124 nce = list_entry(sctx->name_cache_list.next,
2125 struct name_cache_entry, list);
2126 name_cache_delete(sctx, nce);
2131 static void name_cache_free(struct send_ctx *sctx)
2133 struct name_cache_entry *nce;
2135 while (!list_empty(&sctx->name_cache_list)) {
2136 nce = list_entry(sctx->name_cache_list.next,
2137 struct name_cache_entry, list);
2138 name_cache_delete(sctx, nce);
2144 * Used by get_cur_path for each ref up to the root.
2145 * Returns 0 if it succeeded.
2146 * Returns 1 if the inode is not existent or got overwritten. In that case, the
2147 * name is an orphan name. This instructs get_cur_path to stop iterating. If 1
2148 * is returned, parent_ino/parent_gen are not guaranteed to be valid.
2149 * Returns <0 in case of error.
2151 static int __get_cur_name_and_parent(struct send_ctx *sctx,
2155 struct fs_path *dest)
2159 struct name_cache_entry *nce = NULL;
2162 * First check if we already did a call to this function with the same
2163 * ino/gen. If yes, check if the cache entry is still up-to-date. If yes
2164 * return the cached result.
2166 nce = name_cache_search(sctx, ino, gen);
2168 if (ino < sctx->send_progress && nce->need_later_update) {
2169 name_cache_delete(sctx, nce);
2173 name_cache_used(sctx, nce);
2174 *parent_ino = nce->parent_ino;
2175 *parent_gen = nce->parent_gen;
2176 ret = fs_path_add(dest, nce->name, nce->name_len);
2185 * If the inode is not existent yet, add the orphan name and return 1.
2186 * This should only happen for the parent dir that we determine in
2189 ret = is_inode_existent(sctx, ino, gen);
2194 ret = gen_unique_name(sctx, ino, gen, dest);
2202 * Depending on whether the inode was already processed or not, use
2203 * send_root or parent_root for ref lookup.
2205 if (ino < sctx->send_progress)
2206 ret = get_first_ref(sctx->send_root, ino,
2207 parent_ino, parent_gen, dest);
2209 ret = get_first_ref(sctx->parent_root, ino,
2210 parent_ino, parent_gen, dest);
2215 * Check if the ref was overwritten by an inode's ref that was processed
2216 * earlier. If yes, treat as orphan and return 1.
2218 ret = did_overwrite_ref(sctx, *parent_ino, *parent_gen, ino, gen,
2219 dest->start, dest->end - dest->start);
2223 fs_path_reset(dest);
2224 ret = gen_unique_name(sctx, ino, gen, dest);
2232 * Store the result of the lookup in the name cache.
2234 nce = kmalloc(sizeof(*nce) + fs_path_len(dest) + 1, GFP_KERNEL);
2242 nce->parent_ino = *parent_ino;
2243 nce->parent_gen = *parent_gen;
2244 nce->name_len = fs_path_len(dest);
2246 strcpy(nce->name, dest->start);
2248 if (ino < sctx->send_progress)
2249 nce->need_later_update = 0;
2251 nce->need_later_update = 1;
2253 nce_ret = name_cache_insert(sctx, nce);
2256 name_cache_clean_unused(sctx);
2263 * Magic happens here. This function returns the first ref to an inode as it
2264 * would look like while receiving the stream at this point in time.
2265 * We walk the path up to the root. For every inode in between, we check if it
2266 * was already processed/sent. If yes, we continue with the parent as found
2267 * in send_root. If not, we continue with the parent as found in parent_root.
2268 * If we encounter an inode that was deleted at this point in time, we use the
2269 * inodes "orphan" name instead of the real name and stop. Same with new inodes
2270 * that were not created yet and overwritten inodes/refs.
2272 * When do we have orphan inodes:
2273 * 1. When an inode is freshly created and thus no valid refs are available yet
2274 * 2. When a directory lost all it's refs (deleted) but still has dir items
2275 * inside which were not processed yet (pending for move/delete). If anyone
2276 * tried to get the path to the dir items, it would get a path inside that
2278 * 3. When an inode is moved around or gets new links, it may overwrite the ref
2279 * of an unprocessed inode. If in that case the first ref would be
2280 * overwritten, the overwritten inode gets "orphanized". Later when we
2281 * process this overwritten inode, it is restored at a new place by moving
2284 * sctx->send_progress tells this function at which point in time receiving
2287 static int get_cur_path(struct send_ctx *sctx, u64 ino, u64 gen,
2288 struct fs_path *dest)
2291 struct fs_path *name = NULL;
2292 u64 parent_inode = 0;
2296 name = fs_path_alloc();
2303 fs_path_reset(dest);
2305 while (!stop && ino != BTRFS_FIRST_FREE_OBJECTID) {
2306 struct waiting_dir_move *wdm;
2308 fs_path_reset(name);
2310 if (is_waiting_for_rm(sctx, ino, gen)) {
2311 ret = gen_unique_name(sctx, ino, gen, name);
2314 ret = fs_path_add_path(dest, name);
2318 wdm = get_waiting_dir_move(sctx, ino);
2319 if (wdm && wdm->orphanized) {
2320 ret = gen_unique_name(sctx, ino, gen, name);
2323 ret = get_first_ref(sctx->parent_root, ino,
2324 &parent_inode, &parent_gen, name);
2326 ret = __get_cur_name_and_parent(sctx, ino, gen,
2336 ret = fs_path_add_path(dest, name);
2347 fs_path_unreverse(dest);
2352 * Sends a BTRFS_SEND_C_SUBVOL command/item to userspace
2354 static int send_subvol_begin(struct send_ctx *sctx)
2357 struct btrfs_root *send_root = sctx->send_root;
2358 struct btrfs_root *parent_root = sctx->parent_root;
2359 struct btrfs_path *path;
2360 struct btrfs_key key;
2361 struct btrfs_root_ref *ref;
2362 struct extent_buffer *leaf;
2366 path = btrfs_alloc_path();
2370 name = kmalloc(BTRFS_PATH_NAME_MAX, GFP_KERNEL);
2372 btrfs_free_path(path);
2376 key.objectid = send_root->root_key.objectid;
2377 key.type = BTRFS_ROOT_BACKREF_KEY;
2380 ret = btrfs_search_slot_for_read(send_root->fs_info->tree_root,
2389 leaf = path->nodes[0];
2390 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2391 if (key.type != BTRFS_ROOT_BACKREF_KEY ||
2392 key.objectid != send_root->root_key.objectid) {
2396 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
2397 namelen = btrfs_root_ref_name_len(leaf, ref);
2398 read_extent_buffer(leaf, name, (unsigned long)(ref + 1), namelen);
2399 btrfs_release_path(path);
2402 ret = begin_cmd(sctx, BTRFS_SEND_C_SNAPSHOT);
2406 ret = begin_cmd(sctx, BTRFS_SEND_C_SUBVOL);
2411 TLV_PUT_STRING(sctx, BTRFS_SEND_A_PATH, name, namelen);
2413 if (!btrfs_is_empty_uuid(sctx->send_root->root_item.received_uuid))
2414 TLV_PUT_UUID(sctx, BTRFS_SEND_A_UUID,
2415 sctx->send_root->root_item.received_uuid);
2417 TLV_PUT_UUID(sctx, BTRFS_SEND_A_UUID,
2418 sctx->send_root->root_item.uuid);
2420 TLV_PUT_U64(sctx, BTRFS_SEND_A_CTRANSID,
2421 le64_to_cpu(sctx->send_root->root_item.ctransid));
2423 if (!btrfs_is_empty_uuid(parent_root->root_item.received_uuid))
2424 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
2425 parent_root->root_item.received_uuid);
2427 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
2428 parent_root->root_item.uuid);
2429 TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_CTRANSID,
2430 le64_to_cpu(sctx->parent_root->root_item.ctransid));
2433 ret = send_cmd(sctx);
2437 btrfs_free_path(path);
2442 static int send_truncate(struct send_ctx *sctx, u64 ino, u64 gen, u64 size)
2444 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2448 btrfs_debug(fs_info, "send_truncate %llu size=%llu", ino, size);
2450 p = fs_path_alloc();
2454 ret = begin_cmd(sctx, BTRFS_SEND_C_TRUNCATE);
2458 ret = get_cur_path(sctx, ino, gen, p);
2461 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2462 TLV_PUT_U64(sctx, BTRFS_SEND_A_SIZE, size);
2464 ret = send_cmd(sctx);
2472 static int send_chmod(struct send_ctx *sctx, u64 ino, u64 gen, u64 mode)
2474 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2478 btrfs_debug(fs_info, "send_chmod %llu mode=%llu", ino, mode);
2480 p = fs_path_alloc();
2484 ret = begin_cmd(sctx, BTRFS_SEND_C_CHMOD);
2488 ret = get_cur_path(sctx, ino, gen, p);
2491 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2492 TLV_PUT_U64(sctx, BTRFS_SEND_A_MODE, mode & 07777);
2494 ret = send_cmd(sctx);
2502 static int send_chown(struct send_ctx *sctx, u64 ino, u64 gen, u64 uid, u64 gid)
2504 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2508 btrfs_debug(fs_info, "send_chown %llu uid=%llu, gid=%llu",
2511 p = fs_path_alloc();
2515 ret = begin_cmd(sctx, BTRFS_SEND_C_CHOWN);
2519 ret = get_cur_path(sctx, ino, gen, p);
2522 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2523 TLV_PUT_U64(sctx, BTRFS_SEND_A_UID, uid);
2524 TLV_PUT_U64(sctx, BTRFS_SEND_A_GID, gid);
2526 ret = send_cmd(sctx);
2534 static int send_utimes(struct send_ctx *sctx, u64 ino, u64 gen)
2536 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2538 struct fs_path *p = NULL;
2539 struct btrfs_inode_item *ii;
2540 struct btrfs_path *path = NULL;
2541 struct extent_buffer *eb;
2542 struct btrfs_key key;
2545 btrfs_debug(fs_info, "send_utimes %llu", ino);
2547 p = fs_path_alloc();
2551 path = alloc_path_for_send();
2558 key.type = BTRFS_INODE_ITEM_KEY;
2560 ret = btrfs_search_slot(NULL, sctx->send_root, &key, path, 0, 0);
2566 eb = path->nodes[0];
2567 slot = path->slots[0];
2568 ii = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
2570 ret = begin_cmd(sctx, BTRFS_SEND_C_UTIMES);
2574 ret = get_cur_path(sctx, ino, gen, p);
2577 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2578 TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_ATIME, eb, &ii->atime);
2579 TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_MTIME, eb, &ii->mtime);
2580 TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_CTIME, eb, &ii->ctime);
2581 /* TODO Add otime support when the otime patches get into upstream */
2583 ret = send_cmd(sctx);
2588 btrfs_free_path(path);
2593 * Sends a BTRFS_SEND_C_MKXXX or SYMLINK command to user space. We don't have
2594 * a valid path yet because we did not process the refs yet. So, the inode
2595 * is created as orphan.
2597 static int send_create_inode(struct send_ctx *sctx, u64 ino)
2599 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2607 btrfs_debug(fs_info, "send_create_inode %llu", ino);
2609 p = fs_path_alloc();
2613 if (ino != sctx->cur_ino) {
2614 ret = get_inode_info(sctx->send_root, ino, NULL, &gen, &mode,
2619 gen = sctx->cur_inode_gen;
2620 mode = sctx->cur_inode_mode;
2621 rdev = sctx->cur_inode_rdev;
2624 if (S_ISREG(mode)) {
2625 cmd = BTRFS_SEND_C_MKFILE;
2626 } else if (S_ISDIR(mode)) {
2627 cmd = BTRFS_SEND_C_MKDIR;
2628 } else if (S_ISLNK(mode)) {
2629 cmd = BTRFS_SEND_C_SYMLINK;
2630 } else if (S_ISCHR(mode) || S_ISBLK(mode)) {
2631 cmd = BTRFS_SEND_C_MKNOD;
2632 } else if (S_ISFIFO(mode)) {
2633 cmd = BTRFS_SEND_C_MKFIFO;
2634 } else if (S_ISSOCK(mode)) {
2635 cmd = BTRFS_SEND_C_MKSOCK;
2637 btrfs_warn(sctx->send_root->fs_info, "unexpected inode type %o",
2638 (int)(mode & S_IFMT));
2643 ret = begin_cmd(sctx, cmd);
2647 ret = gen_unique_name(sctx, ino, gen, p);
2651 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2652 TLV_PUT_U64(sctx, BTRFS_SEND_A_INO, ino);
2654 if (S_ISLNK(mode)) {
2656 ret = read_symlink(sctx->send_root, ino, p);
2659 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH_LINK, p);
2660 } else if (S_ISCHR(mode) || S_ISBLK(mode) ||
2661 S_ISFIFO(mode) || S_ISSOCK(mode)) {
2662 TLV_PUT_U64(sctx, BTRFS_SEND_A_RDEV, new_encode_dev(rdev));
2663 TLV_PUT_U64(sctx, BTRFS_SEND_A_MODE, mode);
2666 ret = send_cmd(sctx);
2678 * We need some special handling for inodes that get processed before the parent
2679 * directory got created. See process_recorded_refs for details.
2680 * This function does the check if we already created the dir out of order.
2682 static int did_create_dir(struct send_ctx *sctx, u64 dir)
2685 struct btrfs_path *path = NULL;
2686 struct btrfs_key key;
2687 struct btrfs_key found_key;
2688 struct btrfs_key di_key;
2689 struct extent_buffer *eb;
2690 struct btrfs_dir_item *di;
2693 path = alloc_path_for_send();
2700 key.type = BTRFS_DIR_INDEX_KEY;
2702 ret = btrfs_search_slot(NULL, sctx->send_root, &key, path, 0, 0);
2707 eb = path->nodes[0];
2708 slot = path->slots[0];
2709 if (slot >= btrfs_header_nritems(eb)) {
2710 ret = btrfs_next_leaf(sctx->send_root, path);
2713 } else if (ret > 0) {
2720 btrfs_item_key_to_cpu(eb, &found_key, slot);
2721 if (found_key.objectid != key.objectid ||
2722 found_key.type != key.type) {
2727 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
2728 btrfs_dir_item_key_to_cpu(eb, di, &di_key);
2730 if (di_key.type != BTRFS_ROOT_ITEM_KEY &&
2731 di_key.objectid < sctx->send_progress) {
2740 btrfs_free_path(path);
2745 * Only creates the inode if it is:
2746 * 1. Not a directory
2747 * 2. Or a directory which was not created already due to out of order
2748 * directories. See did_create_dir and process_recorded_refs for details.
2750 static int send_create_inode_if_needed(struct send_ctx *sctx)
2754 if (S_ISDIR(sctx->cur_inode_mode)) {
2755 ret = did_create_dir(sctx, sctx->cur_ino);
2764 ret = send_create_inode(sctx, sctx->cur_ino);
2772 struct recorded_ref {
2773 struct list_head list;
2775 struct fs_path *full_path;
2781 static void set_ref_path(struct recorded_ref *ref, struct fs_path *path)
2783 ref->full_path = path;
2784 ref->name = (char *)kbasename(ref->full_path->start);
2785 ref->name_len = ref->full_path->end - ref->name;
2789 * We need to process new refs before deleted refs, but compare_tree gives us
2790 * everything mixed. So we first record all refs and later process them.
2791 * This function is a helper to record one ref.
2793 static int __record_ref(struct list_head *head, u64 dir,
2794 u64 dir_gen, struct fs_path *path)
2796 struct recorded_ref *ref;
2798 ref = kmalloc(sizeof(*ref), GFP_KERNEL);
2803 ref->dir_gen = dir_gen;
2804 set_ref_path(ref, path);
2805 list_add_tail(&ref->list, head);
2809 static int dup_ref(struct recorded_ref *ref, struct list_head *list)
2811 struct recorded_ref *new;
2813 new = kmalloc(sizeof(*ref), GFP_KERNEL);
2817 new->dir = ref->dir;
2818 new->dir_gen = ref->dir_gen;
2819 new->full_path = NULL;
2820 INIT_LIST_HEAD(&new->list);
2821 list_add_tail(&new->list, list);
2825 static void __free_recorded_refs(struct list_head *head)
2827 struct recorded_ref *cur;
2829 while (!list_empty(head)) {
2830 cur = list_entry(head->next, struct recorded_ref, list);
2831 fs_path_free(cur->full_path);
2832 list_del(&cur->list);
2837 static void free_recorded_refs(struct send_ctx *sctx)
2839 __free_recorded_refs(&sctx->new_refs);
2840 __free_recorded_refs(&sctx->deleted_refs);
2844 * Renames/moves a file/dir to its orphan name. Used when the first
2845 * ref of an unprocessed inode gets overwritten and for all non empty
2848 static int orphanize_inode(struct send_ctx *sctx, u64 ino, u64 gen,
2849 struct fs_path *path)
2852 struct fs_path *orphan;
2854 orphan = fs_path_alloc();
2858 ret = gen_unique_name(sctx, ino, gen, orphan);
2862 ret = send_rename(sctx, path, orphan);
2865 fs_path_free(orphan);
2869 static struct orphan_dir_info *add_orphan_dir_info(struct send_ctx *sctx,
2870 u64 dir_ino, u64 dir_gen)
2872 struct rb_node **p = &sctx->orphan_dirs.rb_node;
2873 struct rb_node *parent = NULL;
2874 struct orphan_dir_info *entry, *odi;
2878 entry = rb_entry(parent, struct orphan_dir_info, node);
2879 if (dir_ino < entry->ino)
2881 else if (dir_ino > entry->ino)
2882 p = &(*p)->rb_right;
2883 else if (dir_gen < entry->gen)
2885 else if (dir_gen > entry->gen)
2886 p = &(*p)->rb_right;
2891 odi = kmalloc(sizeof(*odi), GFP_KERNEL);
2893 return ERR_PTR(-ENOMEM);
2896 odi->last_dir_index_offset = 0;
2898 rb_link_node(&odi->node, parent, p);
2899 rb_insert_color(&odi->node, &sctx->orphan_dirs);
2903 static struct orphan_dir_info *get_orphan_dir_info(struct send_ctx *sctx,
2904 u64 dir_ino, u64 gen)
2906 struct rb_node *n = sctx->orphan_dirs.rb_node;
2907 struct orphan_dir_info *entry;
2910 entry = rb_entry(n, struct orphan_dir_info, node);
2911 if (dir_ino < entry->ino)
2913 else if (dir_ino > entry->ino)
2915 else if (gen < entry->gen)
2917 else if (gen > entry->gen)
2925 static int is_waiting_for_rm(struct send_ctx *sctx, u64 dir_ino, u64 gen)
2927 struct orphan_dir_info *odi = get_orphan_dir_info(sctx, dir_ino, gen);
2932 static void free_orphan_dir_info(struct send_ctx *sctx,
2933 struct orphan_dir_info *odi)
2937 rb_erase(&odi->node, &sctx->orphan_dirs);
2942 * Returns 1 if a directory can be removed at this point in time.
2943 * We check this by iterating all dir items and checking if the inode behind
2944 * the dir item was already processed.
2946 static int can_rmdir(struct send_ctx *sctx, u64 dir, u64 dir_gen,
2950 struct btrfs_root *root = sctx->parent_root;
2951 struct btrfs_path *path;
2952 struct btrfs_key key;
2953 struct btrfs_key found_key;
2954 struct btrfs_key loc;
2955 struct btrfs_dir_item *di;
2956 struct orphan_dir_info *odi = NULL;
2959 * Don't try to rmdir the top/root subvolume dir.
2961 if (dir == BTRFS_FIRST_FREE_OBJECTID)
2964 path = alloc_path_for_send();
2969 key.type = BTRFS_DIR_INDEX_KEY;
2972 odi = get_orphan_dir_info(sctx, dir, dir_gen);
2974 key.offset = odi->last_dir_index_offset;
2976 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2981 struct waiting_dir_move *dm;
2983 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2984 ret = btrfs_next_leaf(root, path);
2991 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2993 if (found_key.objectid != key.objectid ||
2994 found_key.type != key.type)
2997 di = btrfs_item_ptr(path->nodes[0], path->slots[0],
2998 struct btrfs_dir_item);
2999 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &loc);
3001 dm = get_waiting_dir_move(sctx, loc.objectid);
3003 odi = add_orphan_dir_info(sctx, dir, dir_gen);
3009 odi->last_dir_index_offset = found_key.offset;
3010 dm->rmdir_ino = dir;
3011 dm->rmdir_gen = dir_gen;
3016 if (loc.objectid > send_progress) {
3017 odi = add_orphan_dir_info(sctx, dir, dir_gen);
3023 odi->last_dir_index_offset = found_key.offset;
3030 free_orphan_dir_info(sctx, odi);
3035 btrfs_free_path(path);
3039 static int is_waiting_for_move(struct send_ctx *sctx, u64 ino)
3041 struct waiting_dir_move *entry = get_waiting_dir_move(sctx, ino);
3043 return entry != NULL;
3046 static int add_waiting_dir_move(struct send_ctx *sctx, u64 ino, bool orphanized)
3048 struct rb_node **p = &sctx->waiting_dir_moves.rb_node;
3049 struct rb_node *parent = NULL;
3050 struct waiting_dir_move *entry, *dm;
3052 dm = kmalloc(sizeof(*dm), GFP_KERNEL);
3058 dm->orphanized = orphanized;
3062 entry = rb_entry(parent, struct waiting_dir_move, node);
3063 if (ino < entry->ino) {
3065 } else if (ino > entry->ino) {
3066 p = &(*p)->rb_right;
3073 rb_link_node(&dm->node, parent, p);
3074 rb_insert_color(&dm->node, &sctx->waiting_dir_moves);
3078 static struct waiting_dir_move *
3079 get_waiting_dir_move(struct send_ctx *sctx, u64 ino)
3081 struct rb_node *n = sctx->waiting_dir_moves.rb_node;
3082 struct waiting_dir_move *entry;
3085 entry = rb_entry(n, struct waiting_dir_move, node);
3086 if (ino < entry->ino)
3088 else if (ino > entry->ino)
3096 static void free_waiting_dir_move(struct send_ctx *sctx,
3097 struct waiting_dir_move *dm)
3101 rb_erase(&dm->node, &sctx->waiting_dir_moves);
3105 static int add_pending_dir_move(struct send_ctx *sctx,
3109 struct list_head *new_refs,
3110 struct list_head *deleted_refs,
3111 const bool is_orphan)
3113 struct rb_node **p = &sctx->pending_dir_moves.rb_node;
3114 struct rb_node *parent = NULL;
3115 struct pending_dir_move *entry = NULL, *pm;
3116 struct recorded_ref *cur;
3120 pm = kmalloc(sizeof(*pm), GFP_KERNEL);
3123 pm->parent_ino = parent_ino;
3126 INIT_LIST_HEAD(&pm->list);
3127 INIT_LIST_HEAD(&pm->update_refs);
3128 RB_CLEAR_NODE(&pm->node);
3132 entry = rb_entry(parent, struct pending_dir_move, node);
3133 if (parent_ino < entry->parent_ino) {
3135 } else if (parent_ino > entry->parent_ino) {
3136 p = &(*p)->rb_right;
3143 list_for_each_entry(cur, deleted_refs, list) {
3144 ret = dup_ref(cur, &pm->update_refs);
3148 list_for_each_entry(cur, new_refs, list) {
3149 ret = dup_ref(cur, &pm->update_refs);
3154 ret = add_waiting_dir_move(sctx, pm->ino, is_orphan);
3159 list_add_tail(&pm->list, &entry->list);
3161 rb_link_node(&pm->node, parent, p);
3162 rb_insert_color(&pm->node, &sctx->pending_dir_moves);
3167 __free_recorded_refs(&pm->update_refs);
3173 static struct pending_dir_move *get_pending_dir_moves(struct send_ctx *sctx,
3176 struct rb_node *n = sctx->pending_dir_moves.rb_node;
3177 struct pending_dir_move *entry;
3180 entry = rb_entry(n, struct pending_dir_move, node);
3181 if (parent_ino < entry->parent_ino)
3183 else if (parent_ino > entry->parent_ino)
3191 static int path_loop(struct send_ctx *sctx, struct fs_path *name,
3192 u64 ino, u64 gen, u64 *ancestor_ino)
3195 u64 parent_inode = 0;
3197 u64 start_ino = ino;
3200 while (ino != BTRFS_FIRST_FREE_OBJECTID) {
3201 fs_path_reset(name);
3203 if (is_waiting_for_rm(sctx, ino, gen))
3205 if (is_waiting_for_move(sctx, ino)) {
3206 if (*ancestor_ino == 0)
3207 *ancestor_ino = ino;
3208 ret = get_first_ref(sctx->parent_root, ino,
3209 &parent_inode, &parent_gen, name);
3211 ret = __get_cur_name_and_parent(sctx, ino, gen,
3221 if (parent_inode == start_ino) {
3223 if (*ancestor_ino == 0)
3224 *ancestor_ino = ino;
3233 static int apply_dir_move(struct send_ctx *sctx, struct pending_dir_move *pm)
3235 struct fs_path *from_path = NULL;
3236 struct fs_path *to_path = NULL;
3237 struct fs_path *name = NULL;
3238 u64 orig_progress = sctx->send_progress;
3239 struct recorded_ref *cur;
3240 u64 parent_ino, parent_gen;
3241 struct waiting_dir_move *dm = NULL;
3248 name = fs_path_alloc();
3249 from_path = fs_path_alloc();
3250 if (!name || !from_path) {
3255 dm = get_waiting_dir_move(sctx, pm->ino);
3257 rmdir_ino = dm->rmdir_ino;
3258 rmdir_gen = dm->rmdir_gen;
3259 is_orphan = dm->orphanized;
3260 free_waiting_dir_move(sctx, dm);
3263 ret = gen_unique_name(sctx, pm->ino,
3264 pm->gen, from_path);
3266 ret = get_first_ref(sctx->parent_root, pm->ino,
3267 &parent_ino, &parent_gen, name);
3270 ret = get_cur_path(sctx, parent_ino, parent_gen,
3274 ret = fs_path_add_path(from_path, name);
3279 sctx->send_progress = sctx->cur_ino + 1;
3280 ret = path_loop(sctx, name, pm->ino, pm->gen, &ancestor);
3284 LIST_HEAD(deleted_refs);
3285 ASSERT(ancestor > BTRFS_FIRST_FREE_OBJECTID);
3286 ret = add_pending_dir_move(sctx, pm->ino, pm->gen, ancestor,
3287 &pm->update_refs, &deleted_refs,
3292 dm = get_waiting_dir_move(sctx, pm->ino);
3294 dm->rmdir_ino = rmdir_ino;
3295 dm->rmdir_gen = rmdir_gen;
3299 fs_path_reset(name);
3302 ret = get_cur_path(sctx, pm->ino, pm->gen, to_path);
3306 ret = send_rename(sctx, from_path, to_path);
3311 struct orphan_dir_info *odi;
3314 odi = get_orphan_dir_info(sctx, rmdir_ino, rmdir_gen);
3316 /* already deleted */
3321 ret = can_rmdir(sctx, rmdir_ino, gen, sctx->cur_ino);
3327 name = fs_path_alloc();
3332 ret = get_cur_path(sctx, rmdir_ino, gen, name);
3335 ret = send_rmdir(sctx, name);
3341 ret = send_utimes(sctx, pm->ino, pm->gen);
3346 * After rename/move, need to update the utimes of both new parent(s)
3347 * and old parent(s).
3349 list_for_each_entry(cur, &pm->update_refs, list) {
3351 * The parent inode might have been deleted in the send snapshot
3353 ret = get_inode_info(sctx->send_root, cur->dir, NULL,
3354 NULL, NULL, NULL, NULL, NULL);
3355 if (ret == -ENOENT) {
3362 ret = send_utimes(sctx, cur->dir, cur->dir_gen);
3369 fs_path_free(from_path);
3370 fs_path_free(to_path);
3371 sctx->send_progress = orig_progress;
3376 static void free_pending_move(struct send_ctx *sctx, struct pending_dir_move *m)
3378 if (!list_empty(&m->list))
3380 if (!RB_EMPTY_NODE(&m->node))
3381 rb_erase(&m->node, &sctx->pending_dir_moves);
3382 __free_recorded_refs(&m->update_refs);
3386 static void tail_append_pending_moves(struct send_ctx *sctx,
3387 struct pending_dir_move *moves,
3388 struct list_head *stack)
3390 if (list_empty(&moves->list)) {
3391 list_add_tail(&moves->list, stack);
3394 list_splice_init(&moves->list, &list);
3395 list_add_tail(&moves->list, stack);
3396 list_splice_tail(&list, stack);
3398 if (!RB_EMPTY_NODE(&moves->node)) {
3399 rb_erase(&moves->node, &sctx->pending_dir_moves);
3400 RB_CLEAR_NODE(&moves->node);
3404 static int apply_children_dir_moves(struct send_ctx *sctx)
3406 struct pending_dir_move *pm;
3407 struct list_head stack;
3408 u64 parent_ino = sctx->cur_ino;
3411 pm = get_pending_dir_moves(sctx, parent_ino);
3415 INIT_LIST_HEAD(&stack);
3416 tail_append_pending_moves(sctx, pm, &stack);
3418 while (!list_empty(&stack)) {
3419 pm = list_first_entry(&stack, struct pending_dir_move, list);
3420 parent_ino = pm->ino;
3421 ret = apply_dir_move(sctx, pm);
3422 free_pending_move(sctx, pm);
3425 pm = get_pending_dir_moves(sctx, parent_ino);
3427 tail_append_pending_moves(sctx, pm, &stack);
3432 while (!list_empty(&stack)) {
3433 pm = list_first_entry(&stack, struct pending_dir_move, list);
3434 free_pending_move(sctx, pm);
3440 * We might need to delay a directory rename even when no ancestor directory
3441 * (in the send root) with a higher inode number than ours (sctx->cur_ino) was
3442 * renamed. This happens when we rename a directory to the old name (the name
3443 * in the parent root) of some other unrelated directory that got its rename
3444 * delayed due to some ancestor with higher number that got renamed.
3450 * |---- a/ (ino 257)
3451 * | |---- file (ino 260)
3453 * |---- b/ (ino 258)
3454 * |---- c/ (ino 259)
3458 * |---- a/ (ino 258)
3459 * |---- x/ (ino 259)
3460 * |---- y/ (ino 257)
3461 * |----- file (ino 260)
3463 * Here we can not rename 258 from 'b' to 'a' without the rename of inode 257
3464 * from 'a' to 'x/y' happening first, which in turn depends on the rename of
3465 * inode 259 from 'c' to 'x'. So the order of rename commands the send stream
3468 * 1 - rename 259 from 'c' to 'x'
3469 * 2 - rename 257 from 'a' to 'x/y'
3470 * 3 - rename 258 from 'b' to 'a'
3472 * Returns 1 if the rename of sctx->cur_ino needs to be delayed, 0 if it can
3473 * be done right away and < 0 on error.
3475 static int wait_for_dest_dir_move(struct send_ctx *sctx,
3476 struct recorded_ref *parent_ref,
3477 const bool is_orphan)
3479 struct btrfs_fs_info *fs_info = sctx->parent_root->fs_info;
3480 struct btrfs_path *path;
3481 struct btrfs_key key;
3482 struct btrfs_key di_key;
3483 struct btrfs_dir_item *di;
3487 struct waiting_dir_move *wdm;
3489 if (RB_EMPTY_ROOT(&sctx->waiting_dir_moves))
3492 path = alloc_path_for_send();
3496 key.objectid = parent_ref->dir;
3497 key.type = BTRFS_DIR_ITEM_KEY;
3498 key.offset = btrfs_name_hash(parent_ref->name, parent_ref->name_len);
3500 ret = btrfs_search_slot(NULL, sctx->parent_root, &key, path, 0, 0);
3503 } else if (ret > 0) {
3508 di = btrfs_match_dir_item_name(fs_info, path, parent_ref->name,
3509 parent_ref->name_len);
3515 * di_key.objectid has the number of the inode that has a dentry in the
3516 * parent directory with the same name that sctx->cur_ino is being
3517 * renamed to. We need to check if that inode is in the send root as
3518 * well and if it is currently marked as an inode with a pending rename,
3519 * if it is, we need to delay the rename of sctx->cur_ino as well, so
3520 * that it happens after that other inode is renamed.
3522 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &di_key);
3523 if (di_key.type != BTRFS_INODE_ITEM_KEY) {
3528 ret = get_inode_info(sctx->parent_root, di_key.objectid, NULL,
3529 &left_gen, NULL, NULL, NULL, NULL);
3532 ret = get_inode_info(sctx->send_root, di_key.objectid, NULL,
3533 &right_gen, NULL, NULL, NULL, NULL);
3540 /* Different inode, no need to delay the rename of sctx->cur_ino */
3541 if (right_gen != left_gen) {
3546 wdm = get_waiting_dir_move(sctx, di_key.objectid);
3547 if (wdm && !wdm->orphanized) {
3548 ret = add_pending_dir_move(sctx,
3550 sctx->cur_inode_gen,
3553 &sctx->deleted_refs,
3559 btrfs_free_path(path);
3564 * Check if inode ino2, or any of its ancestors, is inode ino1.
3565 * Return 1 if true, 0 if false and < 0 on error.
3567 static int check_ino_in_path(struct btrfs_root *root,
3572 struct fs_path *fs_path)
3577 return ino1_gen == ino2_gen;
3579 while (ino > BTRFS_FIRST_FREE_OBJECTID) {
3584 fs_path_reset(fs_path);
3585 ret = get_first_ref(root, ino, &parent, &parent_gen, fs_path);
3589 return parent_gen == ino1_gen;
3596 * Check if ino ino1 is an ancestor of inode ino2 in the given root for any
3597 * possible path (in case ino2 is not a directory and has multiple hard links).
3598 * Return 1 if true, 0 if false and < 0 on error.
3600 static int is_ancestor(struct btrfs_root *root,
3604 struct fs_path *fs_path)
3606 bool free_fs_path = false;
3608 struct btrfs_path *path = NULL;
3609 struct btrfs_key key;
3612 fs_path = fs_path_alloc();
3615 free_fs_path = true;
3618 path = alloc_path_for_send();
3624 key.objectid = ino2;
3625 key.type = BTRFS_INODE_REF_KEY;
3628 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3633 struct extent_buffer *leaf = path->nodes[0];
3634 int slot = path->slots[0];
3638 if (slot >= btrfs_header_nritems(leaf)) {
3639 ret = btrfs_next_leaf(root, path);
3647 btrfs_item_key_to_cpu(leaf, &key, slot);
3648 if (key.objectid != ino2)
3650 if (key.type != BTRFS_INODE_REF_KEY &&
3651 key.type != BTRFS_INODE_EXTREF_KEY)
3654 item_size = btrfs_item_size_nr(leaf, slot);
3655 while (cur_offset < item_size) {
3659 if (key.type == BTRFS_INODE_EXTREF_KEY) {
3661 struct btrfs_inode_extref *extref;
3663 ptr = btrfs_item_ptr_offset(leaf, slot);
3664 extref = (struct btrfs_inode_extref *)
3666 parent = btrfs_inode_extref_parent(leaf,
3668 cur_offset += sizeof(*extref);
3669 cur_offset += btrfs_inode_extref_name_len(leaf,
3672 parent = key.offset;
3673 cur_offset = item_size;
3676 ret = get_inode_info(root, parent, NULL, &parent_gen,
3677 NULL, NULL, NULL, NULL);
3680 ret = check_ino_in_path(root, ino1, ino1_gen,
3681 parent, parent_gen, fs_path);
3689 btrfs_free_path(path);
3691 fs_path_free(fs_path);
3695 static int wait_for_parent_move(struct send_ctx *sctx,
3696 struct recorded_ref *parent_ref,
3697 const bool is_orphan)
3700 u64 ino = parent_ref->dir;
3701 u64 ino_gen = parent_ref->dir_gen;
3702 u64 parent_ino_before, parent_ino_after;
3703 struct fs_path *path_before = NULL;
3704 struct fs_path *path_after = NULL;
3707 path_after = fs_path_alloc();
3708 path_before = fs_path_alloc();
3709 if (!path_after || !path_before) {
3715 * Our current directory inode may not yet be renamed/moved because some
3716 * ancestor (immediate or not) has to be renamed/moved first. So find if
3717 * such ancestor exists and make sure our own rename/move happens after
3718 * that ancestor is processed to avoid path build infinite loops (done
3719 * at get_cur_path()).
3721 while (ino > BTRFS_FIRST_FREE_OBJECTID) {
3722 u64 parent_ino_after_gen;
3724 if (is_waiting_for_move(sctx, ino)) {
3726 * If the current inode is an ancestor of ino in the
3727 * parent root, we need to delay the rename of the
3728 * current inode, otherwise don't delayed the rename
3729 * because we can end up with a circular dependency
3730 * of renames, resulting in some directories never
3731 * getting the respective rename operations issued in
3732 * the send stream or getting into infinite path build
3735 ret = is_ancestor(sctx->parent_root,
3736 sctx->cur_ino, sctx->cur_inode_gen,
3742 fs_path_reset(path_before);
3743 fs_path_reset(path_after);
3745 ret = get_first_ref(sctx->send_root, ino, &parent_ino_after,
3746 &parent_ino_after_gen, path_after);
3749 ret = get_first_ref(sctx->parent_root, ino, &parent_ino_before,
3751 if (ret < 0 && ret != -ENOENT) {
3753 } else if (ret == -ENOENT) {
3758 len1 = fs_path_len(path_before);
3759 len2 = fs_path_len(path_after);
3760 if (ino > sctx->cur_ino &&
3761 (parent_ino_before != parent_ino_after || len1 != len2 ||
3762 memcmp(path_before->start, path_after->start, len1))) {
3765 ret = get_inode_info(sctx->parent_root, ino, NULL,
3766 &parent_ino_gen, NULL, NULL, NULL,
3770 if (ino_gen == parent_ino_gen) {
3775 ino = parent_ino_after;
3776 ino_gen = parent_ino_after_gen;
3780 fs_path_free(path_before);
3781 fs_path_free(path_after);
3784 ret = add_pending_dir_move(sctx,
3786 sctx->cur_inode_gen,
3789 &sctx->deleted_refs,
3798 static int update_ref_path(struct send_ctx *sctx, struct recorded_ref *ref)
3801 struct fs_path *new_path;
3804 * Our reference's name member points to its full_path member string, so
3805 * we use here a new path.
3807 new_path = fs_path_alloc();
3811 ret = get_cur_path(sctx, ref->dir, ref->dir_gen, new_path);
3813 fs_path_free(new_path);
3816 ret = fs_path_add(new_path, ref->name, ref->name_len);
3818 fs_path_free(new_path);
3822 fs_path_free(ref->full_path);
3823 set_ref_path(ref, new_path);
3829 * When processing the new references for an inode we may orphanize an existing
3830 * directory inode because its old name conflicts with one of the new references
3831 * of the current inode. Later, when processing another new reference of our
3832 * inode, we might need to orphanize another inode, but the path we have in the
3833 * reference reflects the pre-orphanization name of the directory we previously
3834 * orphanized. For example:
3836 * parent snapshot looks like:
3839 * |----- f1 (ino 257)
3840 * |----- f2 (ino 258)
3841 * |----- d1/ (ino 259)
3842 * |----- d2/ (ino 260)
3844 * send snapshot looks like:
3847 * |----- d1 (ino 258)
3848 * |----- f2/ (ino 259)
3849 * |----- f2_link/ (ino 260)
3850 * | |----- f1 (ino 257)
3852 * |----- d2 (ino 258)
3854 * When processing inode 257 we compute the name for inode 259 as "d1", and we
3855 * cache it in the name cache. Later when we start processing inode 258, when
3856 * collecting all its new references we set a full path of "d1/d2" for its new
3857 * reference with name "d2". When we start processing the new references we
3858 * start by processing the new reference with name "d1", and this results in
3859 * orphanizing inode 259, since its old reference causes a conflict. Then we
3860 * move on the next new reference, with name "d2", and we find out we must
3861 * orphanize inode 260, as its old reference conflicts with ours - but for the
3862 * orphanization we use a source path corresponding to the path we stored in the
3863 * new reference, which is "d1/d2" and not "o259-6-0/d2" - this makes the
3864 * receiver fail since the path component "d1/" no longer exists, it was renamed
3865 * to "o259-6-0/" when processing the previous new reference. So in this case we
3866 * must recompute the path in the new reference and use it for the new
3867 * orphanization operation.
3869 static int refresh_ref_path(struct send_ctx *sctx, struct recorded_ref *ref)
3874 name = kmemdup(ref->name, ref->name_len, GFP_KERNEL);
3878 fs_path_reset(ref->full_path);
3879 ret = get_cur_path(sctx, ref->dir, ref->dir_gen, ref->full_path);
3883 ret = fs_path_add(ref->full_path, name, ref->name_len);
3887 /* Update the reference's base name pointer. */
3888 set_ref_path(ref, ref->full_path);
3895 * This does all the move/link/unlink/rmdir magic.
3897 static int process_recorded_refs(struct send_ctx *sctx, int *pending_move)
3899 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
3901 struct recorded_ref *cur;
3902 struct recorded_ref *cur2;
3903 struct list_head check_dirs;
3904 struct fs_path *valid_path = NULL;
3908 int did_overwrite = 0;
3910 u64 last_dir_ino_rm = 0;
3911 bool can_rename = true;
3912 bool orphanized_dir = false;
3913 bool orphanized_ancestor = false;
3915 btrfs_debug(fs_info, "process_recorded_refs %llu", sctx->cur_ino);
3918 * This should never happen as the root dir always has the same ref
3919 * which is always '..'
3921 BUG_ON(sctx->cur_ino <= BTRFS_FIRST_FREE_OBJECTID);
3922 INIT_LIST_HEAD(&check_dirs);
3924 valid_path = fs_path_alloc();
3931 * First, check if the first ref of the current inode was overwritten
3932 * before. If yes, we know that the current inode was already orphanized
3933 * and thus use the orphan name. If not, we can use get_cur_path to
3934 * get the path of the first ref as it would like while receiving at
3935 * this point in time.
3936 * New inodes are always orphan at the beginning, so force to use the
3937 * orphan name in this case.
3938 * The first ref is stored in valid_path and will be updated if it
3939 * gets moved around.
3941 if (!sctx->cur_inode_new) {
3942 ret = did_overwrite_first_ref(sctx, sctx->cur_ino,
3943 sctx->cur_inode_gen);
3949 if (sctx->cur_inode_new || did_overwrite) {
3950 ret = gen_unique_name(sctx, sctx->cur_ino,
3951 sctx->cur_inode_gen, valid_path);
3956 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen,
3963 * Before doing any rename and link operations, do a first pass on the
3964 * new references to orphanize any unprocessed inodes that may have a
3965 * reference that conflicts with one of the new references of the current
3966 * inode. This needs to happen first because a new reference may conflict
3967 * with the old reference of a parent directory, so we must make sure
3968 * that the path used for link and rename commands don't use an
3969 * orphanized name when an ancestor was not yet orphanized.
3976 * |----- testdir/ (ino 259)
3977 * | |----- a (ino 257)
3979 * |----- b (ino 258)
3984 * |----- testdir_2/ (ino 259)
3985 * | |----- a (ino 260)
3987 * |----- testdir (ino 257)
3988 * |----- b (ino 257)
3989 * |----- b2 (ino 258)
3991 * Processing the new reference for inode 257 with name "b" may happen
3992 * before processing the new reference with name "testdir". If so, we
3993 * must make sure that by the time we send a link command to create the
3994 * hard link "b", inode 259 was already orphanized, since the generated
3995 * path in "valid_path" already contains the orphanized name for 259.
3996 * We are processing inode 257, so only later when processing 259 we do
3997 * the rename operation to change its temporary (orphanized) name to
4000 list_for_each_entry(cur, &sctx->new_refs, list) {
4001 ret = get_cur_inode_state(sctx, cur->dir, cur->dir_gen);
4004 if (ret == inode_state_will_create)
4008 * Check if this new ref would overwrite the first ref of another
4009 * unprocessed inode. If yes, orphanize the overwritten inode.
4010 * If we find an overwritten ref that is not the first ref,
4013 ret = will_overwrite_ref(sctx, cur->dir, cur->dir_gen,
4014 cur->name, cur->name_len,
4015 &ow_inode, &ow_gen, &ow_mode);
4019 ret = is_first_ref(sctx->parent_root,
4020 ow_inode, cur->dir, cur->name,
4025 struct name_cache_entry *nce;
4026 struct waiting_dir_move *wdm;
4028 if (orphanized_dir) {
4029 ret = refresh_ref_path(sctx, cur);
4034 ret = orphanize_inode(sctx, ow_inode, ow_gen,
4038 if (S_ISDIR(ow_mode))
4039 orphanized_dir = true;
4042 * If ow_inode has its rename operation delayed
4043 * make sure that its orphanized name is used in
4044 * the source path when performing its rename
4047 if (is_waiting_for_move(sctx, ow_inode)) {
4048 wdm = get_waiting_dir_move(sctx,
4051 wdm->orphanized = true;
4055 * Make sure we clear our orphanized inode's
4056 * name from the name cache. This is because the
4057 * inode ow_inode might be an ancestor of some
4058 * other inode that will be orphanized as well
4059 * later and has an inode number greater than
4060 * sctx->send_progress. We need to prevent
4061 * future name lookups from using the old name
4062 * and get instead the orphan name.
4064 nce = name_cache_search(sctx, ow_inode, ow_gen);
4066 name_cache_delete(sctx, nce);
4071 * ow_inode might currently be an ancestor of
4072 * cur_ino, therefore compute valid_path (the
4073 * current path of cur_ino) again because it
4074 * might contain the pre-orphanization name of
4075 * ow_inode, which is no longer valid.
4077 ret = is_ancestor(sctx->parent_root,
4079 sctx->cur_ino, NULL);
4081 orphanized_ancestor = true;
4082 fs_path_reset(valid_path);
4083 ret = get_cur_path(sctx, sctx->cur_ino,
4084 sctx->cur_inode_gen,
4091 * If we previously orphanized a directory that
4092 * collided with a new reference that we already
4093 * processed, recompute the current path because
4094 * that directory may be part of the path.
4096 if (orphanized_dir) {
4097 ret = refresh_ref_path(sctx, cur);
4101 ret = send_unlink(sctx, cur->full_path);
4109 list_for_each_entry(cur, &sctx->new_refs, list) {
4111 * We may have refs where the parent directory does not exist
4112 * yet. This happens if the parent directories inum is higher
4113 * than the current inum. To handle this case, we create the
4114 * parent directory out of order. But we need to check if this
4115 * did already happen before due to other refs in the same dir.
4117 ret = get_cur_inode_state(sctx, cur->dir, cur->dir_gen);
4120 if (ret == inode_state_will_create) {
4123 * First check if any of the current inodes refs did
4124 * already create the dir.
4126 list_for_each_entry(cur2, &sctx->new_refs, list) {
4129 if (cur2->dir == cur->dir) {
4136 * If that did not happen, check if a previous inode
4137 * did already create the dir.
4140 ret = did_create_dir(sctx, cur->dir);
4144 ret = send_create_inode(sctx, cur->dir);
4150 if (S_ISDIR(sctx->cur_inode_mode) && sctx->parent_root) {
4151 ret = wait_for_dest_dir_move(sctx, cur, is_orphan);
4160 if (S_ISDIR(sctx->cur_inode_mode) && sctx->parent_root &&
4162 ret = wait_for_parent_move(sctx, cur, is_orphan);
4172 * link/move the ref to the new place. If we have an orphan
4173 * inode, move it and update valid_path. If not, link or move
4174 * it depending on the inode mode.
4176 if (is_orphan && can_rename) {
4177 ret = send_rename(sctx, valid_path, cur->full_path);
4181 ret = fs_path_copy(valid_path, cur->full_path);
4184 } else if (can_rename) {
4185 if (S_ISDIR(sctx->cur_inode_mode)) {
4187 * Dirs can't be linked, so move it. For moved
4188 * dirs, we always have one new and one deleted
4189 * ref. The deleted ref is ignored later.
4191 ret = send_rename(sctx, valid_path,
4194 ret = fs_path_copy(valid_path,
4200 * We might have previously orphanized an inode
4201 * which is an ancestor of our current inode,
4202 * so our reference's full path, which was
4203 * computed before any such orphanizations, must
4206 if (orphanized_dir) {
4207 ret = update_ref_path(sctx, cur);
4211 ret = send_link(sctx, cur->full_path,
4217 ret = dup_ref(cur, &check_dirs);
4222 if (S_ISDIR(sctx->cur_inode_mode) && sctx->cur_inode_deleted) {
4224 * Check if we can already rmdir the directory. If not,
4225 * orphanize it. For every dir item inside that gets deleted
4226 * later, we do this check again and rmdir it then if possible.
4227 * See the use of check_dirs for more details.
4229 ret = can_rmdir(sctx, sctx->cur_ino, sctx->cur_inode_gen,
4234 ret = send_rmdir(sctx, valid_path);
4237 } else if (!is_orphan) {
4238 ret = orphanize_inode(sctx, sctx->cur_ino,
4239 sctx->cur_inode_gen, valid_path);
4245 list_for_each_entry(cur, &sctx->deleted_refs, list) {
4246 ret = dup_ref(cur, &check_dirs);
4250 } else if (S_ISDIR(sctx->cur_inode_mode) &&
4251 !list_empty(&sctx->deleted_refs)) {
4253 * We have a moved dir. Add the old parent to check_dirs
4255 cur = list_entry(sctx->deleted_refs.next, struct recorded_ref,
4257 ret = dup_ref(cur, &check_dirs);
4260 } else if (!S_ISDIR(sctx->cur_inode_mode)) {
4262 * We have a non dir inode. Go through all deleted refs and
4263 * unlink them if they were not already overwritten by other
4266 list_for_each_entry(cur, &sctx->deleted_refs, list) {
4267 ret = did_overwrite_ref(sctx, cur->dir, cur->dir_gen,
4268 sctx->cur_ino, sctx->cur_inode_gen,
4269 cur->name, cur->name_len);
4274 * If we orphanized any ancestor before, we need
4275 * to recompute the full path for deleted names,
4276 * since any such path was computed before we
4277 * processed any references and orphanized any
4280 if (orphanized_ancestor) {
4281 ret = update_ref_path(sctx, cur);
4285 ret = send_unlink(sctx, cur->full_path);
4289 ret = dup_ref(cur, &check_dirs);
4294 * If the inode is still orphan, unlink the orphan. This may
4295 * happen when a previous inode did overwrite the first ref
4296 * of this inode and no new refs were added for the current
4297 * inode. Unlinking does not mean that the inode is deleted in
4298 * all cases. There may still be links to this inode in other
4302 ret = send_unlink(sctx, valid_path);
4309 * We did collect all parent dirs where cur_inode was once located. We
4310 * now go through all these dirs and check if they are pending for
4311 * deletion and if it's finally possible to perform the rmdir now.
4312 * We also update the inode stats of the parent dirs here.
4314 list_for_each_entry(cur, &check_dirs, list) {
4316 * In case we had refs into dirs that were not processed yet,
4317 * we don't need to do the utime and rmdir logic for these dirs.
4318 * The dir will be processed later.
4320 if (cur->dir > sctx->cur_ino)
4323 ret = get_cur_inode_state(sctx, cur->dir, cur->dir_gen);
4327 if (ret == inode_state_did_create ||
4328 ret == inode_state_no_change) {
4329 /* TODO delayed utimes */
4330 ret = send_utimes(sctx, cur->dir, cur->dir_gen);
4333 } else if (ret == inode_state_did_delete &&
4334 cur->dir != last_dir_ino_rm) {
4335 ret = can_rmdir(sctx, cur->dir, cur->dir_gen,
4340 ret = get_cur_path(sctx, cur->dir,
4341 cur->dir_gen, valid_path);
4344 ret = send_rmdir(sctx, valid_path);
4347 last_dir_ino_rm = cur->dir;
4355 __free_recorded_refs(&check_dirs);
4356 free_recorded_refs(sctx);
4357 fs_path_free(valid_path);
4361 static int record_ref(struct btrfs_root *root, u64 dir, struct fs_path *name,
4362 void *ctx, struct list_head *refs)
4365 struct send_ctx *sctx = ctx;
4369 p = fs_path_alloc();
4373 ret = get_inode_info(root, dir, NULL, &gen, NULL, NULL,
4378 ret = get_cur_path(sctx, dir, gen, p);
4381 ret = fs_path_add_path(p, name);
4385 ret = __record_ref(refs, dir, gen, p);
4393 static int __record_new_ref(int num, u64 dir, int index,
4394 struct fs_path *name,
4397 struct send_ctx *sctx = ctx;
4398 return record_ref(sctx->send_root, dir, name, ctx, &sctx->new_refs);
4402 static int __record_deleted_ref(int num, u64 dir, int index,
4403 struct fs_path *name,
4406 struct send_ctx *sctx = ctx;
4407 return record_ref(sctx->parent_root, dir, name, ctx,
4408 &sctx->deleted_refs);
4411 static int record_new_ref(struct send_ctx *sctx)
4415 ret = iterate_inode_ref(sctx->send_root, sctx->left_path,
4416 sctx->cmp_key, 0, __record_new_ref, sctx);
4425 static int record_deleted_ref(struct send_ctx *sctx)
4429 ret = iterate_inode_ref(sctx->parent_root, sctx->right_path,
4430 sctx->cmp_key, 0, __record_deleted_ref, sctx);
4439 struct find_ref_ctx {
4442 struct btrfs_root *root;
4443 struct fs_path *name;
4447 static int __find_iref(int num, u64 dir, int index,
4448 struct fs_path *name,
4451 struct find_ref_ctx *ctx = ctx_;
4455 if (dir == ctx->dir && fs_path_len(name) == fs_path_len(ctx->name) &&
4456 strncmp(name->start, ctx->name->start, fs_path_len(name)) == 0) {
4458 * To avoid doing extra lookups we'll only do this if everything
4461 ret = get_inode_info(ctx->root, dir, NULL, &dir_gen, NULL,
4465 if (dir_gen != ctx->dir_gen)
4467 ctx->found_idx = num;
4473 static int find_iref(struct btrfs_root *root,
4474 struct btrfs_path *path,
4475 struct btrfs_key *key,
4476 u64 dir, u64 dir_gen, struct fs_path *name)
4479 struct find_ref_ctx ctx;
4483 ctx.dir_gen = dir_gen;
4487 ret = iterate_inode_ref(root, path, key, 0, __find_iref, &ctx);
4491 if (ctx.found_idx == -1)
4494 return ctx.found_idx;
4497 static int __record_changed_new_ref(int num, u64 dir, int index,
4498 struct fs_path *name,
4503 struct send_ctx *sctx = ctx;
4505 ret = get_inode_info(sctx->send_root, dir, NULL, &dir_gen, NULL,
4510 ret = find_iref(sctx->parent_root, sctx->right_path,
4511 sctx->cmp_key, dir, dir_gen, name);
4513 ret = __record_new_ref(num, dir, index, name, sctx);
4520 static int __record_changed_deleted_ref(int num, u64 dir, int index,
4521 struct fs_path *name,
4526 struct send_ctx *sctx = ctx;
4528 ret = get_inode_info(sctx->parent_root, dir, NULL, &dir_gen, NULL,
4533 ret = find_iref(sctx->send_root, sctx->left_path, sctx->cmp_key,
4534 dir, dir_gen, name);
4536 ret = __record_deleted_ref(num, dir, index, name, sctx);
4543 static int record_changed_ref(struct send_ctx *sctx)
4547 ret = iterate_inode_ref(sctx->send_root, sctx->left_path,
4548 sctx->cmp_key, 0, __record_changed_new_ref, sctx);
4551 ret = iterate_inode_ref(sctx->parent_root, sctx->right_path,
4552 sctx->cmp_key, 0, __record_changed_deleted_ref, sctx);
4562 * Record and process all refs at once. Needed when an inode changes the
4563 * generation number, which means that it was deleted and recreated.
4565 static int process_all_refs(struct send_ctx *sctx,
4566 enum btrfs_compare_tree_result cmd)
4569 struct btrfs_root *root;
4570 struct btrfs_path *path;
4571 struct btrfs_key key;
4572 struct btrfs_key found_key;
4573 struct extent_buffer *eb;
4575 iterate_inode_ref_t cb;
4576 int pending_move = 0;
4578 path = alloc_path_for_send();
4582 if (cmd == BTRFS_COMPARE_TREE_NEW) {
4583 root = sctx->send_root;
4584 cb = __record_new_ref;
4585 } else if (cmd == BTRFS_COMPARE_TREE_DELETED) {
4586 root = sctx->parent_root;
4587 cb = __record_deleted_ref;
4589 btrfs_err(sctx->send_root->fs_info,
4590 "Wrong command %d in process_all_refs", cmd);
4595 key.objectid = sctx->cmp_key->objectid;
4596 key.type = BTRFS_INODE_REF_KEY;
4598 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4603 eb = path->nodes[0];
4604 slot = path->slots[0];
4605 if (slot >= btrfs_header_nritems(eb)) {
4606 ret = btrfs_next_leaf(root, path);
4614 btrfs_item_key_to_cpu(eb, &found_key, slot);
4616 if (found_key.objectid != key.objectid ||
4617 (found_key.type != BTRFS_INODE_REF_KEY &&
4618 found_key.type != BTRFS_INODE_EXTREF_KEY))
4621 ret = iterate_inode_ref(root, path, &found_key, 0, cb, sctx);
4627 btrfs_release_path(path);
4630 * We don't actually care about pending_move as we are simply
4631 * re-creating this inode and will be rename'ing it into place once we
4632 * rename the parent directory.
4634 ret = process_recorded_refs(sctx, &pending_move);
4636 btrfs_free_path(path);
4640 static int send_set_xattr(struct send_ctx *sctx,
4641 struct fs_path *path,
4642 const char *name, int name_len,
4643 const char *data, int data_len)
4647 ret = begin_cmd(sctx, BTRFS_SEND_C_SET_XATTR);
4651 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
4652 TLV_PUT_STRING(sctx, BTRFS_SEND_A_XATTR_NAME, name, name_len);
4653 TLV_PUT(sctx, BTRFS_SEND_A_XATTR_DATA, data, data_len);
4655 ret = send_cmd(sctx);
4662 static int send_remove_xattr(struct send_ctx *sctx,
4663 struct fs_path *path,
4664 const char *name, int name_len)
4668 ret = begin_cmd(sctx, BTRFS_SEND_C_REMOVE_XATTR);
4672 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
4673 TLV_PUT_STRING(sctx, BTRFS_SEND_A_XATTR_NAME, name, name_len);
4675 ret = send_cmd(sctx);
4682 static int __process_new_xattr(int num, struct btrfs_key *di_key,
4683 const char *name, int name_len,
4684 const char *data, int data_len,
4688 struct send_ctx *sctx = ctx;
4690 struct posix_acl_xattr_header dummy_acl;
4692 /* Capabilities are emitted by finish_inode_if_needed */
4693 if (!strncmp(name, XATTR_NAME_CAPS, name_len))
4696 p = fs_path_alloc();
4701 * This hack is needed because empty acls are stored as zero byte
4702 * data in xattrs. Problem with that is, that receiving these zero byte
4703 * acls will fail later. To fix this, we send a dummy acl list that
4704 * only contains the version number and no entries.
4706 if (!strncmp(name, XATTR_NAME_POSIX_ACL_ACCESS, name_len) ||
4707 !strncmp(name, XATTR_NAME_POSIX_ACL_DEFAULT, name_len)) {
4708 if (data_len == 0) {
4709 dummy_acl.a_version =
4710 cpu_to_le32(POSIX_ACL_XATTR_VERSION);
4711 data = (char *)&dummy_acl;
4712 data_len = sizeof(dummy_acl);
4716 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
4720 ret = send_set_xattr(sctx, p, name, name_len, data, data_len);
4727 static int __process_deleted_xattr(int num, struct btrfs_key *di_key,
4728 const char *name, int name_len,
4729 const char *data, int data_len,
4733 struct send_ctx *sctx = ctx;
4736 p = fs_path_alloc();
4740 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
4744 ret = send_remove_xattr(sctx, p, name, name_len);
4751 static int process_new_xattr(struct send_ctx *sctx)
4755 ret = iterate_dir_item(sctx->send_root, sctx->left_path,
4756 __process_new_xattr, sctx);
4761 static int process_deleted_xattr(struct send_ctx *sctx)
4763 return iterate_dir_item(sctx->parent_root, sctx->right_path,
4764 __process_deleted_xattr, sctx);
4767 struct find_xattr_ctx {
4775 static int __find_xattr(int num, struct btrfs_key *di_key,
4776 const char *name, int name_len,
4777 const char *data, int data_len,
4778 u8 type, void *vctx)
4780 struct find_xattr_ctx *ctx = vctx;
4782 if (name_len == ctx->name_len &&
4783 strncmp(name, ctx->name, name_len) == 0) {
4784 ctx->found_idx = num;
4785 ctx->found_data_len = data_len;
4786 ctx->found_data = kmemdup(data, data_len, GFP_KERNEL);
4787 if (!ctx->found_data)
4794 static int find_xattr(struct btrfs_root *root,
4795 struct btrfs_path *path,
4796 struct btrfs_key *key,
4797 const char *name, int name_len,
4798 char **data, int *data_len)
4801 struct find_xattr_ctx ctx;
4804 ctx.name_len = name_len;
4806 ctx.found_data = NULL;
4807 ctx.found_data_len = 0;
4809 ret = iterate_dir_item(root, path, __find_xattr, &ctx);
4813 if (ctx.found_idx == -1)
4816 *data = ctx.found_data;
4817 *data_len = ctx.found_data_len;
4819 kfree(ctx.found_data);
4821 return ctx.found_idx;
4825 static int __process_changed_new_xattr(int num, struct btrfs_key *di_key,
4826 const char *name, int name_len,
4827 const char *data, int data_len,
4831 struct send_ctx *sctx = ctx;
4832 char *found_data = NULL;
4833 int found_data_len = 0;
4835 ret = find_xattr(sctx->parent_root, sctx->right_path,
4836 sctx->cmp_key, name, name_len, &found_data,
4838 if (ret == -ENOENT) {
4839 ret = __process_new_xattr(num, di_key, name, name_len, data,
4840 data_len, type, ctx);
4841 } else if (ret >= 0) {
4842 if (data_len != found_data_len ||
4843 memcmp(data, found_data, data_len)) {
4844 ret = __process_new_xattr(num, di_key, name, name_len,
4845 data, data_len, type, ctx);
4855 static int __process_changed_deleted_xattr(int num, struct btrfs_key *di_key,
4856 const char *name, int name_len,
4857 const char *data, int data_len,
4861 struct send_ctx *sctx = ctx;
4863 ret = find_xattr(sctx->send_root, sctx->left_path, sctx->cmp_key,
4864 name, name_len, NULL, NULL);
4866 ret = __process_deleted_xattr(num, di_key, name, name_len, data,
4867 data_len, type, ctx);
4874 static int process_changed_xattr(struct send_ctx *sctx)
4878 ret = iterate_dir_item(sctx->send_root, sctx->left_path,
4879 __process_changed_new_xattr, sctx);
4882 ret = iterate_dir_item(sctx->parent_root, sctx->right_path,
4883 __process_changed_deleted_xattr, sctx);
4889 static int process_all_new_xattrs(struct send_ctx *sctx)
4892 struct btrfs_root *root;
4893 struct btrfs_path *path;
4894 struct btrfs_key key;
4895 struct btrfs_key found_key;
4896 struct extent_buffer *eb;
4899 path = alloc_path_for_send();
4903 root = sctx->send_root;
4905 key.objectid = sctx->cmp_key->objectid;
4906 key.type = BTRFS_XATTR_ITEM_KEY;
4908 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4913 eb = path->nodes[0];
4914 slot = path->slots[0];
4915 if (slot >= btrfs_header_nritems(eb)) {
4916 ret = btrfs_next_leaf(root, path);
4919 } else if (ret > 0) {
4926 btrfs_item_key_to_cpu(eb, &found_key, slot);
4927 if (found_key.objectid != key.objectid ||
4928 found_key.type != key.type) {
4933 ret = iterate_dir_item(root, path, __process_new_xattr, sctx);
4941 btrfs_free_path(path);
4945 static ssize_t fill_read_buf(struct send_ctx *sctx, u64 offset, u32 len)
4947 struct btrfs_root *root = sctx->send_root;
4948 struct btrfs_fs_info *fs_info = root->fs_info;
4949 struct inode *inode;
4952 struct btrfs_key key;
4953 pgoff_t index = offset >> PAGE_SHIFT;
4955 unsigned pg_offset = offset_in_page(offset);
4958 key.objectid = sctx->cur_ino;
4959 key.type = BTRFS_INODE_ITEM_KEY;
4962 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
4964 return PTR_ERR(inode);
4966 if (offset + len > i_size_read(inode)) {
4967 if (offset > i_size_read(inode))
4970 len = offset - i_size_read(inode);
4975 last_index = (offset + len - 1) >> PAGE_SHIFT;
4977 /* initial readahead */
4978 memset(&sctx->ra, 0, sizeof(struct file_ra_state));
4979 file_ra_state_init(&sctx->ra, inode->i_mapping);
4981 while (index <= last_index) {
4982 unsigned cur_len = min_t(unsigned, len,
4983 PAGE_SIZE - pg_offset);
4985 page = find_lock_page(inode->i_mapping, index);
4987 page_cache_sync_readahead(inode->i_mapping, &sctx->ra,
4988 NULL, index, last_index + 1 - index);
4990 page = find_or_create_page(inode->i_mapping, index,
4998 if (PageReadahead(page)) {
4999 page_cache_async_readahead(inode->i_mapping, &sctx->ra,
5000 NULL, page, index, last_index + 1 - index);
5003 if (!PageUptodate(page)) {
5004 btrfs_readpage(NULL, page);
5006 if (!PageUptodate(page)) {
5009 "send: IO error at offset %llu for inode %llu root %llu",
5010 page_offset(page), sctx->cur_ino,
5011 sctx->send_root->root_key.objectid);
5019 memcpy(sctx->read_buf + ret, addr + pg_offset, cur_len);
5034 * Read some bytes from the current inode/file and send a write command to
5037 static int send_write(struct send_ctx *sctx, u64 offset, u32 len)
5039 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
5042 ssize_t num_read = 0;
5044 p = fs_path_alloc();
5048 btrfs_debug(fs_info, "send_write offset=%llu, len=%d", offset, len);
5050 num_read = fill_read_buf(sctx, offset, len);
5051 if (num_read <= 0) {
5057 ret = begin_cmd(sctx, BTRFS_SEND_C_WRITE);
5061 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5065 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5066 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5067 TLV_PUT(sctx, BTRFS_SEND_A_DATA, sctx->read_buf, num_read);
5069 ret = send_cmd(sctx);
5080 * Send a clone command to user space.
5082 static int send_clone(struct send_ctx *sctx,
5083 u64 offset, u32 len,
5084 struct clone_root *clone_root)
5090 btrfs_debug(sctx->send_root->fs_info,
5091 "send_clone offset=%llu, len=%d, clone_root=%llu, clone_inode=%llu, clone_offset=%llu",
5092 offset, len, clone_root->root->root_key.objectid,
5093 clone_root->ino, clone_root->offset);
5095 p = fs_path_alloc();
5099 ret = begin_cmd(sctx, BTRFS_SEND_C_CLONE);
5103 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5107 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5108 TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_LEN, len);
5109 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5111 if (clone_root->root == sctx->send_root) {
5112 ret = get_inode_info(sctx->send_root, clone_root->ino, NULL,
5113 &gen, NULL, NULL, NULL, NULL);
5116 ret = get_cur_path(sctx, clone_root->ino, gen, p);
5118 ret = get_inode_path(clone_root->root, clone_root->ino, p);
5124 * If the parent we're using has a received_uuid set then use that as
5125 * our clone source as that is what we will look for when doing a
5128 * This covers the case that we create a snapshot off of a received
5129 * subvolume and then use that as the parent and try to receive on a
5132 if (!btrfs_is_empty_uuid(clone_root->root->root_item.received_uuid))
5133 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
5134 clone_root->root->root_item.received_uuid);
5136 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
5137 clone_root->root->root_item.uuid);
5138 TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_CTRANSID,
5139 le64_to_cpu(clone_root->root->root_item.ctransid));
5140 TLV_PUT_PATH(sctx, BTRFS_SEND_A_CLONE_PATH, p);
5141 TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_OFFSET,
5142 clone_root->offset);
5144 ret = send_cmd(sctx);
5153 * Send an update extent command to user space.
5155 static int send_update_extent(struct send_ctx *sctx,
5156 u64 offset, u32 len)
5161 p = fs_path_alloc();
5165 ret = begin_cmd(sctx, BTRFS_SEND_C_UPDATE_EXTENT);
5169 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5173 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5174 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5175 TLV_PUT_U64(sctx, BTRFS_SEND_A_SIZE, len);
5177 ret = send_cmd(sctx);
5185 static int send_hole(struct send_ctx *sctx, u64 end)
5187 struct fs_path *p = NULL;
5188 u64 offset = sctx->cur_inode_last_extent;
5193 * A hole that starts at EOF or beyond it. Since we do not yet support
5194 * fallocate (for extent preallocation and hole punching), sending a
5195 * write of zeroes starting at EOF or beyond would later require issuing
5196 * a truncate operation which would undo the write and achieve nothing.
5198 if (offset >= sctx->cur_inode_size)
5202 * Don't go beyond the inode's i_size due to prealloc extents that start
5205 end = min_t(u64, end, sctx->cur_inode_size);
5207 if (sctx->flags & BTRFS_SEND_FLAG_NO_FILE_DATA)
5208 return send_update_extent(sctx, offset, end - offset);
5210 p = fs_path_alloc();
5213 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5215 goto tlv_put_failure;
5216 memset(sctx->read_buf, 0, BTRFS_SEND_READ_SIZE);
5217 while (offset < end) {
5218 len = min_t(u64, end - offset, BTRFS_SEND_READ_SIZE);
5220 ret = begin_cmd(sctx, BTRFS_SEND_C_WRITE);
5223 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5224 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5225 TLV_PUT(sctx, BTRFS_SEND_A_DATA, sctx->read_buf, len);
5226 ret = send_cmd(sctx);
5231 sctx->cur_inode_next_write_offset = offset;
5237 static int send_extent_data(struct send_ctx *sctx,
5243 if (sctx->flags & BTRFS_SEND_FLAG_NO_FILE_DATA)
5244 return send_update_extent(sctx, offset, len);
5246 while (sent < len) {
5247 u64 size = len - sent;
5250 if (size > BTRFS_SEND_READ_SIZE)
5251 size = BTRFS_SEND_READ_SIZE;
5252 ret = send_write(sctx, offset + sent, size);
5263 * Search for a capability xattr related to sctx->cur_ino. If the capability is
5264 * found, call send_set_xattr function to emit it.
5266 * Return 0 if there isn't a capability, or when the capability was emitted
5267 * successfully, or < 0 if an error occurred.
5269 static int send_capabilities(struct send_ctx *sctx)
5271 struct fs_path *fspath = NULL;
5272 struct btrfs_path *path;
5273 struct btrfs_dir_item *di;
5274 struct extent_buffer *leaf;
5275 unsigned long data_ptr;
5280 path = alloc_path_for_send();
5284 di = btrfs_lookup_xattr(NULL, sctx->send_root, path, sctx->cur_ino,
5285 XATTR_NAME_CAPS, strlen(XATTR_NAME_CAPS), 0);
5287 /* There is no xattr for this inode */
5289 } else if (IS_ERR(di)) {
5294 leaf = path->nodes[0];
5295 buf_len = btrfs_dir_data_len(leaf, di);
5297 fspath = fs_path_alloc();
5298 buf = kmalloc(buf_len, GFP_KERNEL);
5299 if (!fspath || !buf) {
5304 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, fspath);
5308 data_ptr = (unsigned long)(di + 1) + btrfs_dir_name_len(leaf, di);
5309 read_extent_buffer(leaf, buf, data_ptr, buf_len);
5311 ret = send_set_xattr(sctx, fspath, XATTR_NAME_CAPS,
5312 strlen(XATTR_NAME_CAPS), buf, buf_len);
5315 fs_path_free(fspath);
5316 btrfs_free_path(path);
5320 static int clone_range(struct send_ctx *sctx,
5321 struct clone_root *clone_root,
5322 const u64 disk_byte,
5327 struct btrfs_path *path;
5328 struct btrfs_key key;
5330 u64 clone_src_i_size = 0;
5333 * Prevent cloning from a zero offset with a length matching the sector
5334 * size because in some scenarios this will make the receiver fail.
5336 * For example, if in the source filesystem the extent at offset 0
5337 * has a length of sectorsize and it was written using direct IO, then
5338 * it can never be an inline extent (even if compression is enabled).
5339 * Then this extent can be cloned in the original filesystem to a non
5340 * zero file offset, but it may not be possible to clone in the
5341 * destination filesystem because it can be inlined due to compression
5342 * on the destination filesystem (as the receiver's write operations are
5343 * always done using buffered IO). The same happens when the original
5344 * filesystem does not have compression enabled but the destination
5347 if (clone_root->offset == 0 &&
5348 len == sctx->send_root->fs_info->sectorsize)
5349 return send_extent_data(sctx, offset, len);
5351 path = alloc_path_for_send();
5356 * There are inodes that have extents that lie behind its i_size. Don't
5357 * accept clones from these extents.
5359 ret = __get_inode_info(clone_root->root, path, clone_root->ino,
5360 &clone_src_i_size, NULL, NULL, NULL, NULL, NULL);
5361 btrfs_release_path(path);
5366 * We can't send a clone operation for the entire range if we find
5367 * extent items in the respective range in the source file that
5368 * refer to different extents or if we find holes.
5369 * So check for that and do a mix of clone and regular write/copy
5370 * operations if needed.
5374 * mkfs.btrfs -f /dev/sda
5375 * mount /dev/sda /mnt
5376 * xfs_io -f -c "pwrite -S 0xaa 0K 100K" /mnt/foo
5377 * cp --reflink=always /mnt/foo /mnt/bar
5378 * xfs_io -c "pwrite -S 0xbb 50K 50K" /mnt/foo
5379 * btrfs subvolume snapshot -r /mnt /mnt/snap
5381 * If when we send the snapshot and we are processing file bar (which
5382 * has a higher inode number than foo) we blindly send a clone operation
5383 * for the [0, 100K[ range from foo to bar, the receiver ends up getting
5384 * a file bar that matches the content of file foo - iow, doesn't match
5385 * the content from bar in the original filesystem.
5387 key.objectid = clone_root->ino;
5388 key.type = BTRFS_EXTENT_DATA_KEY;
5389 key.offset = clone_root->offset;
5390 ret = btrfs_search_slot(NULL, clone_root->root, &key, path, 0, 0);
5393 if (ret > 0 && path->slots[0] > 0) {
5394 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1);
5395 if (key.objectid == clone_root->ino &&
5396 key.type == BTRFS_EXTENT_DATA_KEY)
5401 struct extent_buffer *leaf = path->nodes[0];
5402 int slot = path->slots[0];
5403 struct btrfs_file_extent_item *ei;
5407 u64 clone_data_offset;
5408 bool crossed_src_i_size = false;
5410 if (slot >= btrfs_header_nritems(leaf)) {
5411 ret = btrfs_next_leaf(clone_root->root, path);
5419 btrfs_item_key_to_cpu(leaf, &key, slot);
5422 * We might have an implicit trailing hole (NO_HOLES feature
5423 * enabled). We deal with it after leaving this loop.
5425 if (key.objectid != clone_root->ino ||
5426 key.type != BTRFS_EXTENT_DATA_KEY)
5429 ei = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5430 type = btrfs_file_extent_type(leaf, ei);
5431 if (type == BTRFS_FILE_EXTENT_INLINE) {
5432 ext_len = btrfs_file_extent_ram_bytes(leaf, ei);
5433 ext_len = PAGE_ALIGN(ext_len);
5435 ext_len = btrfs_file_extent_num_bytes(leaf, ei);
5438 if (key.offset + ext_len <= clone_root->offset)
5441 if (key.offset > clone_root->offset) {
5442 /* Implicit hole, NO_HOLES feature enabled. */
5443 u64 hole_len = key.offset - clone_root->offset;
5447 ret = send_extent_data(sctx, offset, hole_len);
5455 clone_root->offset += hole_len;
5456 data_offset += hole_len;
5459 if (key.offset >= clone_root->offset + len)
5462 if (key.offset >= clone_src_i_size)
5465 if (key.offset + ext_len > clone_src_i_size) {
5466 ext_len = clone_src_i_size - key.offset;
5467 crossed_src_i_size = true;
5470 clone_data_offset = btrfs_file_extent_offset(leaf, ei);
5471 if (btrfs_file_extent_disk_bytenr(leaf, ei) == disk_byte) {
5472 clone_root->offset = key.offset;
5473 if (clone_data_offset < data_offset &&
5474 clone_data_offset + ext_len > data_offset) {
5477 extent_offset = data_offset - clone_data_offset;
5478 ext_len -= extent_offset;
5479 clone_data_offset += extent_offset;
5480 clone_root->offset += extent_offset;
5484 clone_len = min_t(u64, ext_len, len);
5486 if (btrfs_file_extent_disk_bytenr(leaf, ei) == disk_byte &&
5487 clone_data_offset == data_offset) {
5488 const u64 src_end = clone_root->offset + clone_len;
5489 const u64 sectorsize = SZ_64K;
5492 * We can't clone the last block, when its size is not
5493 * sector size aligned, into the middle of a file. If we
5494 * do so, the receiver will get a failure (-EINVAL) when
5495 * trying to clone or will silently corrupt the data in
5496 * the destination file if it's on a kernel without the
5497 * fix introduced by commit ac765f83f1397646
5498 * ("Btrfs: fix data corruption due to cloning of eof
5501 * So issue a clone of the aligned down range plus a
5502 * regular write for the eof block, if we hit that case.
5504 * Also, we use the maximum possible sector size, 64K,
5505 * because we don't know what's the sector size of the
5506 * filesystem that receives the stream, so we have to
5507 * assume the largest possible sector size.
5509 if (src_end == clone_src_i_size &&
5510 !IS_ALIGNED(src_end, sectorsize) &&
5511 offset + clone_len < sctx->cur_inode_size) {
5514 slen = ALIGN_DOWN(src_end - clone_root->offset,
5517 ret = send_clone(sctx, offset, slen,
5522 ret = send_extent_data(sctx, offset + slen,
5525 ret = send_clone(sctx, offset, clone_len,
5528 } else if (crossed_src_i_size && clone_len < len) {
5530 * If we are at i_size of the clone source inode and we
5531 * can not clone from it, terminate the loop. This is
5532 * to avoid sending two write operations, one with a
5533 * length matching clone_len and the final one after
5534 * this loop with a length of len - clone_len.
5536 * When using encoded writes (BTRFS_SEND_FLAG_COMPRESSED
5537 * was passed to the send ioctl), this helps avoid
5538 * sending an encoded write for an offset that is not
5539 * sector size aligned, in case the i_size of the source
5540 * inode is not sector size aligned. That will make the
5541 * receiver fallback to decompression of the data and
5542 * writing it using regular buffered IO, therefore while
5543 * not incorrect, it's not optimal due decompression and
5544 * possible re-compression at the receiver.
5548 ret = send_extent_data(sctx, offset, clone_len);
5557 offset += clone_len;
5558 clone_root->offset += clone_len;
5561 * If we are cloning from the file we are currently processing,
5562 * and using the send root as the clone root, we must stop once
5563 * the current clone offset reaches the current eof of the file
5564 * at the receiver, otherwise we would issue an invalid clone
5565 * operation (source range going beyond eof) and cause the
5566 * receiver to fail. So if we reach the current eof, bail out
5567 * and fallback to a regular write.
5569 if (clone_root->root == sctx->send_root &&
5570 clone_root->ino == sctx->cur_ino &&
5571 clone_root->offset >= sctx->cur_inode_next_write_offset)
5574 data_offset += clone_len;
5580 ret = send_extent_data(sctx, offset, len);
5584 btrfs_free_path(path);
5588 static int send_write_or_clone(struct send_ctx *sctx,
5589 struct btrfs_path *path,
5590 struct btrfs_key *key,
5591 struct clone_root *clone_root)
5594 struct btrfs_file_extent_item *ei;
5595 u64 offset = key->offset;
5598 u64 bs = sctx->send_root->fs_info->sb->s_blocksize;
5600 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
5601 struct btrfs_file_extent_item);
5602 type = btrfs_file_extent_type(path->nodes[0], ei);
5603 if (type == BTRFS_FILE_EXTENT_INLINE) {
5604 len = btrfs_file_extent_ram_bytes(path->nodes[0], ei);
5606 * it is possible the inline item won't cover the whole page,
5607 * but there may be items after this page. Make
5608 * sure to send the whole thing
5610 len = PAGE_ALIGN(len);
5612 len = btrfs_file_extent_num_bytes(path->nodes[0], ei);
5615 if (offset >= sctx->cur_inode_size) {
5619 if (offset + len > sctx->cur_inode_size)
5620 len = sctx->cur_inode_size - offset;
5626 if (clone_root && IS_ALIGNED(offset + len, bs)) {
5630 disk_byte = btrfs_file_extent_disk_bytenr(path->nodes[0], ei);
5631 data_offset = btrfs_file_extent_offset(path->nodes[0], ei);
5632 ret = clone_range(sctx, clone_root, disk_byte, data_offset,
5635 ret = send_extent_data(sctx, offset, len);
5637 sctx->cur_inode_next_write_offset = offset + len;
5642 static int is_extent_unchanged(struct send_ctx *sctx,
5643 struct btrfs_path *left_path,
5644 struct btrfs_key *ekey)
5647 struct btrfs_key key;
5648 struct btrfs_path *path = NULL;
5649 struct extent_buffer *eb;
5651 struct btrfs_key found_key;
5652 struct btrfs_file_extent_item *ei;
5657 u64 left_offset_fixed;
5665 path = alloc_path_for_send();
5669 eb = left_path->nodes[0];
5670 slot = left_path->slots[0];
5671 ei = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
5672 left_type = btrfs_file_extent_type(eb, ei);
5674 if (left_type != BTRFS_FILE_EXTENT_REG) {
5678 left_disknr = btrfs_file_extent_disk_bytenr(eb, ei);
5679 left_len = btrfs_file_extent_num_bytes(eb, ei);
5680 left_offset = btrfs_file_extent_offset(eb, ei);
5681 left_gen = btrfs_file_extent_generation(eb, ei);
5684 * Following comments will refer to these graphics. L is the left
5685 * extents which we are checking at the moment. 1-8 are the right
5686 * extents that we iterate.
5689 * |-1-|-2a-|-3-|-4-|-5-|-6-|
5692 * |--1--|-2b-|...(same as above)
5694 * Alternative situation. Happens on files where extents got split.
5696 * |-----------7-----------|-6-|
5698 * Alternative situation. Happens on files which got larger.
5701 * Nothing follows after 8.
5704 key.objectid = ekey->objectid;
5705 key.type = BTRFS_EXTENT_DATA_KEY;
5706 key.offset = ekey->offset;
5707 ret = btrfs_search_slot_for_read(sctx->parent_root, &key, path, 0, 0);
5716 * Handle special case where the right side has no extents at all.
5718 eb = path->nodes[0];
5719 slot = path->slots[0];
5720 btrfs_item_key_to_cpu(eb, &found_key, slot);
5721 if (found_key.objectid != key.objectid ||
5722 found_key.type != key.type) {
5723 /* If we're a hole then just pretend nothing changed */
5724 ret = (left_disknr) ? 0 : 1;
5729 * We're now on 2a, 2b or 7.
5732 while (key.offset < ekey->offset + left_len) {
5733 ei = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
5734 right_type = btrfs_file_extent_type(eb, ei);
5735 if (right_type != BTRFS_FILE_EXTENT_REG &&
5736 right_type != BTRFS_FILE_EXTENT_INLINE) {
5741 if (right_type == BTRFS_FILE_EXTENT_INLINE) {
5742 right_len = btrfs_file_extent_ram_bytes(eb, ei);
5743 right_len = PAGE_ALIGN(right_len);
5745 right_len = btrfs_file_extent_num_bytes(eb, ei);
5749 * Are we at extent 8? If yes, we know the extent is changed.
5750 * This may only happen on the first iteration.
5752 if (found_key.offset + right_len <= ekey->offset) {
5753 /* If we're a hole just pretend nothing changed */
5754 ret = (left_disknr) ? 0 : 1;
5759 * We just wanted to see if when we have an inline extent, what
5760 * follows it is a regular extent (wanted to check the above
5761 * condition for inline extents too). This should normally not
5762 * happen but it's possible for example when we have an inline
5763 * compressed extent representing data with a size matching
5764 * the page size (currently the same as sector size).
5766 if (right_type == BTRFS_FILE_EXTENT_INLINE) {
5771 right_disknr = btrfs_file_extent_disk_bytenr(eb, ei);
5772 right_offset = btrfs_file_extent_offset(eb, ei);
5773 right_gen = btrfs_file_extent_generation(eb, ei);
5775 left_offset_fixed = left_offset;
5776 if (key.offset < ekey->offset) {
5777 /* Fix the right offset for 2a and 7. */
5778 right_offset += ekey->offset - key.offset;
5780 /* Fix the left offset for all behind 2a and 2b */
5781 left_offset_fixed += key.offset - ekey->offset;
5785 * Check if we have the same extent.
5787 if (left_disknr != right_disknr ||
5788 left_offset_fixed != right_offset ||
5789 left_gen != right_gen) {
5795 * Go to the next extent.
5797 ret = btrfs_next_item(sctx->parent_root, path);
5801 eb = path->nodes[0];
5802 slot = path->slots[0];
5803 btrfs_item_key_to_cpu(eb, &found_key, slot);
5805 if (ret || found_key.objectid != key.objectid ||
5806 found_key.type != key.type) {
5807 key.offset += right_len;
5810 if (found_key.offset != key.offset + right_len) {
5818 * We're now behind the left extent (treat as unchanged) or at the end
5819 * of the right side (treat as changed).
5821 if (key.offset >= ekey->offset + left_len)
5828 btrfs_free_path(path);
5832 static int get_last_extent(struct send_ctx *sctx, u64 offset)
5834 struct btrfs_path *path;
5835 struct btrfs_root *root = sctx->send_root;
5836 struct btrfs_file_extent_item *fi;
5837 struct btrfs_key key;
5842 path = alloc_path_for_send();
5846 sctx->cur_inode_last_extent = 0;
5848 key.objectid = sctx->cur_ino;
5849 key.type = BTRFS_EXTENT_DATA_KEY;
5850 key.offset = offset;
5851 ret = btrfs_search_slot_for_read(root, &key, path, 0, 1);
5855 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
5856 if (key.objectid != sctx->cur_ino || key.type != BTRFS_EXTENT_DATA_KEY)
5859 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
5860 struct btrfs_file_extent_item);
5861 type = btrfs_file_extent_type(path->nodes[0], fi);
5862 if (type == BTRFS_FILE_EXTENT_INLINE) {
5863 u64 size = btrfs_file_extent_ram_bytes(path->nodes[0], fi);
5864 extent_end = ALIGN(key.offset + size,
5865 sctx->send_root->fs_info->sectorsize);
5867 extent_end = key.offset +
5868 btrfs_file_extent_num_bytes(path->nodes[0], fi);
5870 sctx->cur_inode_last_extent = extent_end;
5872 btrfs_free_path(path);
5876 static int range_is_hole_in_parent(struct send_ctx *sctx,
5880 struct btrfs_path *path;
5881 struct btrfs_key key;
5882 struct btrfs_root *root = sctx->parent_root;
5883 u64 search_start = start;
5886 path = alloc_path_for_send();
5890 key.objectid = sctx->cur_ino;
5891 key.type = BTRFS_EXTENT_DATA_KEY;
5892 key.offset = search_start;
5893 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5896 if (ret > 0 && path->slots[0] > 0)
5899 while (search_start < end) {
5900 struct extent_buffer *leaf = path->nodes[0];
5901 int slot = path->slots[0];
5902 struct btrfs_file_extent_item *fi;
5905 if (slot >= btrfs_header_nritems(leaf)) {
5906 ret = btrfs_next_leaf(root, path);
5914 btrfs_item_key_to_cpu(leaf, &key, slot);
5915 if (key.objectid < sctx->cur_ino ||
5916 key.type < BTRFS_EXTENT_DATA_KEY)
5918 if (key.objectid > sctx->cur_ino ||
5919 key.type > BTRFS_EXTENT_DATA_KEY ||
5923 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5924 if (btrfs_file_extent_type(leaf, fi) ==
5925 BTRFS_FILE_EXTENT_INLINE) {
5926 u64 size = btrfs_file_extent_ram_bytes(leaf, fi);
5928 extent_end = ALIGN(key.offset + size,
5929 root->fs_info->sectorsize);
5931 extent_end = key.offset +
5932 btrfs_file_extent_num_bytes(leaf, fi);
5934 if (extent_end <= start)
5936 if (btrfs_file_extent_disk_bytenr(leaf, fi) == 0) {
5937 search_start = extent_end;
5947 btrfs_free_path(path);
5951 static int maybe_send_hole(struct send_ctx *sctx, struct btrfs_path *path,
5952 struct btrfs_key *key)
5954 struct btrfs_file_extent_item *fi;
5959 if (sctx->cur_ino != key->objectid || !need_send_hole(sctx))
5962 if (sctx->cur_inode_last_extent == (u64)-1) {
5963 ret = get_last_extent(sctx, key->offset - 1);
5968 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
5969 struct btrfs_file_extent_item);
5970 type = btrfs_file_extent_type(path->nodes[0], fi);
5971 if (type == BTRFS_FILE_EXTENT_INLINE) {
5972 u64 size = btrfs_file_extent_ram_bytes(path->nodes[0], fi);
5973 extent_end = ALIGN(key->offset + size,
5974 sctx->send_root->fs_info->sectorsize);
5976 extent_end = key->offset +
5977 btrfs_file_extent_num_bytes(path->nodes[0], fi);
5980 if (path->slots[0] == 0 &&
5981 sctx->cur_inode_last_extent < key->offset) {
5983 * We might have skipped entire leafs that contained only
5984 * file extent items for our current inode. These leafs have
5985 * a generation number smaller (older) than the one in the
5986 * current leaf and the leaf our last extent came from, and
5987 * are located between these 2 leafs.
5989 ret = get_last_extent(sctx, key->offset - 1);
5994 if (sctx->cur_inode_last_extent < key->offset) {
5995 ret = range_is_hole_in_parent(sctx,
5996 sctx->cur_inode_last_extent,
6001 ret = send_hole(sctx, key->offset);
6005 sctx->cur_inode_last_extent = extent_end;
6009 static int process_extent(struct send_ctx *sctx,
6010 struct btrfs_path *path,
6011 struct btrfs_key *key)
6013 struct clone_root *found_clone = NULL;
6016 if (S_ISLNK(sctx->cur_inode_mode))
6019 if (sctx->parent_root && !sctx->cur_inode_new) {
6020 ret = is_extent_unchanged(sctx, path, key);
6028 struct btrfs_file_extent_item *ei;
6031 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
6032 struct btrfs_file_extent_item);
6033 type = btrfs_file_extent_type(path->nodes[0], ei);
6034 if (type == BTRFS_FILE_EXTENT_PREALLOC ||
6035 type == BTRFS_FILE_EXTENT_REG) {
6037 * The send spec does not have a prealloc command yet,
6038 * so just leave a hole for prealloc'ed extents until
6039 * we have enough commands queued up to justify rev'ing
6042 if (type == BTRFS_FILE_EXTENT_PREALLOC) {
6047 /* Have a hole, just skip it. */
6048 if (btrfs_file_extent_disk_bytenr(path->nodes[0], ei) == 0) {
6055 ret = find_extent_clone(sctx, path, key->objectid, key->offset,
6056 sctx->cur_inode_size, &found_clone);
6057 if (ret != -ENOENT && ret < 0)
6060 ret = send_write_or_clone(sctx, path, key, found_clone);
6064 ret = maybe_send_hole(sctx, path, key);
6069 static int process_all_extents(struct send_ctx *sctx)
6072 struct btrfs_root *root;
6073 struct btrfs_path *path;
6074 struct btrfs_key key;
6075 struct btrfs_key found_key;
6076 struct extent_buffer *eb;
6079 root = sctx->send_root;
6080 path = alloc_path_for_send();
6084 key.objectid = sctx->cmp_key->objectid;
6085 key.type = BTRFS_EXTENT_DATA_KEY;
6087 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6092 eb = path->nodes[0];
6093 slot = path->slots[0];
6095 if (slot >= btrfs_header_nritems(eb)) {
6096 ret = btrfs_next_leaf(root, path);
6099 } else if (ret > 0) {
6106 btrfs_item_key_to_cpu(eb, &found_key, slot);
6108 if (found_key.objectid != key.objectid ||
6109 found_key.type != key.type) {
6114 ret = process_extent(sctx, path, &found_key);
6122 btrfs_free_path(path);
6126 static int process_recorded_refs_if_needed(struct send_ctx *sctx, int at_end,
6128 int *refs_processed)
6132 if (sctx->cur_ino == 0)
6134 if (!at_end && sctx->cur_ino == sctx->cmp_key->objectid &&
6135 sctx->cmp_key->type <= BTRFS_INODE_EXTREF_KEY)
6137 if (list_empty(&sctx->new_refs) && list_empty(&sctx->deleted_refs))
6140 ret = process_recorded_refs(sctx, pending_move);
6144 *refs_processed = 1;
6149 static int finish_inode_if_needed(struct send_ctx *sctx, int at_end)
6160 int need_truncate = 1;
6161 int pending_move = 0;
6162 int refs_processed = 0;
6164 if (sctx->ignore_cur_inode)
6167 ret = process_recorded_refs_if_needed(sctx, at_end, &pending_move,
6173 * We have processed the refs and thus need to advance send_progress.
6174 * Now, calls to get_cur_xxx will take the updated refs of the current
6175 * inode into account.
6177 * On the other hand, if our current inode is a directory and couldn't
6178 * be moved/renamed because its parent was renamed/moved too and it has
6179 * a higher inode number, we can only move/rename our current inode
6180 * after we moved/renamed its parent. Therefore in this case operate on
6181 * the old path (pre move/rename) of our current inode, and the
6182 * move/rename will be performed later.
6184 if (refs_processed && !pending_move)
6185 sctx->send_progress = sctx->cur_ino + 1;
6187 if (sctx->cur_ino == 0 || sctx->cur_inode_deleted)
6189 if (!at_end && sctx->cmp_key->objectid == sctx->cur_ino)
6192 ret = get_inode_info(sctx->send_root, sctx->cur_ino, NULL, NULL,
6193 &left_mode, &left_uid, &left_gid, NULL);
6197 if (!sctx->parent_root || sctx->cur_inode_new) {
6199 if (!S_ISLNK(sctx->cur_inode_mode))
6201 if (sctx->cur_inode_next_write_offset == sctx->cur_inode_size)
6206 ret = get_inode_info(sctx->parent_root, sctx->cur_ino,
6207 &old_size, NULL, &right_mode, &right_uid,
6212 if (left_uid != right_uid || left_gid != right_gid)
6214 if (!S_ISLNK(sctx->cur_inode_mode) && left_mode != right_mode)
6216 if ((old_size == sctx->cur_inode_size) ||
6217 (sctx->cur_inode_size > old_size &&
6218 sctx->cur_inode_next_write_offset == sctx->cur_inode_size))
6222 if (S_ISREG(sctx->cur_inode_mode)) {
6223 if (need_send_hole(sctx)) {
6224 if (sctx->cur_inode_last_extent == (u64)-1 ||
6225 sctx->cur_inode_last_extent <
6226 sctx->cur_inode_size) {
6227 ret = get_last_extent(sctx, (u64)-1);
6231 if (sctx->cur_inode_last_extent <
6232 sctx->cur_inode_size) {
6233 ret = send_hole(sctx, sctx->cur_inode_size);
6238 if (need_truncate) {
6239 ret = send_truncate(sctx, sctx->cur_ino,
6240 sctx->cur_inode_gen,
6241 sctx->cur_inode_size);
6248 ret = send_chown(sctx, sctx->cur_ino, sctx->cur_inode_gen,
6249 left_uid, left_gid);
6254 ret = send_chmod(sctx, sctx->cur_ino, sctx->cur_inode_gen,
6260 ret = send_capabilities(sctx);
6265 * If other directory inodes depended on our current directory
6266 * inode's move/rename, now do their move/rename operations.
6268 if (!is_waiting_for_move(sctx, sctx->cur_ino)) {
6269 ret = apply_children_dir_moves(sctx);
6273 * Need to send that every time, no matter if it actually
6274 * changed between the two trees as we have done changes to
6275 * the inode before. If our inode is a directory and it's
6276 * waiting to be moved/renamed, we will send its utimes when
6277 * it's moved/renamed, therefore we don't need to do it here.
6279 sctx->send_progress = sctx->cur_ino + 1;
6280 ret = send_utimes(sctx, sctx->cur_ino, sctx->cur_inode_gen);
6289 struct parent_paths_ctx {
6290 struct list_head *refs;
6291 struct send_ctx *sctx;
6294 static int record_parent_ref(int num, u64 dir, int index, struct fs_path *name,
6297 struct parent_paths_ctx *ppctx = ctx;
6299 return record_ref(ppctx->sctx->parent_root, dir, name, ppctx->sctx,
6304 * Issue unlink operations for all paths of the current inode found in the
6307 static int btrfs_unlink_all_paths(struct send_ctx *sctx)
6309 LIST_HEAD(deleted_refs);
6310 struct btrfs_path *path;
6311 struct btrfs_key key;
6312 struct parent_paths_ctx ctx;
6315 path = alloc_path_for_send();
6319 key.objectid = sctx->cur_ino;
6320 key.type = BTRFS_INODE_REF_KEY;
6322 ret = btrfs_search_slot(NULL, sctx->parent_root, &key, path, 0, 0);
6326 ctx.refs = &deleted_refs;
6330 struct extent_buffer *eb = path->nodes[0];
6331 int slot = path->slots[0];
6333 if (slot >= btrfs_header_nritems(eb)) {
6334 ret = btrfs_next_leaf(sctx->parent_root, path);
6342 btrfs_item_key_to_cpu(eb, &key, slot);
6343 if (key.objectid != sctx->cur_ino)
6345 if (key.type != BTRFS_INODE_REF_KEY &&
6346 key.type != BTRFS_INODE_EXTREF_KEY)
6349 ret = iterate_inode_ref(sctx->parent_root, path, &key, 1,
6350 record_parent_ref, &ctx);
6357 while (!list_empty(&deleted_refs)) {
6358 struct recorded_ref *ref;
6360 ref = list_first_entry(&deleted_refs, struct recorded_ref, list);
6361 ret = send_unlink(sctx, ref->full_path);
6364 fs_path_free(ref->full_path);
6365 list_del(&ref->list);
6370 btrfs_free_path(path);
6372 __free_recorded_refs(&deleted_refs);
6376 static int changed_inode(struct send_ctx *sctx,
6377 enum btrfs_compare_tree_result result)
6380 struct btrfs_key *key = sctx->cmp_key;
6381 struct btrfs_inode_item *left_ii = NULL;
6382 struct btrfs_inode_item *right_ii = NULL;
6386 sctx->cur_ino = key->objectid;
6387 sctx->cur_inode_new_gen = 0;
6388 sctx->cur_inode_last_extent = (u64)-1;
6389 sctx->cur_inode_next_write_offset = 0;
6390 sctx->ignore_cur_inode = false;
6393 * Set send_progress to current inode. This will tell all get_cur_xxx
6394 * functions that the current inode's refs are not updated yet. Later,
6395 * when process_recorded_refs is finished, it is set to cur_ino + 1.
6397 sctx->send_progress = sctx->cur_ino;
6399 if (result == BTRFS_COMPARE_TREE_NEW ||
6400 result == BTRFS_COMPARE_TREE_CHANGED) {
6401 left_ii = btrfs_item_ptr(sctx->left_path->nodes[0],
6402 sctx->left_path->slots[0],
6403 struct btrfs_inode_item);
6404 left_gen = btrfs_inode_generation(sctx->left_path->nodes[0],
6407 right_ii = btrfs_item_ptr(sctx->right_path->nodes[0],
6408 sctx->right_path->slots[0],
6409 struct btrfs_inode_item);
6410 right_gen = btrfs_inode_generation(sctx->right_path->nodes[0],
6413 if (result == BTRFS_COMPARE_TREE_CHANGED) {
6414 right_ii = btrfs_item_ptr(sctx->right_path->nodes[0],
6415 sctx->right_path->slots[0],
6416 struct btrfs_inode_item);
6418 right_gen = btrfs_inode_generation(sctx->right_path->nodes[0],
6422 * The cur_ino = root dir case is special here. We can't treat
6423 * the inode as deleted+reused because it would generate a
6424 * stream that tries to delete/mkdir the root dir.
6426 if (left_gen != right_gen &&
6427 sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID)
6428 sctx->cur_inode_new_gen = 1;
6432 * Normally we do not find inodes with a link count of zero (orphans)
6433 * because the most common case is to create a snapshot and use it
6434 * for a send operation. However other less common use cases involve
6435 * using a subvolume and send it after turning it to RO mode just
6436 * after deleting all hard links of a file while holding an open
6437 * file descriptor against it or turning a RO snapshot into RW mode,
6438 * keep an open file descriptor against a file, delete it and then
6439 * turn the snapshot back to RO mode before using it for a send
6440 * operation. So if we find such cases, ignore the inode and all its
6441 * items completely if it's a new inode, or if it's a changed inode
6442 * make sure all its previous paths (from the parent snapshot) are all
6443 * unlinked and all other the inode items are ignored.
6445 if (result == BTRFS_COMPARE_TREE_NEW ||
6446 result == BTRFS_COMPARE_TREE_CHANGED) {
6449 nlinks = btrfs_inode_nlink(sctx->left_path->nodes[0], left_ii);
6451 sctx->ignore_cur_inode = true;
6452 if (result == BTRFS_COMPARE_TREE_CHANGED)
6453 ret = btrfs_unlink_all_paths(sctx);
6458 if (result == BTRFS_COMPARE_TREE_NEW) {
6459 sctx->cur_inode_gen = left_gen;
6460 sctx->cur_inode_new = 1;
6461 sctx->cur_inode_deleted = 0;
6462 sctx->cur_inode_size = btrfs_inode_size(
6463 sctx->left_path->nodes[0], left_ii);
6464 sctx->cur_inode_mode = btrfs_inode_mode(
6465 sctx->left_path->nodes[0], left_ii);
6466 sctx->cur_inode_rdev = btrfs_inode_rdev(
6467 sctx->left_path->nodes[0], left_ii);
6468 if (sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID)
6469 ret = send_create_inode_if_needed(sctx);
6470 } else if (result == BTRFS_COMPARE_TREE_DELETED) {
6471 sctx->cur_inode_gen = right_gen;
6472 sctx->cur_inode_new = 0;
6473 sctx->cur_inode_deleted = 1;
6474 sctx->cur_inode_size = btrfs_inode_size(
6475 sctx->right_path->nodes[0], right_ii);
6476 sctx->cur_inode_mode = btrfs_inode_mode(
6477 sctx->right_path->nodes[0], right_ii);
6478 } else if (result == BTRFS_COMPARE_TREE_CHANGED) {
6480 * We need to do some special handling in case the inode was
6481 * reported as changed with a changed generation number. This
6482 * means that the original inode was deleted and new inode
6483 * reused the same inum. So we have to treat the old inode as
6484 * deleted and the new one as new.
6486 if (sctx->cur_inode_new_gen) {
6488 * First, process the inode as if it was deleted.
6490 sctx->cur_inode_gen = right_gen;
6491 sctx->cur_inode_new = 0;
6492 sctx->cur_inode_deleted = 1;
6493 sctx->cur_inode_size = btrfs_inode_size(
6494 sctx->right_path->nodes[0], right_ii);
6495 sctx->cur_inode_mode = btrfs_inode_mode(
6496 sctx->right_path->nodes[0], right_ii);
6497 ret = process_all_refs(sctx,
6498 BTRFS_COMPARE_TREE_DELETED);
6503 * Now process the inode as if it was new.
6505 sctx->cur_inode_gen = left_gen;
6506 sctx->cur_inode_new = 1;
6507 sctx->cur_inode_deleted = 0;
6508 sctx->cur_inode_size = btrfs_inode_size(
6509 sctx->left_path->nodes[0], left_ii);
6510 sctx->cur_inode_mode = btrfs_inode_mode(
6511 sctx->left_path->nodes[0], left_ii);
6512 sctx->cur_inode_rdev = btrfs_inode_rdev(
6513 sctx->left_path->nodes[0], left_ii);
6514 ret = send_create_inode_if_needed(sctx);
6518 ret = process_all_refs(sctx, BTRFS_COMPARE_TREE_NEW);
6522 * Advance send_progress now as we did not get into
6523 * process_recorded_refs_if_needed in the new_gen case.
6525 sctx->send_progress = sctx->cur_ino + 1;
6528 * Now process all extents and xattrs of the inode as if
6529 * they were all new.
6531 ret = process_all_extents(sctx);
6534 ret = process_all_new_xattrs(sctx);
6538 sctx->cur_inode_gen = left_gen;
6539 sctx->cur_inode_new = 0;
6540 sctx->cur_inode_new_gen = 0;
6541 sctx->cur_inode_deleted = 0;
6542 sctx->cur_inode_size = btrfs_inode_size(
6543 sctx->left_path->nodes[0], left_ii);
6544 sctx->cur_inode_mode = btrfs_inode_mode(
6545 sctx->left_path->nodes[0], left_ii);
6554 * We have to process new refs before deleted refs, but compare_trees gives us
6555 * the new and deleted refs mixed. To fix this, we record the new/deleted refs
6556 * first and later process them in process_recorded_refs.
6557 * For the cur_inode_new_gen case, we skip recording completely because
6558 * changed_inode did already initiate processing of refs. The reason for this is
6559 * that in this case, compare_tree actually compares the refs of 2 different
6560 * inodes. To fix this, process_all_refs is used in changed_inode to handle all
6561 * refs of the right tree as deleted and all refs of the left tree as new.
6563 static int changed_ref(struct send_ctx *sctx,
6564 enum btrfs_compare_tree_result result)
6568 if (sctx->cur_ino != sctx->cmp_key->objectid) {
6569 inconsistent_snapshot_error(sctx, result, "reference");
6573 if (!sctx->cur_inode_new_gen &&
6574 sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID) {
6575 if (result == BTRFS_COMPARE_TREE_NEW)
6576 ret = record_new_ref(sctx);
6577 else if (result == BTRFS_COMPARE_TREE_DELETED)
6578 ret = record_deleted_ref(sctx);
6579 else if (result == BTRFS_COMPARE_TREE_CHANGED)
6580 ret = record_changed_ref(sctx);
6587 * Process new/deleted/changed xattrs. We skip processing in the
6588 * cur_inode_new_gen case because changed_inode did already initiate processing
6589 * of xattrs. The reason is the same as in changed_ref
6591 static int changed_xattr(struct send_ctx *sctx,
6592 enum btrfs_compare_tree_result result)
6596 if (sctx->cur_ino != sctx->cmp_key->objectid) {
6597 inconsistent_snapshot_error(sctx, result, "xattr");
6601 if (!sctx->cur_inode_new_gen && !sctx->cur_inode_deleted) {
6602 if (result == BTRFS_COMPARE_TREE_NEW)
6603 ret = process_new_xattr(sctx);
6604 else if (result == BTRFS_COMPARE_TREE_DELETED)
6605 ret = process_deleted_xattr(sctx);
6606 else if (result == BTRFS_COMPARE_TREE_CHANGED)
6607 ret = process_changed_xattr(sctx);
6614 * Process new/deleted/changed extents. We skip processing in the
6615 * cur_inode_new_gen case because changed_inode did already initiate processing
6616 * of extents. The reason is the same as in changed_ref
6618 static int changed_extent(struct send_ctx *sctx,
6619 enum btrfs_compare_tree_result result)
6624 * We have found an extent item that changed without the inode item
6625 * having changed. This can happen either after relocation (where the
6626 * disk_bytenr of an extent item is replaced at
6627 * relocation.c:replace_file_extents()) or after deduplication into a
6628 * file in both the parent and send snapshots (where an extent item can
6629 * get modified or replaced with a new one). Note that deduplication
6630 * updates the inode item, but it only changes the iversion (sequence
6631 * field in the inode item) of the inode, so if a file is deduplicated
6632 * the same amount of times in both the parent and send snapshots, its
6633 * iversion becames the same in both snapshots, whence the inode item is
6634 * the same on both snapshots.
6636 if (sctx->cur_ino != sctx->cmp_key->objectid)
6639 if (!sctx->cur_inode_new_gen && !sctx->cur_inode_deleted) {
6640 if (result != BTRFS_COMPARE_TREE_DELETED)
6641 ret = process_extent(sctx, sctx->left_path,
6648 static int dir_changed(struct send_ctx *sctx, u64 dir)
6650 u64 orig_gen, new_gen;
6653 ret = get_inode_info(sctx->send_root, dir, NULL, &new_gen, NULL, NULL,
6658 ret = get_inode_info(sctx->parent_root, dir, NULL, &orig_gen, NULL,
6663 return (orig_gen != new_gen) ? 1 : 0;
6666 static int compare_refs(struct send_ctx *sctx, struct btrfs_path *path,
6667 struct btrfs_key *key)
6669 struct btrfs_inode_extref *extref;
6670 struct extent_buffer *leaf;
6671 u64 dirid = 0, last_dirid = 0;
6678 /* Easy case, just check this one dirid */
6679 if (key->type == BTRFS_INODE_REF_KEY) {
6680 dirid = key->offset;
6682 ret = dir_changed(sctx, dirid);
6686 leaf = path->nodes[0];
6687 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
6688 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
6689 while (cur_offset < item_size) {
6690 extref = (struct btrfs_inode_extref *)(ptr +
6692 dirid = btrfs_inode_extref_parent(leaf, extref);
6693 ref_name_len = btrfs_inode_extref_name_len(leaf, extref);
6694 cur_offset += ref_name_len + sizeof(*extref);
6695 if (dirid == last_dirid)
6697 ret = dir_changed(sctx, dirid);
6707 * Updates compare related fields in sctx and simply forwards to the actual
6708 * changed_xxx functions.
6710 static int changed_cb(struct btrfs_path *left_path,
6711 struct btrfs_path *right_path,
6712 struct btrfs_key *key,
6713 enum btrfs_compare_tree_result result,
6717 struct send_ctx *sctx = ctx;
6719 if (result == BTRFS_COMPARE_TREE_SAME) {
6720 if (key->type == BTRFS_INODE_REF_KEY ||
6721 key->type == BTRFS_INODE_EXTREF_KEY) {
6722 ret = compare_refs(sctx, left_path, key);
6727 } else if (key->type == BTRFS_EXTENT_DATA_KEY) {
6728 return maybe_send_hole(sctx, left_path, key);
6732 result = BTRFS_COMPARE_TREE_CHANGED;
6736 sctx->left_path = left_path;
6737 sctx->right_path = right_path;
6738 sctx->cmp_key = key;
6740 ret = finish_inode_if_needed(sctx, 0);
6744 /* Ignore non-FS objects */
6745 if (key->objectid == BTRFS_FREE_INO_OBJECTID ||
6746 key->objectid == BTRFS_FREE_SPACE_OBJECTID)
6749 if (key->type == BTRFS_INODE_ITEM_KEY) {
6750 ret = changed_inode(sctx, result);
6751 } else if (!sctx->ignore_cur_inode) {
6752 if (key->type == BTRFS_INODE_REF_KEY ||
6753 key->type == BTRFS_INODE_EXTREF_KEY)
6754 ret = changed_ref(sctx, result);
6755 else if (key->type == BTRFS_XATTR_ITEM_KEY)
6756 ret = changed_xattr(sctx, result);
6757 else if (key->type == BTRFS_EXTENT_DATA_KEY)
6758 ret = changed_extent(sctx, result);
6765 static int full_send_tree(struct send_ctx *sctx)
6768 struct btrfs_root *send_root = sctx->send_root;
6769 struct btrfs_key key;
6770 struct btrfs_path *path;
6771 struct extent_buffer *eb;
6774 path = alloc_path_for_send();
6778 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
6779 key.type = BTRFS_INODE_ITEM_KEY;
6782 ret = btrfs_search_slot_for_read(send_root, &key, path, 1, 0);
6789 eb = path->nodes[0];
6790 slot = path->slots[0];
6791 btrfs_item_key_to_cpu(eb, &key, slot);
6793 ret = changed_cb(path, NULL, &key,
6794 BTRFS_COMPARE_TREE_NEW, sctx);
6798 ret = btrfs_next_item(send_root, path);
6808 ret = finish_inode_if_needed(sctx, 1);
6811 btrfs_free_path(path);
6815 static int tree_move_down(struct btrfs_path *path, int *level)
6817 struct extent_buffer *eb;
6819 BUG_ON(*level == 0);
6820 eb = btrfs_read_node_slot(path->nodes[*level], path->slots[*level]);
6824 path->nodes[*level - 1] = eb;
6825 path->slots[*level - 1] = 0;
6830 static int tree_move_next_or_upnext(struct btrfs_path *path,
6831 int *level, int root_level)
6835 nritems = btrfs_header_nritems(path->nodes[*level]);
6837 path->slots[*level]++;
6839 while (path->slots[*level] >= nritems) {
6840 if (*level == root_level)
6844 path->slots[*level] = 0;
6845 free_extent_buffer(path->nodes[*level]);
6846 path->nodes[*level] = NULL;
6848 path->slots[*level]++;
6850 nritems = btrfs_header_nritems(path->nodes[*level]);
6857 * Returns 1 if it had to move up and next. 0 is returned if it moved only next
6860 static int tree_advance(struct btrfs_path *path,
6861 int *level, int root_level,
6863 struct btrfs_key *key)
6867 if (*level == 0 || !allow_down) {
6868 ret = tree_move_next_or_upnext(path, level, root_level);
6870 ret = tree_move_down(path, level);
6874 btrfs_item_key_to_cpu(path->nodes[*level], key,
6875 path->slots[*level]);
6877 btrfs_node_key_to_cpu(path->nodes[*level], key,
6878 path->slots[*level]);
6883 static int tree_compare_item(struct btrfs_path *left_path,
6884 struct btrfs_path *right_path,
6889 unsigned long off1, off2;
6891 len1 = btrfs_item_size_nr(left_path->nodes[0], left_path->slots[0]);
6892 len2 = btrfs_item_size_nr(right_path->nodes[0], right_path->slots[0]);
6896 off1 = btrfs_item_ptr_offset(left_path->nodes[0], left_path->slots[0]);
6897 off2 = btrfs_item_ptr_offset(right_path->nodes[0],
6898 right_path->slots[0]);
6900 read_extent_buffer(left_path->nodes[0], tmp_buf, off1, len1);
6902 cmp = memcmp_extent_buffer(right_path->nodes[0], tmp_buf, off2, len1);
6909 * This function compares two trees and calls the provided callback for
6910 * every changed/new/deleted item it finds.
6911 * If shared tree blocks are encountered, whole subtrees are skipped, making
6912 * the compare pretty fast on snapshotted subvolumes.
6914 * This currently works on commit roots only. As commit roots are read only,
6915 * we don't do any locking. The commit roots are protected with transactions.
6916 * Transactions are ended and rejoined when a commit is tried in between.
6918 * This function checks for modifications done to the trees while comparing.
6919 * If it detects a change, it aborts immediately.
6921 static int btrfs_compare_trees(struct btrfs_root *left_root,
6922 struct btrfs_root *right_root,
6923 btrfs_changed_cb_t changed_cb, void *ctx)
6925 struct btrfs_fs_info *fs_info = left_root->fs_info;
6928 struct btrfs_path *left_path = NULL;
6929 struct btrfs_path *right_path = NULL;
6930 struct btrfs_key left_key;
6931 struct btrfs_key right_key;
6932 char *tmp_buf = NULL;
6933 int left_root_level;
6934 int right_root_level;
6937 int left_end_reached;
6938 int right_end_reached;
6946 left_path = btrfs_alloc_path();
6951 right_path = btrfs_alloc_path();
6957 tmp_buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
6963 left_path->search_commit_root = 1;
6964 left_path->skip_locking = 1;
6965 right_path->search_commit_root = 1;
6966 right_path->skip_locking = 1;
6969 * Strategy: Go to the first items of both trees. Then do
6971 * If both trees are at level 0
6972 * Compare keys of current items
6973 * If left < right treat left item as new, advance left tree
6975 * If left > right treat right item as deleted, advance right tree
6977 * If left == right do deep compare of items, treat as changed if
6978 * needed, advance both trees and repeat
6979 * If both trees are at the same level but not at level 0
6980 * Compare keys of current nodes/leafs
6981 * If left < right advance left tree and repeat
6982 * If left > right advance right tree and repeat
6983 * If left == right compare blockptrs of the next nodes/leafs
6984 * If they match advance both trees but stay at the same level
6986 * If they don't match advance both trees while allowing to go
6988 * If tree levels are different
6989 * Advance the tree that needs it and repeat
6991 * Advancing a tree means:
6992 * If we are at level 0, try to go to the next slot. If that's not
6993 * possible, go one level up and repeat. Stop when we found a level
6994 * where we could go to the next slot. We may at this point be on a
6997 * If we are not at level 0 and not on shared tree blocks, go one
7000 * If we are not at level 0 and on shared tree blocks, go one slot to
7001 * the right if possible or go up and right.
7004 down_read(&fs_info->commit_root_sem);
7005 left_level = btrfs_header_level(left_root->commit_root);
7006 left_root_level = left_level;
7007 left_path->nodes[left_level] =
7008 btrfs_clone_extent_buffer(left_root->commit_root);
7009 if (!left_path->nodes[left_level]) {
7010 up_read(&fs_info->commit_root_sem);
7015 right_level = btrfs_header_level(right_root->commit_root);
7016 right_root_level = right_level;
7017 right_path->nodes[right_level] =
7018 btrfs_clone_extent_buffer(right_root->commit_root);
7019 if (!right_path->nodes[right_level]) {
7020 up_read(&fs_info->commit_root_sem);
7024 up_read(&fs_info->commit_root_sem);
7026 if (left_level == 0)
7027 btrfs_item_key_to_cpu(left_path->nodes[left_level],
7028 &left_key, left_path->slots[left_level]);
7030 btrfs_node_key_to_cpu(left_path->nodes[left_level],
7031 &left_key, left_path->slots[left_level]);
7032 if (right_level == 0)
7033 btrfs_item_key_to_cpu(right_path->nodes[right_level],
7034 &right_key, right_path->slots[right_level]);
7036 btrfs_node_key_to_cpu(right_path->nodes[right_level],
7037 &right_key, right_path->slots[right_level]);
7039 left_end_reached = right_end_reached = 0;
7040 advance_left = advance_right = 0;
7044 if (advance_left && !left_end_reached) {
7045 ret = tree_advance(left_path, &left_level,
7047 advance_left != ADVANCE_ONLY_NEXT,
7050 left_end_reached = ADVANCE;
7055 if (advance_right && !right_end_reached) {
7056 ret = tree_advance(right_path, &right_level,
7058 advance_right != ADVANCE_ONLY_NEXT,
7061 right_end_reached = ADVANCE;
7067 if (left_end_reached && right_end_reached) {
7070 } else if (left_end_reached) {
7071 if (right_level == 0) {
7072 ret = changed_cb(left_path, right_path,
7074 BTRFS_COMPARE_TREE_DELETED,
7079 advance_right = ADVANCE;
7081 } else if (right_end_reached) {
7082 if (left_level == 0) {
7083 ret = changed_cb(left_path, right_path,
7085 BTRFS_COMPARE_TREE_NEW,
7090 advance_left = ADVANCE;
7094 if (left_level == 0 && right_level == 0) {
7095 cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
7097 ret = changed_cb(left_path, right_path,
7099 BTRFS_COMPARE_TREE_NEW,
7103 advance_left = ADVANCE;
7104 } else if (cmp > 0) {
7105 ret = changed_cb(left_path, right_path,
7107 BTRFS_COMPARE_TREE_DELETED,
7111 advance_right = ADVANCE;
7113 enum btrfs_compare_tree_result result;
7115 WARN_ON(!extent_buffer_uptodate(left_path->nodes[0]));
7116 ret = tree_compare_item(left_path, right_path,
7119 result = BTRFS_COMPARE_TREE_CHANGED;
7121 result = BTRFS_COMPARE_TREE_SAME;
7122 ret = changed_cb(left_path, right_path,
7123 &left_key, result, ctx);
7126 advance_left = ADVANCE;
7127 advance_right = ADVANCE;
7129 } else if (left_level == right_level) {
7130 cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
7132 advance_left = ADVANCE;
7133 } else if (cmp > 0) {
7134 advance_right = ADVANCE;
7136 left_blockptr = btrfs_node_blockptr(
7137 left_path->nodes[left_level],
7138 left_path->slots[left_level]);
7139 right_blockptr = btrfs_node_blockptr(
7140 right_path->nodes[right_level],
7141 right_path->slots[right_level]);
7142 left_gen = btrfs_node_ptr_generation(
7143 left_path->nodes[left_level],
7144 left_path->slots[left_level]);
7145 right_gen = btrfs_node_ptr_generation(
7146 right_path->nodes[right_level],
7147 right_path->slots[right_level]);
7148 if (left_blockptr == right_blockptr &&
7149 left_gen == right_gen) {
7151 * As we're on a shared block, don't
7152 * allow to go deeper.
7154 advance_left = ADVANCE_ONLY_NEXT;
7155 advance_right = ADVANCE_ONLY_NEXT;
7157 advance_left = ADVANCE;
7158 advance_right = ADVANCE;
7161 } else if (left_level < right_level) {
7162 advance_right = ADVANCE;
7164 advance_left = ADVANCE;
7169 btrfs_free_path(left_path);
7170 btrfs_free_path(right_path);
7175 static int send_subvol(struct send_ctx *sctx)
7179 if (!(sctx->flags & BTRFS_SEND_FLAG_OMIT_STREAM_HEADER)) {
7180 ret = send_header(sctx);
7185 ret = send_subvol_begin(sctx);
7189 if (sctx->parent_root) {
7190 ret = btrfs_compare_trees(sctx->send_root, sctx->parent_root,
7194 ret = finish_inode_if_needed(sctx, 1);
7198 ret = full_send_tree(sctx);
7204 free_recorded_refs(sctx);
7209 * If orphan cleanup did remove any orphans from a root, it means the tree
7210 * was modified and therefore the commit root is not the same as the current
7211 * root anymore. This is a problem, because send uses the commit root and
7212 * therefore can see inode items that don't exist in the current root anymore,
7213 * and for example make calls to btrfs_iget, which will do tree lookups based
7214 * on the current root and not on the commit root. Those lookups will fail,
7215 * returning a -ESTALE error, and making send fail with that error. So make
7216 * sure a send does not see any orphans we have just removed, and that it will
7217 * see the same inodes regardless of whether a transaction commit happened
7218 * before it started (meaning that the commit root will be the same as the
7219 * current root) or not.
7221 static int ensure_commit_roots_uptodate(struct send_ctx *sctx)
7224 struct btrfs_trans_handle *trans = NULL;
7227 if (sctx->parent_root &&
7228 sctx->parent_root->node != sctx->parent_root->commit_root)
7231 for (i = 0; i < sctx->clone_roots_cnt; i++)
7232 if (sctx->clone_roots[i].root->node !=
7233 sctx->clone_roots[i].root->commit_root)
7237 return btrfs_end_transaction(trans);
7242 /* Use any root, all fs roots will get their commit roots updated. */
7244 trans = btrfs_join_transaction(sctx->send_root);
7246 return PTR_ERR(trans);
7250 return btrfs_commit_transaction(trans);
7254 * Make sure any existing dellaloc is flushed for any root used by a send
7255 * operation so that we do not miss any data and we do not race with writeback
7256 * finishing and changing a tree while send is using the tree. This could
7257 * happen if a subvolume is in RW mode, has delalloc, is turned to RO mode and
7258 * a send operation then uses the subvolume.
7259 * After flushing delalloc ensure_commit_roots_uptodate() must be called.
7261 static int flush_delalloc_roots(struct send_ctx *sctx)
7263 struct btrfs_root *root = sctx->parent_root;
7268 ret = btrfs_start_delalloc_snapshot(root);
7271 btrfs_wait_ordered_extents(root, U64_MAX, 0, U64_MAX);
7274 for (i = 0; i < sctx->clone_roots_cnt; i++) {
7275 root = sctx->clone_roots[i].root;
7276 ret = btrfs_start_delalloc_snapshot(root);
7279 btrfs_wait_ordered_extents(root, U64_MAX, 0, U64_MAX);
7285 static void btrfs_root_dec_send_in_progress(struct btrfs_root* root)
7287 spin_lock(&root->root_item_lock);
7288 root->send_in_progress--;
7290 * Not much left to do, we don't know why it's unbalanced and
7291 * can't blindly reset it to 0.
7293 if (root->send_in_progress < 0)
7294 btrfs_err(root->fs_info,
7295 "send_in_progress unbalanced %d root %llu",
7296 root->send_in_progress, root->root_key.objectid);
7297 spin_unlock(&root->root_item_lock);
7300 static void dedupe_in_progress_warn(const struct btrfs_root *root)
7302 btrfs_warn_rl(root->fs_info,
7303 "cannot use root %llu for send while deduplications on it are in progress (%d in progress)",
7304 root->root_key.objectid, root->dedupe_in_progress);
7307 long btrfs_ioctl_send(struct file *mnt_file, struct btrfs_ioctl_send_args *arg)
7310 struct btrfs_root *send_root = BTRFS_I(file_inode(mnt_file))->root;
7311 struct btrfs_fs_info *fs_info = send_root->fs_info;
7312 struct btrfs_root *clone_root;
7313 struct btrfs_key key;
7314 struct send_ctx *sctx = NULL;
7316 u64 *clone_sources_tmp = NULL;
7317 int clone_sources_to_rollback = 0;
7318 unsigned alloc_size;
7319 int sort_clone_roots = 0;
7322 if (!capable(CAP_SYS_ADMIN))
7326 * The subvolume must remain read-only during send, protect against
7327 * making it RW. This also protects against deletion.
7329 spin_lock(&send_root->root_item_lock);
7330 if (btrfs_root_readonly(send_root) && send_root->dedupe_in_progress) {
7331 dedupe_in_progress_warn(send_root);
7332 spin_unlock(&send_root->root_item_lock);
7335 send_root->send_in_progress++;
7336 spin_unlock(&send_root->root_item_lock);
7339 * Userspace tools do the checks and warn the user if it's
7342 if (!btrfs_root_readonly(send_root)) {
7348 * Check that we don't overflow at later allocations, we request
7349 * clone_sources_count + 1 items, and compare to unsigned long inside
7350 * access_ok. Also set an upper limit for allocation size so this can't
7351 * easily exhaust memory. Max number of clone sources is about 200K.
7353 if (arg->clone_sources_count > SZ_8M / sizeof(struct clone_root)) {
7358 if (!access_ok(arg->clone_sources,
7359 sizeof(*arg->clone_sources) *
7360 arg->clone_sources_count)) {
7365 if (arg->flags & ~BTRFS_SEND_FLAG_MASK) {
7370 sctx = kzalloc(sizeof(struct send_ctx), GFP_KERNEL);
7376 INIT_LIST_HEAD(&sctx->new_refs);
7377 INIT_LIST_HEAD(&sctx->deleted_refs);
7378 INIT_RADIX_TREE(&sctx->name_cache, GFP_KERNEL);
7379 INIT_LIST_HEAD(&sctx->name_cache_list);
7381 sctx->flags = arg->flags;
7383 sctx->send_filp = fget(arg->send_fd);
7384 if (!sctx->send_filp) {
7389 sctx->send_root = send_root;
7391 * Unlikely but possible, if the subvolume is marked for deletion but
7392 * is slow to remove the directory entry, send can still be started
7394 if (btrfs_root_dead(sctx->send_root)) {
7399 sctx->clone_roots_cnt = arg->clone_sources_count;
7401 sctx->send_max_size = BTRFS_SEND_BUF_SIZE;
7402 sctx->send_buf = kvmalloc(sctx->send_max_size, GFP_KERNEL);
7403 if (!sctx->send_buf) {
7408 sctx->read_buf = kvmalloc(BTRFS_SEND_READ_SIZE, GFP_KERNEL);
7409 if (!sctx->read_buf) {
7414 sctx->pending_dir_moves = RB_ROOT;
7415 sctx->waiting_dir_moves = RB_ROOT;
7416 sctx->orphan_dirs = RB_ROOT;
7418 alloc_size = sizeof(struct clone_root) * (arg->clone_sources_count + 1);
7420 sctx->clone_roots = kvzalloc(alloc_size, GFP_KERNEL);
7421 if (!sctx->clone_roots) {
7426 alloc_size = arg->clone_sources_count * sizeof(*arg->clone_sources);
7428 if (arg->clone_sources_count) {
7429 clone_sources_tmp = kvmalloc(alloc_size, GFP_KERNEL);
7430 if (!clone_sources_tmp) {
7435 ret = copy_from_user(clone_sources_tmp, arg->clone_sources,
7442 for (i = 0; i < arg->clone_sources_count; i++) {
7443 key.objectid = clone_sources_tmp[i];
7444 key.type = BTRFS_ROOT_ITEM_KEY;
7445 key.offset = (u64)-1;
7447 index = srcu_read_lock(&fs_info->subvol_srcu);
7449 clone_root = btrfs_read_fs_root_no_name(fs_info, &key);
7450 if (IS_ERR(clone_root)) {
7451 srcu_read_unlock(&fs_info->subvol_srcu, index);
7452 ret = PTR_ERR(clone_root);
7455 spin_lock(&clone_root->root_item_lock);
7456 if (!btrfs_root_readonly(clone_root) ||
7457 btrfs_root_dead(clone_root)) {
7458 spin_unlock(&clone_root->root_item_lock);
7459 srcu_read_unlock(&fs_info->subvol_srcu, index);
7463 if (clone_root->dedupe_in_progress) {
7464 dedupe_in_progress_warn(clone_root);
7465 spin_unlock(&clone_root->root_item_lock);
7466 srcu_read_unlock(&fs_info->subvol_srcu, index);
7470 clone_root->send_in_progress++;
7471 spin_unlock(&clone_root->root_item_lock);
7472 srcu_read_unlock(&fs_info->subvol_srcu, index);
7474 sctx->clone_roots[i].root = clone_root;
7475 clone_sources_to_rollback = i + 1;
7477 kvfree(clone_sources_tmp);
7478 clone_sources_tmp = NULL;
7481 if (arg->parent_root) {
7482 key.objectid = arg->parent_root;
7483 key.type = BTRFS_ROOT_ITEM_KEY;
7484 key.offset = (u64)-1;
7486 index = srcu_read_lock(&fs_info->subvol_srcu);
7488 sctx->parent_root = btrfs_read_fs_root_no_name(fs_info, &key);
7489 if (IS_ERR(sctx->parent_root)) {
7490 srcu_read_unlock(&fs_info->subvol_srcu, index);
7491 ret = PTR_ERR(sctx->parent_root);
7495 spin_lock(&sctx->parent_root->root_item_lock);
7496 sctx->parent_root->send_in_progress++;
7497 if (!btrfs_root_readonly(sctx->parent_root) ||
7498 btrfs_root_dead(sctx->parent_root)) {
7499 spin_unlock(&sctx->parent_root->root_item_lock);
7500 srcu_read_unlock(&fs_info->subvol_srcu, index);
7504 if (sctx->parent_root->dedupe_in_progress) {
7505 dedupe_in_progress_warn(sctx->parent_root);
7506 spin_unlock(&sctx->parent_root->root_item_lock);
7507 srcu_read_unlock(&fs_info->subvol_srcu, index);
7511 spin_unlock(&sctx->parent_root->root_item_lock);
7513 srcu_read_unlock(&fs_info->subvol_srcu, index);
7517 * Clones from send_root are allowed, but only if the clone source
7518 * is behind the current send position. This is checked while searching
7519 * for possible clone sources.
7521 sctx->clone_roots[sctx->clone_roots_cnt++].root = sctx->send_root;
7523 /* We do a bsearch later */
7524 sort(sctx->clone_roots, sctx->clone_roots_cnt,
7525 sizeof(*sctx->clone_roots), __clone_root_cmp_sort,
7527 sort_clone_roots = 1;
7529 ret = flush_delalloc_roots(sctx);
7533 ret = ensure_commit_roots_uptodate(sctx);
7537 mutex_lock(&fs_info->balance_mutex);
7538 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
7539 mutex_unlock(&fs_info->balance_mutex);
7540 btrfs_warn_rl(fs_info,
7541 "cannot run send because a balance operation is in progress");
7545 fs_info->send_in_progress++;
7546 mutex_unlock(&fs_info->balance_mutex);
7548 current->journal_info = BTRFS_SEND_TRANS_STUB;
7549 ret = send_subvol(sctx);
7550 current->journal_info = NULL;
7551 mutex_lock(&fs_info->balance_mutex);
7552 fs_info->send_in_progress--;
7553 mutex_unlock(&fs_info->balance_mutex);
7557 if (!(sctx->flags & BTRFS_SEND_FLAG_OMIT_END_CMD)) {
7558 ret = begin_cmd(sctx, BTRFS_SEND_C_END);
7561 ret = send_cmd(sctx);
7567 WARN_ON(sctx && !ret && !RB_EMPTY_ROOT(&sctx->pending_dir_moves));
7568 while (sctx && !RB_EMPTY_ROOT(&sctx->pending_dir_moves)) {
7570 struct pending_dir_move *pm;
7572 n = rb_first(&sctx->pending_dir_moves);
7573 pm = rb_entry(n, struct pending_dir_move, node);
7574 while (!list_empty(&pm->list)) {
7575 struct pending_dir_move *pm2;
7577 pm2 = list_first_entry(&pm->list,
7578 struct pending_dir_move, list);
7579 free_pending_move(sctx, pm2);
7581 free_pending_move(sctx, pm);
7584 WARN_ON(sctx && !ret && !RB_EMPTY_ROOT(&sctx->waiting_dir_moves));
7585 while (sctx && !RB_EMPTY_ROOT(&sctx->waiting_dir_moves)) {
7587 struct waiting_dir_move *dm;
7589 n = rb_first(&sctx->waiting_dir_moves);
7590 dm = rb_entry(n, struct waiting_dir_move, node);
7591 rb_erase(&dm->node, &sctx->waiting_dir_moves);
7595 WARN_ON(sctx && !ret && !RB_EMPTY_ROOT(&sctx->orphan_dirs));
7596 while (sctx && !RB_EMPTY_ROOT(&sctx->orphan_dirs)) {
7598 struct orphan_dir_info *odi;
7600 n = rb_first(&sctx->orphan_dirs);
7601 odi = rb_entry(n, struct orphan_dir_info, node);
7602 free_orphan_dir_info(sctx, odi);
7605 if (sort_clone_roots) {
7606 for (i = 0; i < sctx->clone_roots_cnt; i++)
7607 btrfs_root_dec_send_in_progress(
7608 sctx->clone_roots[i].root);
7610 for (i = 0; sctx && i < clone_sources_to_rollback; i++)
7611 btrfs_root_dec_send_in_progress(
7612 sctx->clone_roots[i].root);
7614 btrfs_root_dec_send_in_progress(send_root);
7616 if (sctx && !IS_ERR_OR_NULL(sctx->parent_root))
7617 btrfs_root_dec_send_in_progress(sctx->parent_root);
7619 kvfree(clone_sources_tmp);
7622 if (sctx->send_filp)
7623 fput(sctx->send_filp);
7625 kvfree(sctx->clone_roots);
7626 kvfree(sctx->send_buf);
7627 kvfree(sctx->read_buf);
7629 name_cache_free(sctx);