xref: /openbmc/linux/fs/btrfs/send.c (revision 3c38faa3)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2012 Alexander Block.  All rights reserved.
4  */
5 
6 #include <linux/bsearch.h>
7 #include <linux/fs.h>
8 #include <linux/file.h>
9 #include <linux/sort.h>
10 #include <linux/mount.h>
11 #include <linux/xattr.h>
12 #include <linux/posix_acl_xattr.h>
13 #include <linux/radix-tree.h>
14 #include <linux/vmalloc.h>
15 #include <linux/string.h>
16 #include <linux/compat.h>
17 #include <linux/crc32c.h>
18 #include <linux/fsverity.h>
19 
20 #include "send.h"
21 #include "ctree.h"
22 #include "backref.h"
23 #include "locking.h"
24 #include "disk-io.h"
25 #include "btrfs_inode.h"
26 #include "transaction.h"
27 #include "compression.h"
28 #include "xattr.h"
29 #include "print-tree.h"
30 #include "accessors.h"
31 #include "dir-item.h"
32 #include "file-item.h"
33 #include "ioctl.h"
34 #include "verity.h"
35 #include "lru_cache.h"
36 
37 /*
38  * Maximum number of references an extent can have in order for us to attempt to
39  * issue clone operations instead of write operations. This currently exists to
40  * avoid hitting limitations of the backreference walking code (taking a lot of
41  * time and using too much memory for extents with large number of references).
42  */
43 #define SEND_MAX_EXTENT_REFS	1024
44 
45 /*
46  * A fs_path is a helper to dynamically build path names with unknown size.
47  * It reallocates the internal buffer on demand.
48  * It allows fast adding of path elements on the right side (normal path) and
49  * fast adding to the left side (reversed path). A reversed path can also be
50  * unreversed if needed.
51  */
52 struct fs_path {
53 	union {
54 		struct {
55 			char *start;
56 			char *end;
57 
58 			char *buf;
59 			unsigned short buf_len:15;
60 			unsigned short reversed:1;
61 			char inline_buf[];
62 		};
63 		/*
64 		 * Average path length does not exceed 200 bytes, we'll have
65 		 * better packing in the slab and higher chance to satisfy
66 		 * a allocation later during send.
67 		 */
68 		char pad[256];
69 	};
70 };
71 #define FS_PATH_INLINE_SIZE \
72 	(sizeof(struct fs_path) - offsetof(struct fs_path, inline_buf))
73 
74 
75 /* reused for each extent */
76 struct clone_root {
77 	struct btrfs_root *root;
78 	u64 ino;
79 	u64 offset;
80 	u64 num_bytes;
81 	bool found_ref;
82 };
83 
84 #define SEND_MAX_NAME_CACHE_SIZE			256
85 
86 /*
87  * Limit the root_ids array of struct backref_cache_entry to 17 elements.
88  * This makes the size of a cache entry to be exactly 192 bytes on x86_64, which
89  * can be satisfied from the kmalloc-192 slab, without wasting any space.
90  * The most common case is to have a single root for cloning, which corresponds
91  * to the send root. Having the user specify more than 16 clone roots is not
92  * common, and in such rare cases we simply don't use caching if the number of
93  * cloning roots that lead down to a leaf is more than 17.
94  */
95 #define SEND_MAX_BACKREF_CACHE_ROOTS			17
96 
97 /*
98  * Max number of entries in the cache.
99  * With SEND_MAX_BACKREF_CACHE_ROOTS as 17, the size in bytes, excluding
100  * maple tree's internal nodes, is 24K.
101  */
102 #define SEND_MAX_BACKREF_CACHE_SIZE 128
103 
104 /*
105  * A backref cache entry maps a leaf to a list of IDs of roots from which the
106  * leaf is accessible and we can use for clone operations.
107  * With SEND_MAX_BACKREF_CACHE_ROOTS as 12, each cache entry is 128 bytes (on
108  * x86_64).
109  */
110 struct backref_cache_entry {
111 	struct btrfs_lru_cache_entry entry;
112 	u64 root_ids[SEND_MAX_BACKREF_CACHE_ROOTS];
113 	/* Number of valid elements in the root_ids array. */
114 	int num_roots;
115 };
116 
117 /* See the comment at lru_cache.h about struct btrfs_lru_cache_entry. */
118 static_assert(offsetof(struct backref_cache_entry, entry) == 0);
119 
120 /*
121  * Max number of entries in the cache that stores directories that were already
122  * created. The cache uses raw struct btrfs_lru_cache_entry entries, so it uses
123  * at most 4096 bytes - sizeof(struct btrfs_lru_cache_entry) is 48 bytes, but
124  * the kmalloc-64 slab is used, so we get 4096 bytes (64 bytes * 64).
125  */
126 #define SEND_MAX_DIR_CREATED_CACHE_SIZE			64
127 
128 /*
129  * Max number of entries in the cache that stores directories that were already
130  * created. The cache uses raw struct btrfs_lru_cache_entry entries, so it uses
131  * at most 4096 bytes - sizeof(struct btrfs_lru_cache_entry) is 48 bytes, but
132  * the kmalloc-64 slab is used, so we get 4096 bytes (64 bytes * 64).
133  */
134 #define SEND_MAX_DIR_UTIMES_CACHE_SIZE			64
135 
136 struct send_ctx {
137 	struct file *send_filp;
138 	loff_t send_off;
139 	char *send_buf;
140 	u32 send_size;
141 	u32 send_max_size;
142 	/*
143 	 * Whether BTRFS_SEND_A_DATA attribute was already added to current
144 	 * command (since protocol v2, data must be the last attribute).
145 	 */
146 	bool put_data;
147 	struct page **send_buf_pages;
148 	u64 flags;	/* 'flags' member of btrfs_ioctl_send_args is u64 */
149 	/* Protocol version compatibility requested */
150 	u32 proto;
151 
152 	struct btrfs_root *send_root;
153 	struct btrfs_root *parent_root;
154 	struct clone_root *clone_roots;
155 	int clone_roots_cnt;
156 
157 	/* current state of the compare_tree call */
158 	struct btrfs_path *left_path;
159 	struct btrfs_path *right_path;
160 	struct btrfs_key *cmp_key;
161 
162 	/*
163 	 * Keep track of the generation of the last transaction that was used
164 	 * for relocating a block group. This is periodically checked in order
165 	 * to detect if a relocation happened since the last check, so that we
166 	 * don't operate on stale extent buffers for nodes (level >= 1) or on
167 	 * stale disk_bytenr values of file extent items.
168 	 */
169 	u64 last_reloc_trans;
170 
171 	/*
172 	 * infos of the currently processed inode. In case of deleted inodes,
173 	 * these are the values from the deleted inode.
174 	 */
175 	u64 cur_ino;
176 	u64 cur_inode_gen;
177 	u64 cur_inode_size;
178 	u64 cur_inode_mode;
179 	u64 cur_inode_rdev;
180 	u64 cur_inode_last_extent;
181 	u64 cur_inode_next_write_offset;
182 	bool cur_inode_new;
183 	bool cur_inode_new_gen;
184 	bool cur_inode_deleted;
185 	bool ignore_cur_inode;
186 	bool cur_inode_needs_verity;
187 	void *verity_descriptor;
188 
189 	u64 send_progress;
190 
191 	struct list_head new_refs;
192 	struct list_head deleted_refs;
193 
194 	struct btrfs_lru_cache name_cache;
195 
196 	/*
197 	 * The inode we are currently processing. It's not NULL only when we
198 	 * need to issue write commands for data extents from this inode.
199 	 */
200 	struct inode *cur_inode;
201 	struct file_ra_state ra;
202 	u64 page_cache_clear_start;
203 	bool clean_page_cache;
204 
205 	/*
206 	 * We process inodes by their increasing order, so if before an
207 	 * incremental send we reverse the parent/child relationship of
208 	 * directories such that a directory with a lower inode number was
209 	 * the parent of a directory with a higher inode number, and the one
210 	 * becoming the new parent got renamed too, we can't rename/move the
211 	 * directory with lower inode number when we finish processing it - we
212 	 * must process the directory with higher inode number first, then
213 	 * rename/move it and then rename/move the directory with lower inode
214 	 * number. Example follows.
215 	 *
216 	 * Tree state when the first send was performed:
217 	 *
218 	 * .
219 	 * |-- a                   (ino 257)
220 	 *     |-- b               (ino 258)
221 	 *         |
222 	 *         |
223 	 *         |-- c           (ino 259)
224 	 *         |   |-- d       (ino 260)
225 	 *         |
226 	 *         |-- c2          (ino 261)
227 	 *
228 	 * Tree state when the second (incremental) send is performed:
229 	 *
230 	 * .
231 	 * |-- a                   (ino 257)
232 	 *     |-- b               (ino 258)
233 	 *         |-- c2          (ino 261)
234 	 *             |-- d2      (ino 260)
235 	 *                 |-- cc  (ino 259)
236 	 *
237 	 * The sequence of steps that lead to the second state was:
238 	 *
239 	 * mv /a/b/c/d /a/b/c2/d2
240 	 * mv /a/b/c /a/b/c2/d2/cc
241 	 *
242 	 * "c" has lower inode number, but we can't move it (2nd mv operation)
243 	 * before we move "d", which has higher inode number.
244 	 *
245 	 * So we just memorize which move/rename operations must be performed
246 	 * later when their respective parent is processed and moved/renamed.
247 	 */
248 
249 	/* Indexed by parent directory inode number. */
250 	struct rb_root pending_dir_moves;
251 
252 	/*
253 	 * Reverse index, indexed by the inode number of a directory that
254 	 * is waiting for the move/rename of its immediate parent before its
255 	 * own move/rename can be performed.
256 	 */
257 	struct rb_root waiting_dir_moves;
258 
259 	/*
260 	 * A directory that is going to be rm'ed might have a child directory
261 	 * which is in the pending directory moves index above. In this case,
262 	 * the directory can only be removed after the move/rename of its child
263 	 * is performed. Example:
264 	 *
265 	 * Parent snapshot:
266 	 *
267 	 * .                        (ino 256)
268 	 * |-- a/                   (ino 257)
269 	 *     |-- b/               (ino 258)
270 	 *         |-- c/           (ino 259)
271 	 *         |   |-- x/       (ino 260)
272 	 *         |
273 	 *         |-- y/           (ino 261)
274 	 *
275 	 * Send snapshot:
276 	 *
277 	 * .                        (ino 256)
278 	 * |-- a/                   (ino 257)
279 	 *     |-- b/               (ino 258)
280 	 *         |-- YY/          (ino 261)
281 	 *              |-- x/      (ino 260)
282 	 *
283 	 * Sequence of steps that lead to the send snapshot:
284 	 * rm -f /a/b/c/foo.txt
285 	 * mv /a/b/y /a/b/YY
286 	 * mv /a/b/c/x /a/b/YY
287 	 * rmdir /a/b/c
288 	 *
289 	 * When the child is processed, its move/rename is delayed until its
290 	 * parent is processed (as explained above), but all other operations
291 	 * like update utimes, chown, chgrp, etc, are performed and the paths
292 	 * that it uses for those operations must use the orphanized name of
293 	 * its parent (the directory we're going to rm later), so we need to
294 	 * memorize that name.
295 	 *
296 	 * Indexed by the inode number of the directory to be deleted.
297 	 */
298 	struct rb_root orphan_dirs;
299 
300 	struct rb_root rbtree_new_refs;
301 	struct rb_root rbtree_deleted_refs;
302 
303 	struct btrfs_lru_cache backref_cache;
304 	u64 backref_cache_last_reloc_trans;
305 
306 	struct btrfs_lru_cache dir_created_cache;
307 	struct btrfs_lru_cache dir_utimes_cache;
308 };
309 
310 struct pending_dir_move {
311 	struct rb_node node;
312 	struct list_head list;
313 	u64 parent_ino;
314 	u64 ino;
315 	u64 gen;
316 	struct list_head update_refs;
317 };
318 
319 struct waiting_dir_move {
320 	struct rb_node node;
321 	u64 ino;
322 	/*
323 	 * There might be some directory that could not be removed because it
324 	 * was waiting for this directory inode to be moved first. Therefore
325 	 * after this directory is moved, we can try to rmdir the ino rmdir_ino.
326 	 */
327 	u64 rmdir_ino;
328 	u64 rmdir_gen;
329 	bool orphanized;
330 };
331 
332 struct orphan_dir_info {
333 	struct rb_node node;
334 	u64 ino;
335 	u64 gen;
336 	u64 last_dir_index_offset;
337 	u64 dir_high_seq_ino;
338 };
339 
340 struct name_cache_entry {
341 	/*
342 	 * The key in the entry is an inode number, and the generation matches
343 	 * the inode's generation.
344 	 */
345 	struct btrfs_lru_cache_entry entry;
346 	u64 parent_ino;
347 	u64 parent_gen;
348 	int ret;
349 	int need_later_update;
350 	int name_len;
351 	char name[];
352 };
353 
354 /* See the comment at lru_cache.h about struct btrfs_lru_cache_entry. */
355 static_assert(offsetof(struct name_cache_entry, entry) == 0);
356 
357 #define ADVANCE							1
358 #define ADVANCE_ONLY_NEXT					-1
359 
360 enum btrfs_compare_tree_result {
361 	BTRFS_COMPARE_TREE_NEW,
362 	BTRFS_COMPARE_TREE_DELETED,
363 	BTRFS_COMPARE_TREE_CHANGED,
364 	BTRFS_COMPARE_TREE_SAME,
365 };
366 
367 __cold
368 static void inconsistent_snapshot_error(struct send_ctx *sctx,
369 					enum btrfs_compare_tree_result result,
370 					const char *what)
371 {
372 	const char *result_string;
373 
374 	switch (result) {
375 	case BTRFS_COMPARE_TREE_NEW:
376 		result_string = "new";
377 		break;
378 	case BTRFS_COMPARE_TREE_DELETED:
379 		result_string = "deleted";
380 		break;
381 	case BTRFS_COMPARE_TREE_CHANGED:
382 		result_string = "updated";
383 		break;
384 	case BTRFS_COMPARE_TREE_SAME:
385 		ASSERT(0);
386 		result_string = "unchanged";
387 		break;
388 	default:
389 		ASSERT(0);
390 		result_string = "unexpected";
391 	}
392 
393 	btrfs_err(sctx->send_root->fs_info,
394 		  "Send: inconsistent snapshot, found %s %s for inode %llu without updated inode item, send root is %llu, parent root is %llu",
395 		  result_string, what, sctx->cmp_key->objectid,
396 		  sctx->send_root->root_key.objectid,
397 		  (sctx->parent_root ?
398 		   sctx->parent_root->root_key.objectid : 0));
399 }
400 
401 __maybe_unused
402 static bool proto_cmd_ok(const struct send_ctx *sctx, int cmd)
403 {
404 	switch (sctx->proto) {
405 	case 1:	 return cmd <= BTRFS_SEND_C_MAX_V1;
406 	case 2:	 return cmd <= BTRFS_SEND_C_MAX_V2;
407 	case 3:	 return cmd <= BTRFS_SEND_C_MAX_V3;
408 	default: return false;
409 	}
410 }
411 
412 static int is_waiting_for_move(struct send_ctx *sctx, u64 ino);
413 
414 static struct waiting_dir_move *
415 get_waiting_dir_move(struct send_ctx *sctx, u64 ino);
416 
417 static int is_waiting_for_rm(struct send_ctx *sctx, u64 dir_ino, u64 gen);
418 
419 static int need_send_hole(struct send_ctx *sctx)
420 {
421 	return (sctx->parent_root && !sctx->cur_inode_new &&
422 		!sctx->cur_inode_new_gen && !sctx->cur_inode_deleted &&
423 		S_ISREG(sctx->cur_inode_mode));
424 }
425 
426 static void fs_path_reset(struct fs_path *p)
427 {
428 	if (p->reversed) {
429 		p->start = p->buf + p->buf_len - 1;
430 		p->end = p->start;
431 		*p->start = 0;
432 	} else {
433 		p->start = p->buf;
434 		p->end = p->start;
435 		*p->start = 0;
436 	}
437 }
438 
439 static struct fs_path *fs_path_alloc(void)
440 {
441 	struct fs_path *p;
442 
443 	p = kmalloc(sizeof(*p), GFP_KERNEL);
444 	if (!p)
445 		return NULL;
446 	p->reversed = 0;
447 	p->buf = p->inline_buf;
448 	p->buf_len = FS_PATH_INLINE_SIZE;
449 	fs_path_reset(p);
450 	return p;
451 }
452 
453 static struct fs_path *fs_path_alloc_reversed(void)
454 {
455 	struct fs_path *p;
456 
457 	p = fs_path_alloc();
458 	if (!p)
459 		return NULL;
460 	p->reversed = 1;
461 	fs_path_reset(p);
462 	return p;
463 }
464 
465 static void fs_path_free(struct fs_path *p)
466 {
467 	if (!p)
468 		return;
469 	if (p->buf != p->inline_buf)
470 		kfree(p->buf);
471 	kfree(p);
472 }
473 
474 static int fs_path_len(struct fs_path *p)
475 {
476 	return p->end - p->start;
477 }
478 
479 static int fs_path_ensure_buf(struct fs_path *p, int len)
480 {
481 	char *tmp_buf;
482 	int path_len;
483 	int old_buf_len;
484 
485 	len++;
486 
487 	if (p->buf_len >= len)
488 		return 0;
489 
490 	if (len > PATH_MAX) {
491 		WARN_ON(1);
492 		return -ENOMEM;
493 	}
494 
495 	path_len = p->end - p->start;
496 	old_buf_len = p->buf_len;
497 
498 	/*
499 	 * Allocate to the next largest kmalloc bucket size, to let
500 	 * the fast path happen most of the time.
501 	 */
502 	len = kmalloc_size_roundup(len);
503 	/*
504 	 * First time the inline_buf does not suffice
505 	 */
506 	if (p->buf == p->inline_buf) {
507 		tmp_buf = kmalloc(len, GFP_KERNEL);
508 		if (tmp_buf)
509 			memcpy(tmp_buf, p->buf, old_buf_len);
510 	} else {
511 		tmp_buf = krealloc(p->buf, len, GFP_KERNEL);
512 	}
513 	if (!tmp_buf)
514 		return -ENOMEM;
515 	p->buf = tmp_buf;
516 	p->buf_len = len;
517 
518 	if (p->reversed) {
519 		tmp_buf = p->buf + old_buf_len - path_len - 1;
520 		p->end = p->buf + p->buf_len - 1;
521 		p->start = p->end - path_len;
522 		memmove(p->start, tmp_buf, path_len + 1);
523 	} else {
524 		p->start = p->buf;
525 		p->end = p->start + path_len;
526 	}
527 	return 0;
528 }
529 
530 static int fs_path_prepare_for_add(struct fs_path *p, int name_len,
531 				   char **prepared)
532 {
533 	int ret;
534 	int new_len;
535 
536 	new_len = p->end - p->start + name_len;
537 	if (p->start != p->end)
538 		new_len++;
539 	ret = fs_path_ensure_buf(p, new_len);
540 	if (ret < 0)
541 		goto out;
542 
543 	if (p->reversed) {
544 		if (p->start != p->end)
545 			*--p->start = '/';
546 		p->start -= name_len;
547 		*prepared = p->start;
548 	} else {
549 		if (p->start != p->end)
550 			*p->end++ = '/';
551 		*prepared = p->end;
552 		p->end += name_len;
553 		*p->end = 0;
554 	}
555 
556 out:
557 	return ret;
558 }
559 
560 static int fs_path_add(struct fs_path *p, const char *name, int name_len)
561 {
562 	int ret;
563 	char *prepared;
564 
565 	ret = fs_path_prepare_for_add(p, name_len, &prepared);
566 	if (ret < 0)
567 		goto out;
568 	memcpy(prepared, name, name_len);
569 
570 out:
571 	return ret;
572 }
573 
574 static int fs_path_add_path(struct fs_path *p, struct fs_path *p2)
575 {
576 	int ret;
577 	char *prepared;
578 
579 	ret = fs_path_prepare_for_add(p, p2->end - p2->start, &prepared);
580 	if (ret < 0)
581 		goto out;
582 	memcpy(prepared, p2->start, p2->end - p2->start);
583 
584 out:
585 	return ret;
586 }
587 
588 static int fs_path_add_from_extent_buffer(struct fs_path *p,
589 					  struct extent_buffer *eb,
590 					  unsigned long off, int len)
591 {
592 	int ret;
593 	char *prepared;
594 
595 	ret = fs_path_prepare_for_add(p, len, &prepared);
596 	if (ret < 0)
597 		goto out;
598 
599 	read_extent_buffer(eb, prepared, off, len);
600 
601 out:
602 	return ret;
603 }
604 
605 static int fs_path_copy(struct fs_path *p, struct fs_path *from)
606 {
607 	p->reversed = from->reversed;
608 	fs_path_reset(p);
609 
610 	return fs_path_add_path(p, from);
611 }
612 
613 static void fs_path_unreverse(struct fs_path *p)
614 {
615 	char *tmp;
616 	int len;
617 
618 	if (!p->reversed)
619 		return;
620 
621 	tmp = p->start;
622 	len = p->end - p->start;
623 	p->start = p->buf;
624 	p->end = p->start + len;
625 	memmove(p->start, tmp, len + 1);
626 	p->reversed = 0;
627 }
628 
629 static struct btrfs_path *alloc_path_for_send(void)
630 {
631 	struct btrfs_path *path;
632 
633 	path = btrfs_alloc_path();
634 	if (!path)
635 		return NULL;
636 	path->search_commit_root = 1;
637 	path->skip_locking = 1;
638 	path->need_commit_sem = 1;
639 	return path;
640 }
641 
642 static int write_buf(struct file *filp, const void *buf, u32 len, loff_t *off)
643 {
644 	int ret;
645 	u32 pos = 0;
646 
647 	while (pos < len) {
648 		ret = kernel_write(filp, buf + pos, len - pos, off);
649 		if (ret < 0)
650 			return ret;
651 		if (ret == 0)
652 			return -EIO;
653 		pos += ret;
654 	}
655 
656 	return 0;
657 }
658 
659 static int tlv_put(struct send_ctx *sctx, u16 attr, const void *data, int len)
660 {
661 	struct btrfs_tlv_header *hdr;
662 	int total_len = sizeof(*hdr) + len;
663 	int left = sctx->send_max_size - sctx->send_size;
664 
665 	if (WARN_ON_ONCE(sctx->put_data))
666 		return -EINVAL;
667 
668 	if (unlikely(left < total_len))
669 		return -EOVERFLOW;
670 
671 	hdr = (struct btrfs_tlv_header *) (sctx->send_buf + sctx->send_size);
672 	put_unaligned_le16(attr, &hdr->tlv_type);
673 	put_unaligned_le16(len, &hdr->tlv_len);
674 	memcpy(hdr + 1, data, len);
675 	sctx->send_size += total_len;
676 
677 	return 0;
678 }
679 
680 #define TLV_PUT_DEFINE_INT(bits) \
681 	static int tlv_put_u##bits(struct send_ctx *sctx,	 	\
682 			u##bits attr, u##bits value)			\
683 	{								\
684 		__le##bits __tmp = cpu_to_le##bits(value);		\
685 		return tlv_put(sctx, attr, &__tmp, sizeof(__tmp));	\
686 	}
687 
688 TLV_PUT_DEFINE_INT(8)
689 TLV_PUT_DEFINE_INT(32)
690 TLV_PUT_DEFINE_INT(64)
691 
692 static int tlv_put_string(struct send_ctx *sctx, u16 attr,
693 			  const char *str, int len)
694 {
695 	if (len == -1)
696 		len = strlen(str);
697 	return tlv_put(sctx, attr, str, len);
698 }
699 
700 static int tlv_put_uuid(struct send_ctx *sctx, u16 attr,
701 			const u8 *uuid)
702 {
703 	return tlv_put(sctx, attr, uuid, BTRFS_UUID_SIZE);
704 }
705 
706 static int tlv_put_btrfs_timespec(struct send_ctx *sctx, u16 attr,
707 				  struct extent_buffer *eb,
708 				  struct btrfs_timespec *ts)
709 {
710 	struct btrfs_timespec bts;
711 	read_extent_buffer(eb, &bts, (unsigned long)ts, sizeof(bts));
712 	return tlv_put(sctx, attr, &bts, sizeof(bts));
713 }
714 
715 
716 #define TLV_PUT(sctx, attrtype, data, attrlen) \
717 	do { \
718 		ret = tlv_put(sctx, attrtype, data, attrlen); \
719 		if (ret < 0) \
720 			goto tlv_put_failure; \
721 	} while (0)
722 
723 #define TLV_PUT_INT(sctx, attrtype, bits, value) \
724 	do { \
725 		ret = tlv_put_u##bits(sctx, attrtype, value); \
726 		if (ret < 0) \
727 			goto tlv_put_failure; \
728 	} while (0)
729 
730 #define TLV_PUT_U8(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 8, data)
731 #define TLV_PUT_U16(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 16, data)
732 #define TLV_PUT_U32(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 32, data)
733 #define TLV_PUT_U64(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 64, data)
734 #define TLV_PUT_STRING(sctx, attrtype, str, len) \
735 	do { \
736 		ret = tlv_put_string(sctx, attrtype, str, len); \
737 		if (ret < 0) \
738 			goto tlv_put_failure; \
739 	} while (0)
740 #define TLV_PUT_PATH(sctx, attrtype, p) \
741 	do { \
742 		ret = tlv_put_string(sctx, attrtype, p->start, \
743 			p->end - p->start); \
744 		if (ret < 0) \
745 			goto tlv_put_failure; \
746 	} while(0)
747 #define TLV_PUT_UUID(sctx, attrtype, uuid) \
748 	do { \
749 		ret = tlv_put_uuid(sctx, attrtype, uuid); \
750 		if (ret < 0) \
751 			goto tlv_put_failure; \
752 	} while (0)
753 #define TLV_PUT_BTRFS_TIMESPEC(sctx, attrtype, eb, ts) \
754 	do { \
755 		ret = tlv_put_btrfs_timespec(sctx, attrtype, eb, ts); \
756 		if (ret < 0) \
757 			goto tlv_put_failure; \
758 	} while (0)
759 
760 static int send_header(struct send_ctx *sctx)
761 {
762 	struct btrfs_stream_header hdr;
763 
764 	strcpy(hdr.magic, BTRFS_SEND_STREAM_MAGIC);
765 	hdr.version = cpu_to_le32(sctx->proto);
766 	return write_buf(sctx->send_filp, &hdr, sizeof(hdr),
767 					&sctx->send_off);
768 }
769 
770 /*
771  * For each command/item we want to send to userspace, we call this function.
772  */
773 static int begin_cmd(struct send_ctx *sctx, int cmd)
774 {
775 	struct btrfs_cmd_header *hdr;
776 
777 	if (WARN_ON(!sctx->send_buf))
778 		return -EINVAL;
779 
780 	if (unlikely(sctx->send_size != 0)) {
781 		btrfs_err(sctx->send_root->fs_info,
782 			  "send: command header buffer not empty cmd %d offset %llu",
783 			  cmd, sctx->send_off);
784 		return -EINVAL;
785 	}
786 
787 	sctx->send_size += sizeof(*hdr);
788 	hdr = (struct btrfs_cmd_header *)sctx->send_buf;
789 	put_unaligned_le16(cmd, &hdr->cmd);
790 
791 	return 0;
792 }
793 
794 static int send_cmd(struct send_ctx *sctx)
795 {
796 	int ret;
797 	struct btrfs_cmd_header *hdr;
798 	u32 crc;
799 
800 	hdr = (struct btrfs_cmd_header *)sctx->send_buf;
801 	put_unaligned_le32(sctx->send_size - sizeof(*hdr), &hdr->len);
802 	put_unaligned_le32(0, &hdr->crc);
803 
804 	crc = btrfs_crc32c(0, (unsigned char *)sctx->send_buf, sctx->send_size);
805 	put_unaligned_le32(crc, &hdr->crc);
806 
807 	ret = write_buf(sctx->send_filp, sctx->send_buf, sctx->send_size,
808 					&sctx->send_off);
809 
810 	sctx->send_size = 0;
811 	sctx->put_data = false;
812 
813 	return ret;
814 }
815 
816 /*
817  * Sends a move instruction to user space
818  */
819 static int send_rename(struct send_ctx *sctx,
820 		     struct fs_path *from, struct fs_path *to)
821 {
822 	struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
823 	int ret;
824 
825 	btrfs_debug(fs_info, "send_rename %s -> %s", from->start, to->start);
826 
827 	ret = begin_cmd(sctx, BTRFS_SEND_C_RENAME);
828 	if (ret < 0)
829 		goto out;
830 
831 	TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, from);
832 	TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH_TO, to);
833 
834 	ret = send_cmd(sctx);
835 
836 tlv_put_failure:
837 out:
838 	return ret;
839 }
840 
841 /*
842  * Sends a link instruction to user space
843  */
844 static int send_link(struct send_ctx *sctx,
845 		     struct fs_path *path, struct fs_path *lnk)
846 {
847 	struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
848 	int ret;
849 
850 	btrfs_debug(fs_info, "send_link %s -> %s", path->start, lnk->start);
851 
852 	ret = begin_cmd(sctx, BTRFS_SEND_C_LINK);
853 	if (ret < 0)
854 		goto out;
855 
856 	TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
857 	TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH_LINK, lnk);
858 
859 	ret = send_cmd(sctx);
860 
861 tlv_put_failure:
862 out:
863 	return ret;
864 }
865 
866 /*
867  * Sends an unlink instruction to user space
868  */
869 static int send_unlink(struct send_ctx *sctx, struct fs_path *path)
870 {
871 	struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
872 	int ret;
873 
874 	btrfs_debug(fs_info, "send_unlink %s", path->start);
875 
876 	ret = begin_cmd(sctx, BTRFS_SEND_C_UNLINK);
877 	if (ret < 0)
878 		goto out;
879 
880 	TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
881 
882 	ret = send_cmd(sctx);
883 
884 tlv_put_failure:
885 out:
886 	return ret;
887 }
888 
889 /*
890  * Sends a rmdir instruction to user space
891  */
892 static int send_rmdir(struct send_ctx *sctx, struct fs_path *path)
893 {
894 	struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
895 	int ret;
896 
897 	btrfs_debug(fs_info, "send_rmdir %s", path->start);
898 
899 	ret = begin_cmd(sctx, BTRFS_SEND_C_RMDIR);
900 	if (ret < 0)
901 		goto out;
902 
903 	TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
904 
905 	ret = send_cmd(sctx);
906 
907 tlv_put_failure:
908 out:
909 	return ret;
910 }
911 
912 struct btrfs_inode_info {
913 	u64 size;
914 	u64 gen;
915 	u64 mode;
916 	u64 uid;
917 	u64 gid;
918 	u64 rdev;
919 	u64 fileattr;
920 	u64 nlink;
921 };
922 
923 /*
924  * Helper function to retrieve some fields from an inode item.
925  */
926 static int get_inode_info(struct btrfs_root *root, u64 ino,
927 			  struct btrfs_inode_info *info)
928 {
929 	int ret;
930 	struct btrfs_path *path;
931 	struct btrfs_inode_item *ii;
932 	struct btrfs_key key;
933 
934 	path = alloc_path_for_send();
935 	if (!path)
936 		return -ENOMEM;
937 
938 	key.objectid = ino;
939 	key.type = BTRFS_INODE_ITEM_KEY;
940 	key.offset = 0;
941 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
942 	if (ret) {
943 		if (ret > 0)
944 			ret = -ENOENT;
945 		goto out;
946 	}
947 
948 	if (!info)
949 		goto out;
950 
951 	ii = btrfs_item_ptr(path->nodes[0], path->slots[0],
952 			struct btrfs_inode_item);
953 	info->size = btrfs_inode_size(path->nodes[0], ii);
954 	info->gen = btrfs_inode_generation(path->nodes[0], ii);
955 	info->mode = btrfs_inode_mode(path->nodes[0], ii);
956 	info->uid = btrfs_inode_uid(path->nodes[0], ii);
957 	info->gid = btrfs_inode_gid(path->nodes[0], ii);
958 	info->rdev = btrfs_inode_rdev(path->nodes[0], ii);
959 	info->nlink = btrfs_inode_nlink(path->nodes[0], ii);
960 	/*
961 	 * Transfer the unchanged u64 value of btrfs_inode_item::flags, that's
962 	 * otherwise logically split to 32/32 parts.
963 	 */
964 	info->fileattr = btrfs_inode_flags(path->nodes[0], ii);
965 
966 out:
967 	btrfs_free_path(path);
968 	return ret;
969 }
970 
971 static int get_inode_gen(struct btrfs_root *root, u64 ino, u64 *gen)
972 {
973 	int ret;
974 	struct btrfs_inode_info info = { 0 };
975 
976 	ASSERT(gen);
977 
978 	ret = get_inode_info(root, ino, &info);
979 	*gen = info.gen;
980 	return ret;
981 }
982 
983 typedef int (*iterate_inode_ref_t)(int num, u64 dir, int index,
984 				   struct fs_path *p,
985 				   void *ctx);
986 
987 /*
988  * Helper function to iterate the entries in ONE btrfs_inode_ref or
989  * btrfs_inode_extref.
990  * The iterate callback may return a non zero value to stop iteration. This can
991  * be a negative value for error codes or 1 to simply stop it.
992  *
993  * path must point to the INODE_REF or INODE_EXTREF when called.
994  */
995 static int iterate_inode_ref(struct btrfs_root *root, struct btrfs_path *path,
996 			     struct btrfs_key *found_key, int resolve,
997 			     iterate_inode_ref_t iterate, void *ctx)
998 {
999 	struct extent_buffer *eb = path->nodes[0];
1000 	struct btrfs_inode_ref *iref;
1001 	struct btrfs_inode_extref *extref;
1002 	struct btrfs_path *tmp_path;
1003 	struct fs_path *p;
1004 	u32 cur = 0;
1005 	u32 total;
1006 	int slot = path->slots[0];
1007 	u32 name_len;
1008 	char *start;
1009 	int ret = 0;
1010 	int num = 0;
1011 	int index;
1012 	u64 dir;
1013 	unsigned long name_off;
1014 	unsigned long elem_size;
1015 	unsigned long ptr;
1016 
1017 	p = fs_path_alloc_reversed();
1018 	if (!p)
1019 		return -ENOMEM;
1020 
1021 	tmp_path = alloc_path_for_send();
1022 	if (!tmp_path) {
1023 		fs_path_free(p);
1024 		return -ENOMEM;
1025 	}
1026 
1027 
1028 	if (found_key->type == BTRFS_INODE_REF_KEY) {
1029 		ptr = (unsigned long)btrfs_item_ptr(eb, slot,
1030 						    struct btrfs_inode_ref);
1031 		total = btrfs_item_size(eb, slot);
1032 		elem_size = sizeof(*iref);
1033 	} else {
1034 		ptr = btrfs_item_ptr_offset(eb, slot);
1035 		total = btrfs_item_size(eb, slot);
1036 		elem_size = sizeof(*extref);
1037 	}
1038 
1039 	while (cur < total) {
1040 		fs_path_reset(p);
1041 
1042 		if (found_key->type == BTRFS_INODE_REF_KEY) {
1043 			iref = (struct btrfs_inode_ref *)(ptr + cur);
1044 			name_len = btrfs_inode_ref_name_len(eb, iref);
1045 			name_off = (unsigned long)(iref + 1);
1046 			index = btrfs_inode_ref_index(eb, iref);
1047 			dir = found_key->offset;
1048 		} else {
1049 			extref = (struct btrfs_inode_extref *)(ptr + cur);
1050 			name_len = btrfs_inode_extref_name_len(eb, extref);
1051 			name_off = (unsigned long)&extref->name;
1052 			index = btrfs_inode_extref_index(eb, extref);
1053 			dir = btrfs_inode_extref_parent(eb, extref);
1054 		}
1055 
1056 		if (resolve) {
1057 			start = btrfs_ref_to_path(root, tmp_path, name_len,
1058 						  name_off, eb, dir,
1059 						  p->buf, p->buf_len);
1060 			if (IS_ERR(start)) {
1061 				ret = PTR_ERR(start);
1062 				goto out;
1063 			}
1064 			if (start < p->buf) {
1065 				/* overflow , try again with larger buffer */
1066 				ret = fs_path_ensure_buf(p,
1067 						p->buf_len + p->buf - start);
1068 				if (ret < 0)
1069 					goto out;
1070 				start = btrfs_ref_to_path(root, tmp_path,
1071 							  name_len, name_off,
1072 							  eb, dir,
1073 							  p->buf, p->buf_len);
1074 				if (IS_ERR(start)) {
1075 					ret = PTR_ERR(start);
1076 					goto out;
1077 				}
1078 				if (unlikely(start < p->buf)) {
1079 					btrfs_err(root->fs_info,
1080 			"send: path ref buffer underflow for key (%llu %u %llu)",
1081 						  found_key->objectid,
1082 						  found_key->type,
1083 						  found_key->offset);
1084 					ret = -EINVAL;
1085 					goto out;
1086 				}
1087 			}
1088 			p->start = start;
1089 		} else {
1090 			ret = fs_path_add_from_extent_buffer(p, eb, name_off,
1091 							     name_len);
1092 			if (ret < 0)
1093 				goto out;
1094 		}
1095 
1096 		cur += elem_size + name_len;
1097 		ret = iterate(num, dir, index, p, ctx);
1098 		if (ret)
1099 			goto out;
1100 		num++;
1101 	}
1102 
1103 out:
1104 	btrfs_free_path(tmp_path);
1105 	fs_path_free(p);
1106 	return ret;
1107 }
1108 
1109 typedef int (*iterate_dir_item_t)(int num, struct btrfs_key *di_key,
1110 				  const char *name, int name_len,
1111 				  const char *data, int data_len,
1112 				  void *ctx);
1113 
1114 /*
1115  * Helper function to iterate the entries in ONE btrfs_dir_item.
1116  * The iterate callback may return a non zero value to stop iteration. This can
1117  * be a negative value for error codes or 1 to simply stop it.
1118  *
1119  * path must point to the dir item when called.
1120  */
1121 static int iterate_dir_item(struct btrfs_root *root, struct btrfs_path *path,
1122 			    iterate_dir_item_t iterate, void *ctx)
1123 {
1124 	int ret = 0;
1125 	struct extent_buffer *eb;
1126 	struct btrfs_dir_item *di;
1127 	struct btrfs_key di_key;
1128 	char *buf = NULL;
1129 	int buf_len;
1130 	u32 name_len;
1131 	u32 data_len;
1132 	u32 cur;
1133 	u32 len;
1134 	u32 total;
1135 	int slot;
1136 	int num;
1137 
1138 	/*
1139 	 * Start with a small buffer (1 page). If later we end up needing more
1140 	 * space, which can happen for xattrs on a fs with a leaf size greater
1141 	 * then the page size, attempt to increase the buffer. Typically xattr
1142 	 * values are small.
1143 	 */
1144 	buf_len = PATH_MAX;
1145 	buf = kmalloc(buf_len, GFP_KERNEL);
1146 	if (!buf) {
1147 		ret = -ENOMEM;
1148 		goto out;
1149 	}
1150 
1151 	eb = path->nodes[0];
1152 	slot = path->slots[0];
1153 	di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
1154 	cur = 0;
1155 	len = 0;
1156 	total = btrfs_item_size(eb, slot);
1157 
1158 	num = 0;
1159 	while (cur < total) {
1160 		name_len = btrfs_dir_name_len(eb, di);
1161 		data_len = btrfs_dir_data_len(eb, di);
1162 		btrfs_dir_item_key_to_cpu(eb, di, &di_key);
1163 
1164 		if (btrfs_dir_ftype(eb, di) == BTRFS_FT_XATTR) {
1165 			if (name_len > XATTR_NAME_MAX) {
1166 				ret = -ENAMETOOLONG;
1167 				goto out;
1168 			}
1169 			if (name_len + data_len >
1170 					BTRFS_MAX_XATTR_SIZE(root->fs_info)) {
1171 				ret = -E2BIG;
1172 				goto out;
1173 			}
1174 		} else {
1175 			/*
1176 			 * Path too long
1177 			 */
1178 			if (name_len + data_len > PATH_MAX) {
1179 				ret = -ENAMETOOLONG;
1180 				goto out;
1181 			}
1182 		}
1183 
1184 		if (name_len + data_len > buf_len) {
1185 			buf_len = name_len + data_len;
1186 			if (is_vmalloc_addr(buf)) {
1187 				vfree(buf);
1188 				buf = NULL;
1189 			} else {
1190 				char *tmp = krealloc(buf, buf_len,
1191 						GFP_KERNEL | __GFP_NOWARN);
1192 
1193 				if (!tmp)
1194 					kfree(buf);
1195 				buf = tmp;
1196 			}
1197 			if (!buf) {
1198 				buf = kvmalloc(buf_len, GFP_KERNEL);
1199 				if (!buf) {
1200 					ret = -ENOMEM;
1201 					goto out;
1202 				}
1203 			}
1204 		}
1205 
1206 		read_extent_buffer(eb, buf, (unsigned long)(di + 1),
1207 				name_len + data_len);
1208 
1209 		len = sizeof(*di) + name_len + data_len;
1210 		di = (struct btrfs_dir_item *)((char *)di + len);
1211 		cur += len;
1212 
1213 		ret = iterate(num, &di_key, buf, name_len, buf + name_len,
1214 			      data_len, ctx);
1215 		if (ret < 0)
1216 			goto out;
1217 		if (ret) {
1218 			ret = 0;
1219 			goto out;
1220 		}
1221 
1222 		num++;
1223 	}
1224 
1225 out:
1226 	kvfree(buf);
1227 	return ret;
1228 }
1229 
1230 static int __copy_first_ref(int num, u64 dir, int index,
1231 			    struct fs_path *p, void *ctx)
1232 {
1233 	int ret;
1234 	struct fs_path *pt = ctx;
1235 
1236 	ret = fs_path_copy(pt, p);
1237 	if (ret < 0)
1238 		return ret;
1239 
1240 	/* we want the first only */
1241 	return 1;
1242 }
1243 
1244 /*
1245  * Retrieve the first path of an inode. If an inode has more then one
1246  * ref/hardlink, this is ignored.
1247  */
1248 static int get_inode_path(struct btrfs_root *root,
1249 			  u64 ino, struct fs_path *path)
1250 {
1251 	int ret;
1252 	struct btrfs_key key, found_key;
1253 	struct btrfs_path *p;
1254 
1255 	p = alloc_path_for_send();
1256 	if (!p)
1257 		return -ENOMEM;
1258 
1259 	fs_path_reset(path);
1260 
1261 	key.objectid = ino;
1262 	key.type = BTRFS_INODE_REF_KEY;
1263 	key.offset = 0;
1264 
1265 	ret = btrfs_search_slot_for_read(root, &key, p, 1, 0);
1266 	if (ret < 0)
1267 		goto out;
1268 	if (ret) {
1269 		ret = 1;
1270 		goto out;
1271 	}
1272 	btrfs_item_key_to_cpu(p->nodes[0], &found_key, p->slots[0]);
1273 	if (found_key.objectid != ino ||
1274 	    (found_key.type != BTRFS_INODE_REF_KEY &&
1275 	     found_key.type != BTRFS_INODE_EXTREF_KEY)) {
1276 		ret = -ENOENT;
1277 		goto out;
1278 	}
1279 
1280 	ret = iterate_inode_ref(root, p, &found_key, 1,
1281 				__copy_first_ref, path);
1282 	if (ret < 0)
1283 		goto out;
1284 	ret = 0;
1285 
1286 out:
1287 	btrfs_free_path(p);
1288 	return ret;
1289 }
1290 
1291 struct backref_ctx {
1292 	struct send_ctx *sctx;
1293 
1294 	/* number of total found references */
1295 	u64 found;
1296 
1297 	/*
1298 	 * used for clones found in send_root. clones found behind cur_objectid
1299 	 * and cur_offset are not considered as allowed clones.
1300 	 */
1301 	u64 cur_objectid;
1302 	u64 cur_offset;
1303 
1304 	/* may be truncated in case it's the last extent in a file */
1305 	u64 extent_len;
1306 
1307 	/* The bytenr the file extent item we are processing refers to. */
1308 	u64 bytenr;
1309 	/* The owner (root id) of the data backref for the current extent. */
1310 	u64 backref_owner;
1311 	/* The offset of the data backref for the current extent. */
1312 	u64 backref_offset;
1313 };
1314 
1315 static int __clone_root_cmp_bsearch(const void *key, const void *elt)
1316 {
1317 	u64 root = (u64)(uintptr_t)key;
1318 	const struct clone_root *cr = elt;
1319 
1320 	if (root < cr->root->root_key.objectid)
1321 		return -1;
1322 	if (root > cr->root->root_key.objectid)
1323 		return 1;
1324 	return 0;
1325 }
1326 
1327 static int __clone_root_cmp_sort(const void *e1, const void *e2)
1328 {
1329 	const struct clone_root *cr1 = e1;
1330 	const struct clone_root *cr2 = e2;
1331 
1332 	if (cr1->root->root_key.objectid < cr2->root->root_key.objectid)
1333 		return -1;
1334 	if (cr1->root->root_key.objectid > cr2->root->root_key.objectid)
1335 		return 1;
1336 	return 0;
1337 }
1338 
1339 /*
1340  * Called for every backref that is found for the current extent.
1341  * Results are collected in sctx->clone_roots->ino/offset.
1342  */
1343 static int iterate_backrefs(u64 ino, u64 offset, u64 num_bytes, u64 root_id,
1344 			    void *ctx_)
1345 {
1346 	struct backref_ctx *bctx = ctx_;
1347 	struct clone_root *clone_root;
1348 
1349 	/* First check if the root is in the list of accepted clone sources */
1350 	clone_root = bsearch((void *)(uintptr_t)root_id, bctx->sctx->clone_roots,
1351 			     bctx->sctx->clone_roots_cnt,
1352 			     sizeof(struct clone_root),
1353 			     __clone_root_cmp_bsearch);
1354 	if (!clone_root)
1355 		return 0;
1356 
1357 	/* This is our own reference, bail out as we can't clone from it. */
1358 	if (clone_root->root == bctx->sctx->send_root &&
1359 	    ino == bctx->cur_objectid &&
1360 	    offset == bctx->cur_offset)
1361 		return 0;
1362 
1363 	/*
1364 	 * Make sure we don't consider clones from send_root that are
1365 	 * behind the current inode/offset.
1366 	 */
1367 	if (clone_root->root == bctx->sctx->send_root) {
1368 		/*
1369 		 * If the source inode was not yet processed we can't issue a
1370 		 * clone operation, as the source extent does not exist yet at
1371 		 * the destination of the stream.
1372 		 */
1373 		if (ino > bctx->cur_objectid)
1374 			return 0;
1375 		/*
1376 		 * We clone from the inode currently being sent as long as the
1377 		 * source extent is already processed, otherwise we could try
1378 		 * to clone from an extent that does not exist yet at the
1379 		 * destination of the stream.
1380 		 */
1381 		if (ino == bctx->cur_objectid &&
1382 		    offset + bctx->extent_len >
1383 		    bctx->sctx->cur_inode_next_write_offset)
1384 			return 0;
1385 	}
1386 
1387 	bctx->found++;
1388 	clone_root->found_ref = true;
1389 
1390 	/*
1391 	 * If the given backref refers to a file extent item with a larger
1392 	 * number of bytes than what we found before, use the new one so that
1393 	 * we clone more optimally and end up doing less writes and getting
1394 	 * less exclusive, non-shared extents at the destination.
1395 	 */
1396 	if (num_bytes > clone_root->num_bytes) {
1397 		clone_root->ino = ino;
1398 		clone_root->offset = offset;
1399 		clone_root->num_bytes = num_bytes;
1400 
1401 		/*
1402 		 * Found a perfect candidate, so there's no need to continue
1403 		 * backref walking.
1404 		 */
1405 		if (num_bytes >= bctx->extent_len)
1406 			return BTRFS_ITERATE_EXTENT_INODES_STOP;
1407 	}
1408 
1409 	return 0;
1410 }
1411 
1412 static bool lookup_backref_cache(u64 leaf_bytenr, void *ctx,
1413 				 const u64 **root_ids_ret, int *root_count_ret)
1414 {
1415 	struct backref_ctx *bctx = ctx;
1416 	struct send_ctx *sctx = bctx->sctx;
1417 	struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
1418 	const u64 key = leaf_bytenr >> fs_info->sectorsize_bits;
1419 	struct btrfs_lru_cache_entry *raw_entry;
1420 	struct backref_cache_entry *entry;
1421 
1422 	if (btrfs_lru_cache_size(&sctx->backref_cache) == 0)
1423 		return false;
1424 
1425 	/*
1426 	 * If relocation happened since we first filled the cache, then we must
1427 	 * empty the cache and can not use it, because even though we operate on
1428 	 * read-only roots, their leaves and nodes may have been reallocated and
1429 	 * now be used for different nodes/leaves of the same tree or some other
1430 	 * tree.
1431 	 *
1432 	 * We are called from iterate_extent_inodes() while either holding a
1433 	 * transaction handle or holding fs_info->commit_root_sem, so no need
1434 	 * to take any lock here.
1435 	 */
1436 	if (fs_info->last_reloc_trans > sctx->backref_cache_last_reloc_trans) {
1437 		btrfs_lru_cache_clear(&sctx->backref_cache);
1438 		return false;
1439 	}
1440 
1441 	raw_entry = btrfs_lru_cache_lookup(&sctx->backref_cache, key, 0);
1442 	if (!raw_entry)
1443 		return false;
1444 
1445 	entry = container_of(raw_entry, struct backref_cache_entry, entry);
1446 	*root_ids_ret = entry->root_ids;
1447 	*root_count_ret = entry->num_roots;
1448 
1449 	return true;
1450 }
1451 
1452 static void store_backref_cache(u64 leaf_bytenr, const struct ulist *root_ids,
1453 				void *ctx)
1454 {
1455 	struct backref_ctx *bctx = ctx;
1456 	struct send_ctx *sctx = bctx->sctx;
1457 	struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
1458 	struct backref_cache_entry *new_entry;
1459 	struct ulist_iterator uiter;
1460 	struct ulist_node *node;
1461 	int ret;
1462 
1463 	/*
1464 	 * We're called while holding a transaction handle or while holding
1465 	 * fs_info->commit_root_sem (at iterate_extent_inodes()), so must do a
1466 	 * NOFS allocation.
1467 	 */
1468 	new_entry = kmalloc(sizeof(struct backref_cache_entry), GFP_NOFS);
1469 	/* No worries, cache is optional. */
1470 	if (!new_entry)
1471 		return;
1472 
1473 	new_entry->entry.key = leaf_bytenr >> fs_info->sectorsize_bits;
1474 	new_entry->entry.gen = 0;
1475 	new_entry->num_roots = 0;
1476 	ULIST_ITER_INIT(&uiter);
1477 	while ((node = ulist_next(root_ids, &uiter)) != NULL) {
1478 		const u64 root_id = node->val;
1479 		struct clone_root *root;
1480 
1481 		root = bsearch((void *)(uintptr_t)root_id, sctx->clone_roots,
1482 			       sctx->clone_roots_cnt, sizeof(struct clone_root),
1483 			       __clone_root_cmp_bsearch);
1484 		if (!root)
1485 			continue;
1486 
1487 		/* Too many roots, just exit, no worries as caching is optional. */
1488 		if (new_entry->num_roots >= SEND_MAX_BACKREF_CACHE_ROOTS) {
1489 			kfree(new_entry);
1490 			return;
1491 		}
1492 
1493 		new_entry->root_ids[new_entry->num_roots] = root_id;
1494 		new_entry->num_roots++;
1495 	}
1496 
1497 	/*
1498 	 * We may have not added any roots to the new cache entry, which means
1499 	 * none of the roots is part of the list of roots from which we are
1500 	 * allowed to clone. Cache the new entry as it's still useful to avoid
1501 	 * backref walking to determine which roots have a path to the leaf.
1502 	 *
1503 	 * Also use GFP_NOFS because we're called while holding a transaction
1504 	 * handle or while holding fs_info->commit_root_sem.
1505 	 */
1506 	ret = btrfs_lru_cache_store(&sctx->backref_cache, &new_entry->entry,
1507 				    GFP_NOFS);
1508 	ASSERT(ret == 0 || ret == -ENOMEM);
1509 	if (ret) {
1510 		/* Caching is optional, no worries. */
1511 		kfree(new_entry);
1512 		return;
1513 	}
1514 
1515 	/*
1516 	 * We are called from iterate_extent_inodes() while either holding a
1517 	 * transaction handle or holding fs_info->commit_root_sem, so no need
1518 	 * to take any lock here.
1519 	 */
1520 	if (btrfs_lru_cache_size(&sctx->backref_cache) == 1)
1521 		sctx->backref_cache_last_reloc_trans = fs_info->last_reloc_trans;
1522 }
1523 
1524 static int check_extent_item(u64 bytenr, const struct btrfs_extent_item *ei,
1525 			     const struct extent_buffer *leaf, void *ctx)
1526 {
1527 	const u64 refs = btrfs_extent_refs(leaf, ei);
1528 	const struct backref_ctx *bctx = ctx;
1529 	const struct send_ctx *sctx = bctx->sctx;
1530 
1531 	if (bytenr == bctx->bytenr) {
1532 		const u64 flags = btrfs_extent_flags(leaf, ei);
1533 
1534 		if (WARN_ON(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK))
1535 			return -EUCLEAN;
1536 
1537 		/*
1538 		 * If we have only one reference and only the send root as a
1539 		 * clone source - meaning no clone roots were given in the
1540 		 * struct btrfs_ioctl_send_args passed to the send ioctl - then
1541 		 * it's our reference and there's no point in doing backref
1542 		 * walking which is expensive, so exit early.
1543 		 */
1544 		if (refs == 1 && sctx->clone_roots_cnt == 1)
1545 			return -ENOENT;
1546 	}
1547 
1548 	/*
1549 	 * Backreference walking (iterate_extent_inodes() below) is currently
1550 	 * too expensive when an extent has a large number of references, both
1551 	 * in time spent and used memory. So for now just fallback to write
1552 	 * operations instead of clone operations when an extent has more than
1553 	 * a certain amount of references.
1554 	 */
1555 	if (refs > SEND_MAX_EXTENT_REFS)
1556 		return -ENOENT;
1557 
1558 	return 0;
1559 }
1560 
1561 static bool skip_self_data_ref(u64 root, u64 ino, u64 offset, void *ctx)
1562 {
1563 	const struct backref_ctx *bctx = ctx;
1564 
1565 	if (ino == bctx->cur_objectid &&
1566 	    root == bctx->backref_owner &&
1567 	    offset == bctx->backref_offset)
1568 		return true;
1569 
1570 	return false;
1571 }
1572 
1573 /*
1574  * Given an inode, offset and extent item, it finds a good clone for a clone
1575  * instruction. Returns -ENOENT when none could be found. The function makes
1576  * sure that the returned clone is usable at the point where sending is at the
1577  * moment. This means, that no clones are accepted which lie behind the current
1578  * inode+offset.
1579  *
1580  * path must point to the extent item when called.
1581  */
1582 static int find_extent_clone(struct send_ctx *sctx,
1583 			     struct btrfs_path *path,
1584 			     u64 ino, u64 data_offset,
1585 			     u64 ino_size,
1586 			     struct clone_root **found)
1587 {
1588 	struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
1589 	int ret;
1590 	int extent_type;
1591 	u64 logical;
1592 	u64 disk_byte;
1593 	u64 num_bytes;
1594 	struct btrfs_file_extent_item *fi;
1595 	struct extent_buffer *eb = path->nodes[0];
1596 	struct backref_ctx backref_ctx = { 0 };
1597 	struct btrfs_backref_walk_ctx backref_walk_ctx = { 0 };
1598 	struct clone_root *cur_clone_root;
1599 	int compressed;
1600 	u32 i;
1601 
1602 	/*
1603 	 * With fallocate we can get prealloc extents beyond the inode's i_size,
1604 	 * so we don't do anything here because clone operations can not clone
1605 	 * to a range beyond i_size without increasing the i_size of the
1606 	 * destination inode.
1607 	 */
1608 	if (data_offset >= ino_size)
1609 		return 0;
1610 
1611 	fi = btrfs_item_ptr(eb, path->slots[0], struct btrfs_file_extent_item);
1612 	extent_type = btrfs_file_extent_type(eb, fi);
1613 	if (extent_type == BTRFS_FILE_EXTENT_INLINE)
1614 		return -ENOENT;
1615 
1616 	disk_byte = btrfs_file_extent_disk_bytenr(eb, fi);
1617 	if (disk_byte == 0)
1618 		return -ENOENT;
1619 
1620 	compressed = btrfs_file_extent_compression(eb, fi);
1621 	num_bytes = btrfs_file_extent_num_bytes(eb, fi);
1622 	logical = disk_byte + btrfs_file_extent_offset(eb, fi);
1623 
1624 	/*
1625 	 * Setup the clone roots.
1626 	 */
1627 	for (i = 0; i < sctx->clone_roots_cnt; i++) {
1628 		cur_clone_root = sctx->clone_roots + i;
1629 		cur_clone_root->ino = (u64)-1;
1630 		cur_clone_root->offset = 0;
1631 		cur_clone_root->num_bytes = 0;
1632 		cur_clone_root->found_ref = false;
1633 	}
1634 
1635 	backref_ctx.sctx = sctx;
1636 	backref_ctx.cur_objectid = ino;
1637 	backref_ctx.cur_offset = data_offset;
1638 	backref_ctx.bytenr = disk_byte;
1639 	/*
1640 	 * Use the header owner and not the send root's id, because in case of a
1641 	 * snapshot we can have shared subtrees.
1642 	 */
1643 	backref_ctx.backref_owner = btrfs_header_owner(eb);
1644 	backref_ctx.backref_offset = data_offset - btrfs_file_extent_offset(eb, fi);
1645 
1646 	/*
1647 	 * The last extent of a file may be too large due to page alignment.
1648 	 * We need to adjust extent_len in this case so that the checks in
1649 	 * iterate_backrefs() work.
1650 	 */
1651 	if (data_offset + num_bytes >= ino_size)
1652 		backref_ctx.extent_len = ino_size - data_offset;
1653 	else
1654 		backref_ctx.extent_len = num_bytes;
1655 
1656 	/*
1657 	 * Now collect all backrefs.
1658 	 */
1659 	backref_walk_ctx.bytenr = disk_byte;
1660 	if (compressed == BTRFS_COMPRESS_NONE)
1661 		backref_walk_ctx.extent_item_pos = btrfs_file_extent_offset(eb, fi);
1662 	backref_walk_ctx.fs_info = fs_info;
1663 	backref_walk_ctx.cache_lookup = lookup_backref_cache;
1664 	backref_walk_ctx.cache_store = store_backref_cache;
1665 	backref_walk_ctx.indirect_ref_iterator = iterate_backrefs;
1666 	backref_walk_ctx.check_extent_item = check_extent_item;
1667 	backref_walk_ctx.user_ctx = &backref_ctx;
1668 
1669 	/*
1670 	 * If have a single clone root, then it's the send root and we can tell
1671 	 * the backref walking code to skip our own backref and not resolve it,
1672 	 * since we can not use it for cloning - the source and destination
1673 	 * ranges can't overlap and in case the leaf is shared through a subtree
1674 	 * due to snapshots, we can't use those other roots since they are not
1675 	 * in the list of clone roots.
1676 	 */
1677 	if (sctx->clone_roots_cnt == 1)
1678 		backref_walk_ctx.skip_data_ref = skip_self_data_ref;
1679 
1680 	ret = iterate_extent_inodes(&backref_walk_ctx, true, iterate_backrefs,
1681 				    &backref_ctx);
1682 	if (ret < 0)
1683 		return ret;
1684 
1685 	down_read(&fs_info->commit_root_sem);
1686 	if (fs_info->last_reloc_trans > sctx->last_reloc_trans) {
1687 		/*
1688 		 * A transaction commit for a transaction in which block group
1689 		 * relocation was done just happened.
1690 		 * The disk_bytenr of the file extent item we processed is
1691 		 * possibly stale, referring to the extent's location before
1692 		 * relocation. So act as if we haven't found any clone sources
1693 		 * and fallback to write commands, which will read the correct
1694 		 * data from the new extent location. Otherwise we will fail
1695 		 * below because we haven't found our own back reference or we
1696 		 * could be getting incorrect sources in case the old extent
1697 		 * was already reallocated after the relocation.
1698 		 */
1699 		up_read(&fs_info->commit_root_sem);
1700 		return -ENOENT;
1701 	}
1702 	up_read(&fs_info->commit_root_sem);
1703 
1704 	btrfs_debug(fs_info,
1705 		    "find_extent_clone: data_offset=%llu, ino=%llu, num_bytes=%llu, logical=%llu",
1706 		    data_offset, ino, num_bytes, logical);
1707 
1708 	if (!backref_ctx.found) {
1709 		btrfs_debug(fs_info, "no clones found");
1710 		return -ENOENT;
1711 	}
1712 
1713 	cur_clone_root = NULL;
1714 	for (i = 0; i < sctx->clone_roots_cnt; i++) {
1715 		struct clone_root *clone_root = &sctx->clone_roots[i];
1716 
1717 		if (!clone_root->found_ref)
1718 			continue;
1719 
1720 		/*
1721 		 * Choose the root from which we can clone more bytes, to
1722 		 * minimize write operations and therefore have more extent
1723 		 * sharing at the destination (the same as in the source).
1724 		 */
1725 		if (!cur_clone_root ||
1726 		    clone_root->num_bytes > cur_clone_root->num_bytes) {
1727 			cur_clone_root = clone_root;
1728 
1729 			/*
1730 			 * We found an optimal clone candidate (any inode from
1731 			 * any root is fine), so we're done.
1732 			 */
1733 			if (clone_root->num_bytes >= backref_ctx.extent_len)
1734 				break;
1735 		}
1736 	}
1737 
1738 	if (cur_clone_root) {
1739 		*found = cur_clone_root;
1740 		ret = 0;
1741 	} else {
1742 		ret = -ENOENT;
1743 	}
1744 
1745 	return ret;
1746 }
1747 
1748 static int read_symlink(struct btrfs_root *root,
1749 			u64 ino,
1750 			struct fs_path *dest)
1751 {
1752 	int ret;
1753 	struct btrfs_path *path;
1754 	struct btrfs_key key;
1755 	struct btrfs_file_extent_item *ei;
1756 	u8 type;
1757 	u8 compression;
1758 	unsigned long off;
1759 	int len;
1760 
1761 	path = alloc_path_for_send();
1762 	if (!path)
1763 		return -ENOMEM;
1764 
1765 	key.objectid = ino;
1766 	key.type = BTRFS_EXTENT_DATA_KEY;
1767 	key.offset = 0;
1768 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1769 	if (ret < 0)
1770 		goto out;
1771 	if (ret) {
1772 		/*
1773 		 * An empty symlink inode. Can happen in rare error paths when
1774 		 * creating a symlink (transaction committed before the inode
1775 		 * eviction handler removed the symlink inode items and a crash
1776 		 * happened in between or the subvol was snapshoted in between).
1777 		 * Print an informative message to dmesg/syslog so that the user
1778 		 * can delete the symlink.
1779 		 */
1780 		btrfs_err(root->fs_info,
1781 			  "Found empty symlink inode %llu at root %llu",
1782 			  ino, root->root_key.objectid);
1783 		ret = -EIO;
1784 		goto out;
1785 	}
1786 
1787 	ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
1788 			struct btrfs_file_extent_item);
1789 	type = btrfs_file_extent_type(path->nodes[0], ei);
1790 	if (unlikely(type != BTRFS_FILE_EXTENT_INLINE)) {
1791 		ret = -EUCLEAN;
1792 		btrfs_crit(root->fs_info,
1793 "send: found symlink extent that is not inline, ino %llu root %llu extent type %d",
1794 			   ino, btrfs_root_id(root), type);
1795 		goto out;
1796 	}
1797 	compression = btrfs_file_extent_compression(path->nodes[0], ei);
1798 	if (unlikely(compression != BTRFS_COMPRESS_NONE)) {
1799 		ret = -EUCLEAN;
1800 		btrfs_crit(root->fs_info,
1801 "send: found symlink extent with compression, ino %llu root %llu compression type %d",
1802 			   ino, btrfs_root_id(root), compression);
1803 		goto out;
1804 	}
1805 
1806 	off = btrfs_file_extent_inline_start(ei);
1807 	len = btrfs_file_extent_ram_bytes(path->nodes[0], ei);
1808 
1809 	ret = fs_path_add_from_extent_buffer(dest, path->nodes[0], off, len);
1810 
1811 out:
1812 	btrfs_free_path(path);
1813 	return ret;
1814 }
1815 
1816 /*
1817  * Helper function to generate a file name that is unique in the root of
1818  * send_root and parent_root. This is used to generate names for orphan inodes.
1819  */
1820 static int gen_unique_name(struct send_ctx *sctx,
1821 			   u64 ino, u64 gen,
1822 			   struct fs_path *dest)
1823 {
1824 	int ret = 0;
1825 	struct btrfs_path *path;
1826 	struct btrfs_dir_item *di;
1827 	char tmp[64];
1828 	int len;
1829 	u64 idx = 0;
1830 
1831 	path = alloc_path_for_send();
1832 	if (!path)
1833 		return -ENOMEM;
1834 
1835 	while (1) {
1836 		struct fscrypt_str tmp_name;
1837 
1838 		len = snprintf(tmp, sizeof(tmp), "o%llu-%llu-%llu",
1839 				ino, gen, idx);
1840 		ASSERT(len < sizeof(tmp));
1841 		tmp_name.name = tmp;
1842 		tmp_name.len = strlen(tmp);
1843 
1844 		di = btrfs_lookup_dir_item(NULL, sctx->send_root,
1845 				path, BTRFS_FIRST_FREE_OBJECTID,
1846 				&tmp_name, 0);
1847 		btrfs_release_path(path);
1848 		if (IS_ERR(di)) {
1849 			ret = PTR_ERR(di);
1850 			goto out;
1851 		}
1852 		if (di) {
1853 			/* not unique, try again */
1854 			idx++;
1855 			continue;
1856 		}
1857 
1858 		if (!sctx->parent_root) {
1859 			/* unique */
1860 			ret = 0;
1861 			break;
1862 		}
1863 
1864 		di = btrfs_lookup_dir_item(NULL, sctx->parent_root,
1865 				path, BTRFS_FIRST_FREE_OBJECTID,
1866 				&tmp_name, 0);
1867 		btrfs_release_path(path);
1868 		if (IS_ERR(di)) {
1869 			ret = PTR_ERR(di);
1870 			goto out;
1871 		}
1872 		if (di) {
1873 			/* not unique, try again */
1874 			idx++;
1875 			continue;
1876 		}
1877 		/* unique */
1878 		break;
1879 	}
1880 
1881 	ret = fs_path_add(dest, tmp, strlen(tmp));
1882 
1883 out:
1884 	btrfs_free_path(path);
1885 	return ret;
1886 }
1887 
1888 enum inode_state {
1889 	inode_state_no_change,
1890 	inode_state_will_create,
1891 	inode_state_did_create,
1892 	inode_state_will_delete,
1893 	inode_state_did_delete,
1894 };
1895 
1896 static int get_cur_inode_state(struct send_ctx *sctx, u64 ino, u64 gen,
1897 			       u64 *send_gen, u64 *parent_gen)
1898 {
1899 	int ret;
1900 	int left_ret;
1901 	int right_ret;
1902 	u64 left_gen;
1903 	u64 right_gen = 0;
1904 	struct btrfs_inode_info info;
1905 
1906 	ret = get_inode_info(sctx->send_root, ino, &info);
1907 	if (ret < 0 && ret != -ENOENT)
1908 		goto out;
1909 	left_ret = (info.nlink == 0) ? -ENOENT : ret;
1910 	left_gen = info.gen;
1911 	if (send_gen)
1912 		*send_gen = ((left_ret == -ENOENT) ? 0 : info.gen);
1913 
1914 	if (!sctx->parent_root) {
1915 		right_ret = -ENOENT;
1916 	} else {
1917 		ret = get_inode_info(sctx->parent_root, ino, &info);
1918 		if (ret < 0 && ret != -ENOENT)
1919 			goto out;
1920 		right_ret = (info.nlink == 0) ? -ENOENT : ret;
1921 		right_gen = info.gen;
1922 		if (parent_gen)
1923 			*parent_gen = ((right_ret == -ENOENT) ? 0 : info.gen);
1924 	}
1925 
1926 	if (!left_ret && !right_ret) {
1927 		if (left_gen == gen && right_gen == gen) {
1928 			ret = inode_state_no_change;
1929 		} else if (left_gen == gen) {
1930 			if (ino < sctx->send_progress)
1931 				ret = inode_state_did_create;
1932 			else
1933 				ret = inode_state_will_create;
1934 		} else if (right_gen == gen) {
1935 			if (ino < sctx->send_progress)
1936 				ret = inode_state_did_delete;
1937 			else
1938 				ret = inode_state_will_delete;
1939 		} else  {
1940 			ret = -ENOENT;
1941 		}
1942 	} else if (!left_ret) {
1943 		if (left_gen == gen) {
1944 			if (ino < sctx->send_progress)
1945 				ret = inode_state_did_create;
1946 			else
1947 				ret = inode_state_will_create;
1948 		} else {
1949 			ret = -ENOENT;
1950 		}
1951 	} else if (!right_ret) {
1952 		if (right_gen == gen) {
1953 			if (ino < sctx->send_progress)
1954 				ret = inode_state_did_delete;
1955 			else
1956 				ret = inode_state_will_delete;
1957 		} else {
1958 			ret = -ENOENT;
1959 		}
1960 	} else {
1961 		ret = -ENOENT;
1962 	}
1963 
1964 out:
1965 	return ret;
1966 }
1967 
1968 static int is_inode_existent(struct send_ctx *sctx, u64 ino, u64 gen,
1969 			     u64 *send_gen, u64 *parent_gen)
1970 {
1971 	int ret;
1972 
1973 	if (ino == BTRFS_FIRST_FREE_OBJECTID)
1974 		return 1;
1975 
1976 	ret = get_cur_inode_state(sctx, ino, gen, send_gen, parent_gen);
1977 	if (ret < 0)
1978 		goto out;
1979 
1980 	if (ret == inode_state_no_change ||
1981 	    ret == inode_state_did_create ||
1982 	    ret == inode_state_will_delete)
1983 		ret = 1;
1984 	else
1985 		ret = 0;
1986 
1987 out:
1988 	return ret;
1989 }
1990 
1991 /*
1992  * Helper function to lookup a dir item in a dir.
1993  */
1994 static int lookup_dir_item_inode(struct btrfs_root *root,
1995 				 u64 dir, const char *name, int name_len,
1996 				 u64 *found_inode)
1997 {
1998 	int ret = 0;
1999 	struct btrfs_dir_item *di;
2000 	struct btrfs_key key;
2001 	struct btrfs_path *path;
2002 	struct fscrypt_str name_str = FSTR_INIT((char *)name, name_len);
2003 
2004 	path = alloc_path_for_send();
2005 	if (!path)
2006 		return -ENOMEM;
2007 
2008 	di = btrfs_lookup_dir_item(NULL, root, path, dir, &name_str, 0);
2009 	if (IS_ERR_OR_NULL(di)) {
2010 		ret = di ? PTR_ERR(di) : -ENOENT;
2011 		goto out;
2012 	}
2013 	btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
2014 	if (key.type == BTRFS_ROOT_ITEM_KEY) {
2015 		ret = -ENOENT;
2016 		goto out;
2017 	}
2018 	*found_inode = key.objectid;
2019 
2020 out:
2021 	btrfs_free_path(path);
2022 	return ret;
2023 }
2024 
2025 /*
2026  * Looks up the first btrfs_inode_ref of a given ino. It returns the parent dir,
2027  * generation of the parent dir and the name of the dir entry.
2028  */
2029 static int get_first_ref(struct btrfs_root *root, u64 ino,
2030 			 u64 *dir, u64 *dir_gen, struct fs_path *name)
2031 {
2032 	int ret;
2033 	struct btrfs_key key;
2034 	struct btrfs_key found_key;
2035 	struct btrfs_path *path;
2036 	int len;
2037 	u64 parent_dir;
2038 
2039 	path = alloc_path_for_send();
2040 	if (!path)
2041 		return -ENOMEM;
2042 
2043 	key.objectid = ino;
2044 	key.type = BTRFS_INODE_REF_KEY;
2045 	key.offset = 0;
2046 
2047 	ret = btrfs_search_slot_for_read(root, &key, path, 1, 0);
2048 	if (ret < 0)
2049 		goto out;
2050 	if (!ret)
2051 		btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2052 				path->slots[0]);
2053 	if (ret || found_key.objectid != ino ||
2054 	    (found_key.type != BTRFS_INODE_REF_KEY &&
2055 	     found_key.type != BTRFS_INODE_EXTREF_KEY)) {
2056 		ret = -ENOENT;
2057 		goto out;
2058 	}
2059 
2060 	if (found_key.type == BTRFS_INODE_REF_KEY) {
2061 		struct btrfs_inode_ref *iref;
2062 		iref = btrfs_item_ptr(path->nodes[0], path->slots[0],
2063 				      struct btrfs_inode_ref);
2064 		len = btrfs_inode_ref_name_len(path->nodes[0], iref);
2065 		ret = fs_path_add_from_extent_buffer(name, path->nodes[0],
2066 						     (unsigned long)(iref + 1),
2067 						     len);
2068 		parent_dir = found_key.offset;
2069 	} else {
2070 		struct btrfs_inode_extref *extref;
2071 		extref = btrfs_item_ptr(path->nodes[0], path->slots[0],
2072 					struct btrfs_inode_extref);
2073 		len = btrfs_inode_extref_name_len(path->nodes[0], extref);
2074 		ret = fs_path_add_from_extent_buffer(name, path->nodes[0],
2075 					(unsigned long)&extref->name, len);
2076 		parent_dir = btrfs_inode_extref_parent(path->nodes[0], extref);
2077 	}
2078 	if (ret < 0)
2079 		goto out;
2080 	btrfs_release_path(path);
2081 
2082 	if (dir_gen) {
2083 		ret = get_inode_gen(root, parent_dir, dir_gen);
2084 		if (ret < 0)
2085 			goto out;
2086 	}
2087 
2088 	*dir = parent_dir;
2089 
2090 out:
2091 	btrfs_free_path(path);
2092 	return ret;
2093 }
2094 
2095 static int is_first_ref(struct btrfs_root *root,
2096 			u64 ino, u64 dir,
2097 			const char *name, int name_len)
2098 {
2099 	int ret;
2100 	struct fs_path *tmp_name;
2101 	u64 tmp_dir;
2102 
2103 	tmp_name = fs_path_alloc();
2104 	if (!tmp_name)
2105 		return -ENOMEM;
2106 
2107 	ret = get_first_ref(root, ino, &tmp_dir, NULL, tmp_name);
2108 	if (ret < 0)
2109 		goto out;
2110 
2111 	if (dir != tmp_dir || name_len != fs_path_len(tmp_name)) {
2112 		ret = 0;
2113 		goto out;
2114 	}
2115 
2116 	ret = !memcmp(tmp_name->start, name, name_len);
2117 
2118 out:
2119 	fs_path_free(tmp_name);
2120 	return ret;
2121 }
2122 
2123 /*
2124  * Used by process_recorded_refs to determine if a new ref would overwrite an
2125  * already existing ref. In case it detects an overwrite, it returns the
2126  * inode/gen in who_ino/who_gen.
2127  * When an overwrite is detected, process_recorded_refs does proper orphanizing
2128  * to make sure later references to the overwritten inode are possible.
2129  * Orphanizing is however only required for the first ref of an inode.
2130  * process_recorded_refs does an additional is_first_ref check to see if
2131  * orphanizing is really required.
2132  */
2133 static int will_overwrite_ref(struct send_ctx *sctx, u64 dir, u64 dir_gen,
2134 			      const char *name, int name_len,
2135 			      u64 *who_ino, u64 *who_gen, u64 *who_mode)
2136 {
2137 	int ret;
2138 	u64 parent_root_dir_gen;
2139 	u64 other_inode = 0;
2140 	struct btrfs_inode_info info;
2141 
2142 	if (!sctx->parent_root)
2143 		return 0;
2144 
2145 	ret = is_inode_existent(sctx, dir, dir_gen, NULL, &parent_root_dir_gen);
2146 	if (ret <= 0)
2147 		return 0;
2148 
2149 	/*
2150 	 * If we have a parent root we need to verify that the parent dir was
2151 	 * not deleted and then re-created, if it was then we have no overwrite
2152 	 * and we can just unlink this entry.
2153 	 *
2154 	 * @parent_root_dir_gen was set to 0 if the inode does not exist in the
2155 	 * parent root.
2156 	 */
2157 	if (sctx->parent_root && dir != BTRFS_FIRST_FREE_OBJECTID &&
2158 	    parent_root_dir_gen != dir_gen)
2159 		return 0;
2160 
2161 	ret = lookup_dir_item_inode(sctx->parent_root, dir, name, name_len,
2162 				    &other_inode);
2163 	if (ret == -ENOENT)
2164 		return 0;
2165 	else if (ret < 0)
2166 		return ret;
2167 
2168 	/*
2169 	 * Check if the overwritten ref was already processed. If yes, the ref
2170 	 * was already unlinked/moved, so we can safely assume that we will not
2171 	 * overwrite anything at this point in time.
2172 	 */
2173 	if (other_inode > sctx->send_progress ||
2174 	    is_waiting_for_move(sctx, other_inode)) {
2175 		ret = get_inode_info(sctx->parent_root, other_inode, &info);
2176 		if (ret < 0)
2177 			return ret;
2178 
2179 		*who_ino = other_inode;
2180 		*who_gen = info.gen;
2181 		*who_mode = info.mode;
2182 		return 1;
2183 	}
2184 
2185 	return 0;
2186 }
2187 
2188 /*
2189  * Checks if the ref was overwritten by an already processed inode. This is
2190  * used by __get_cur_name_and_parent to find out if the ref was orphanized and
2191  * thus the orphan name needs be used.
2192  * process_recorded_refs also uses it to avoid unlinking of refs that were
2193  * overwritten.
2194  */
2195 static int did_overwrite_ref(struct send_ctx *sctx,
2196 			    u64 dir, u64 dir_gen,
2197 			    u64 ino, u64 ino_gen,
2198 			    const char *name, int name_len)
2199 {
2200 	int ret;
2201 	u64 ow_inode;
2202 	u64 ow_gen = 0;
2203 	u64 send_root_dir_gen;
2204 
2205 	if (!sctx->parent_root)
2206 		return 0;
2207 
2208 	ret = is_inode_existent(sctx, dir, dir_gen, &send_root_dir_gen, NULL);
2209 	if (ret <= 0)
2210 		return ret;
2211 
2212 	/*
2213 	 * @send_root_dir_gen was set to 0 if the inode does not exist in the
2214 	 * send root.
2215 	 */
2216 	if (dir != BTRFS_FIRST_FREE_OBJECTID && send_root_dir_gen != dir_gen)
2217 		return 0;
2218 
2219 	/* check if the ref was overwritten by another ref */
2220 	ret = lookup_dir_item_inode(sctx->send_root, dir, name, name_len,
2221 				    &ow_inode);
2222 	if (ret == -ENOENT) {
2223 		/* was never and will never be overwritten */
2224 		return 0;
2225 	} else if (ret < 0) {
2226 		return ret;
2227 	}
2228 
2229 	if (ow_inode == ino) {
2230 		ret = get_inode_gen(sctx->send_root, ow_inode, &ow_gen);
2231 		if (ret < 0)
2232 			return ret;
2233 
2234 		/* It's the same inode, so no overwrite happened. */
2235 		if (ow_gen == ino_gen)
2236 			return 0;
2237 	}
2238 
2239 	/*
2240 	 * We know that it is or will be overwritten. Check this now.
2241 	 * The current inode being processed might have been the one that caused
2242 	 * inode 'ino' to be orphanized, therefore check if ow_inode matches
2243 	 * the current inode being processed.
2244 	 */
2245 	if (ow_inode < sctx->send_progress)
2246 		return 1;
2247 
2248 	if (ino != sctx->cur_ino && ow_inode == sctx->cur_ino) {
2249 		if (ow_gen == 0) {
2250 			ret = get_inode_gen(sctx->send_root, ow_inode, &ow_gen);
2251 			if (ret < 0)
2252 				return ret;
2253 		}
2254 		if (ow_gen == sctx->cur_inode_gen)
2255 			return 1;
2256 	}
2257 
2258 	return 0;
2259 }
2260 
2261 /*
2262  * Same as did_overwrite_ref, but also checks if it is the first ref of an inode
2263  * that got overwritten. This is used by process_recorded_refs to determine
2264  * if it has to use the path as returned by get_cur_path or the orphan name.
2265  */
2266 static int did_overwrite_first_ref(struct send_ctx *sctx, u64 ino, u64 gen)
2267 {
2268 	int ret = 0;
2269 	struct fs_path *name = NULL;
2270 	u64 dir;
2271 	u64 dir_gen;
2272 
2273 	if (!sctx->parent_root)
2274 		goto out;
2275 
2276 	name = fs_path_alloc();
2277 	if (!name)
2278 		return -ENOMEM;
2279 
2280 	ret = get_first_ref(sctx->parent_root, ino, &dir, &dir_gen, name);
2281 	if (ret < 0)
2282 		goto out;
2283 
2284 	ret = did_overwrite_ref(sctx, dir, dir_gen, ino, gen,
2285 			name->start, fs_path_len(name));
2286 
2287 out:
2288 	fs_path_free(name);
2289 	return ret;
2290 }
2291 
2292 static inline struct name_cache_entry *name_cache_search(struct send_ctx *sctx,
2293 							 u64 ino, u64 gen)
2294 {
2295 	struct btrfs_lru_cache_entry *entry;
2296 
2297 	entry = btrfs_lru_cache_lookup(&sctx->name_cache, ino, gen);
2298 	if (!entry)
2299 		return NULL;
2300 
2301 	return container_of(entry, struct name_cache_entry, entry);
2302 }
2303 
2304 /*
2305  * Used by get_cur_path for each ref up to the root.
2306  * Returns 0 if it succeeded.
2307  * Returns 1 if the inode is not existent or got overwritten. In that case, the
2308  * name is an orphan name. This instructs get_cur_path to stop iterating. If 1
2309  * is returned, parent_ino/parent_gen are not guaranteed to be valid.
2310  * Returns <0 in case of error.
2311  */
2312 static int __get_cur_name_and_parent(struct send_ctx *sctx,
2313 				     u64 ino, u64 gen,
2314 				     u64 *parent_ino,
2315 				     u64 *parent_gen,
2316 				     struct fs_path *dest)
2317 {
2318 	int ret;
2319 	int nce_ret;
2320 	struct name_cache_entry *nce;
2321 
2322 	/*
2323 	 * First check if we already did a call to this function with the same
2324 	 * ino/gen. If yes, check if the cache entry is still up-to-date. If yes
2325 	 * return the cached result.
2326 	 */
2327 	nce = name_cache_search(sctx, ino, gen);
2328 	if (nce) {
2329 		if (ino < sctx->send_progress && nce->need_later_update) {
2330 			btrfs_lru_cache_remove(&sctx->name_cache, &nce->entry);
2331 			nce = NULL;
2332 		} else {
2333 			*parent_ino = nce->parent_ino;
2334 			*parent_gen = nce->parent_gen;
2335 			ret = fs_path_add(dest, nce->name, nce->name_len);
2336 			if (ret < 0)
2337 				goto out;
2338 			ret = nce->ret;
2339 			goto out;
2340 		}
2341 	}
2342 
2343 	/*
2344 	 * If the inode is not existent yet, add the orphan name and return 1.
2345 	 * This should only happen for the parent dir that we determine in
2346 	 * record_new_ref_if_needed().
2347 	 */
2348 	ret = is_inode_existent(sctx, ino, gen, NULL, NULL);
2349 	if (ret < 0)
2350 		goto out;
2351 
2352 	if (!ret) {
2353 		ret = gen_unique_name(sctx, ino, gen, dest);
2354 		if (ret < 0)
2355 			goto out;
2356 		ret = 1;
2357 		goto out_cache;
2358 	}
2359 
2360 	/*
2361 	 * Depending on whether the inode was already processed or not, use
2362 	 * send_root or parent_root for ref lookup.
2363 	 */
2364 	if (ino < sctx->send_progress)
2365 		ret = get_first_ref(sctx->send_root, ino,
2366 				    parent_ino, parent_gen, dest);
2367 	else
2368 		ret = get_first_ref(sctx->parent_root, ino,
2369 				    parent_ino, parent_gen, dest);
2370 	if (ret < 0)
2371 		goto out;
2372 
2373 	/*
2374 	 * Check if the ref was overwritten by an inode's ref that was processed
2375 	 * earlier. If yes, treat as orphan and return 1.
2376 	 */
2377 	ret = did_overwrite_ref(sctx, *parent_ino, *parent_gen, ino, gen,
2378 			dest->start, dest->end - dest->start);
2379 	if (ret < 0)
2380 		goto out;
2381 	if (ret) {
2382 		fs_path_reset(dest);
2383 		ret = gen_unique_name(sctx, ino, gen, dest);
2384 		if (ret < 0)
2385 			goto out;
2386 		ret = 1;
2387 	}
2388 
2389 out_cache:
2390 	/*
2391 	 * Store the result of the lookup in the name cache.
2392 	 */
2393 	nce = kmalloc(sizeof(*nce) + fs_path_len(dest) + 1, GFP_KERNEL);
2394 	if (!nce) {
2395 		ret = -ENOMEM;
2396 		goto out;
2397 	}
2398 
2399 	nce->entry.key = ino;
2400 	nce->entry.gen = gen;
2401 	nce->parent_ino = *parent_ino;
2402 	nce->parent_gen = *parent_gen;
2403 	nce->name_len = fs_path_len(dest);
2404 	nce->ret = ret;
2405 	strcpy(nce->name, dest->start);
2406 
2407 	if (ino < sctx->send_progress)
2408 		nce->need_later_update = 0;
2409 	else
2410 		nce->need_later_update = 1;
2411 
2412 	nce_ret = btrfs_lru_cache_store(&sctx->name_cache, &nce->entry, GFP_KERNEL);
2413 	if (nce_ret < 0) {
2414 		kfree(nce);
2415 		ret = nce_ret;
2416 	}
2417 
2418 out:
2419 	return ret;
2420 }
2421 
2422 /*
2423  * Magic happens here. This function returns the first ref to an inode as it
2424  * would look like while receiving the stream at this point in time.
2425  * We walk the path up to the root. For every inode in between, we check if it
2426  * was already processed/sent. If yes, we continue with the parent as found
2427  * in send_root. If not, we continue with the parent as found in parent_root.
2428  * If we encounter an inode that was deleted at this point in time, we use the
2429  * inodes "orphan" name instead of the real name and stop. Same with new inodes
2430  * that were not created yet and overwritten inodes/refs.
2431  *
2432  * When do we have orphan inodes:
2433  * 1. When an inode is freshly created and thus no valid refs are available yet
2434  * 2. When a directory lost all it's refs (deleted) but still has dir items
2435  *    inside which were not processed yet (pending for move/delete). If anyone
2436  *    tried to get the path to the dir items, it would get a path inside that
2437  *    orphan directory.
2438  * 3. When an inode is moved around or gets new links, it may overwrite the ref
2439  *    of an unprocessed inode. If in that case the first ref would be
2440  *    overwritten, the overwritten inode gets "orphanized". Later when we
2441  *    process this overwritten inode, it is restored at a new place by moving
2442  *    the orphan inode.
2443  *
2444  * sctx->send_progress tells this function at which point in time receiving
2445  * would be.
2446  */
2447 static int get_cur_path(struct send_ctx *sctx, u64 ino, u64 gen,
2448 			struct fs_path *dest)
2449 {
2450 	int ret = 0;
2451 	struct fs_path *name = NULL;
2452 	u64 parent_inode = 0;
2453 	u64 parent_gen = 0;
2454 	int stop = 0;
2455 
2456 	name = fs_path_alloc();
2457 	if (!name) {
2458 		ret = -ENOMEM;
2459 		goto out;
2460 	}
2461 
2462 	dest->reversed = 1;
2463 	fs_path_reset(dest);
2464 
2465 	while (!stop && ino != BTRFS_FIRST_FREE_OBJECTID) {
2466 		struct waiting_dir_move *wdm;
2467 
2468 		fs_path_reset(name);
2469 
2470 		if (is_waiting_for_rm(sctx, ino, gen)) {
2471 			ret = gen_unique_name(sctx, ino, gen, name);
2472 			if (ret < 0)
2473 				goto out;
2474 			ret = fs_path_add_path(dest, name);
2475 			break;
2476 		}
2477 
2478 		wdm = get_waiting_dir_move(sctx, ino);
2479 		if (wdm && wdm->orphanized) {
2480 			ret = gen_unique_name(sctx, ino, gen, name);
2481 			stop = 1;
2482 		} else if (wdm) {
2483 			ret = get_first_ref(sctx->parent_root, ino,
2484 					    &parent_inode, &parent_gen, name);
2485 		} else {
2486 			ret = __get_cur_name_and_parent(sctx, ino, gen,
2487 							&parent_inode,
2488 							&parent_gen, name);
2489 			if (ret)
2490 				stop = 1;
2491 		}
2492 
2493 		if (ret < 0)
2494 			goto out;
2495 
2496 		ret = fs_path_add_path(dest, name);
2497 		if (ret < 0)
2498 			goto out;
2499 
2500 		ino = parent_inode;
2501 		gen = parent_gen;
2502 	}
2503 
2504 out:
2505 	fs_path_free(name);
2506 	if (!ret)
2507 		fs_path_unreverse(dest);
2508 	return ret;
2509 }
2510 
2511 /*
2512  * Sends a BTRFS_SEND_C_SUBVOL command/item to userspace
2513  */
2514 static int send_subvol_begin(struct send_ctx *sctx)
2515 {
2516 	int ret;
2517 	struct btrfs_root *send_root = sctx->send_root;
2518 	struct btrfs_root *parent_root = sctx->parent_root;
2519 	struct btrfs_path *path;
2520 	struct btrfs_key key;
2521 	struct btrfs_root_ref *ref;
2522 	struct extent_buffer *leaf;
2523 	char *name = NULL;
2524 	int namelen;
2525 
2526 	path = btrfs_alloc_path();
2527 	if (!path)
2528 		return -ENOMEM;
2529 
2530 	name = kmalloc(BTRFS_PATH_NAME_MAX, GFP_KERNEL);
2531 	if (!name) {
2532 		btrfs_free_path(path);
2533 		return -ENOMEM;
2534 	}
2535 
2536 	key.objectid = send_root->root_key.objectid;
2537 	key.type = BTRFS_ROOT_BACKREF_KEY;
2538 	key.offset = 0;
2539 
2540 	ret = btrfs_search_slot_for_read(send_root->fs_info->tree_root,
2541 				&key, path, 1, 0);
2542 	if (ret < 0)
2543 		goto out;
2544 	if (ret) {
2545 		ret = -ENOENT;
2546 		goto out;
2547 	}
2548 
2549 	leaf = path->nodes[0];
2550 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2551 	if (key.type != BTRFS_ROOT_BACKREF_KEY ||
2552 	    key.objectid != send_root->root_key.objectid) {
2553 		ret = -ENOENT;
2554 		goto out;
2555 	}
2556 	ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
2557 	namelen = btrfs_root_ref_name_len(leaf, ref);
2558 	read_extent_buffer(leaf, name, (unsigned long)(ref + 1), namelen);
2559 	btrfs_release_path(path);
2560 
2561 	if (parent_root) {
2562 		ret = begin_cmd(sctx, BTRFS_SEND_C_SNAPSHOT);
2563 		if (ret < 0)
2564 			goto out;
2565 	} else {
2566 		ret = begin_cmd(sctx, BTRFS_SEND_C_SUBVOL);
2567 		if (ret < 0)
2568 			goto out;
2569 	}
2570 
2571 	TLV_PUT_STRING(sctx, BTRFS_SEND_A_PATH, name, namelen);
2572 
2573 	if (!btrfs_is_empty_uuid(sctx->send_root->root_item.received_uuid))
2574 		TLV_PUT_UUID(sctx, BTRFS_SEND_A_UUID,
2575 			    sctx->send_root->root_item.received_uuid);
2576 	else
2577 		TLV_PUT_UUID(sctx, BTRFS_SEND_A_UUID,
2578 			    sctx->send_root->root_item.uuid);
2579 
2580 	TLV_PUT_U64(sctx, BTRFS_SEND_A_CTRANSID,
2581 		    btrfs_root_ctransid(&sctx->send_root->root_item));
2582 	if (parent_root) {
2583 		if (!btrfs_is_empty_uuid(parent_root->root_item.received_uuid))
2584 			TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
2585 				     parent_root->root_item.received_uuid);
2586 		else
2587 			TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
2588 				     parent_root->root_item.uuid);
2589 		TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_CTRANSID,
2590 			    btrfs_root_ctransid(&sctx->parent_root->root_item));
2591 	}
2592 
2593 	ret = send_cmd(sctx);
2594 
2595 tlv_put_failure:
2596 out:
2597 	btrfs_free_path(path);
2598 	kfree(name);
2599 	return ret;
2600 }
2601 
2602 static int send_truncate(struct send_ctx *sctx, u64 ino, u64 gen, u64 size)
2603 {
2604 	struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2605 	int ret = 0;
2606 	struct fs_path *p;
2607 
2608 	btrfs_debug(fs_info, "send_truncate %llu size=%llu", ino, size);
2609 
2610 	p = fs_path_alloc();
2611 	if (!p)
2612 		return -ENOMEM;
2613 
2614 	ret = begin_cmd(sctx, BTRFS_SEND_C_TRUNCATE);
2615 	if (ret < 0)
2616 		goto out;
2617 
2618 	ret = get_cur_path(sctx, ino, gen, p);
2619 	if (ret < 0)
2620 		goto out;
2621 	TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2622 	TLV_PUT_U64(sctx, BTRFS_SEND_A_SIZE, size);
2623 
2624 	ret = send_cmd(sctx);
2625 
2626 tlv_put_failure:
2627 out:
2628 	fs_path_free(p);
2629 	return ret;
2630 }
2631 
2632 static int send_chmod(struct send_ctx *sctx, u64 ino, u64 gen, u64 mode)
2633 {
2634 	struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2635 	int ret = 0;
2636 	struct fs_path *p;
2637 
2638 	btrfs_debug(fs_info, "send_chmod %llu mode=%llu", ino, mode);
2639 
2640 	p = fs_path_alloc();
2641 	if (!p)
2642 		return -ENOMEM;
2643 
2644 	ret = begin_cmd(sctx, BTRFS_SEND_C_CHMOD);
2645 	if (ret < 0)
2646 		goto out;
2647 
2648 	ret = get_cur_path(sctx, ino, gen, p);
2649 	if (ret < 0)
2650 		goto out;
2651 	TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2652 	TLV_PUT_U64(sctx, BTRFS_SEND_A_MODE, mode & 07777);
2653 
2654 	ret = send_cmd(sctx);
2655 
2656 tlv_put_failure:
2657 out:
2658 	fs_path_free(p);
2659 	return ret;
2660 }
2661 
2662 static int send_fileattr(struct send_ctx *sctx, u64 ino, u64 gen, u64 fileattr)
2663 {
2664 	struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2665 	int ret = 0;
2666 	struct fs_path *p;
2667 
2668 	if (sctx->proto < 2)
2669 		return 0;
2670 
2671 	btrfs_debug(fs_info, "send_fileattr %llu fileattr=%llu", ino, fileattr);
2672 
2673 	p = fs_path_alloc();
2674 	if (!p)
2675 		return -ENOMEM;
2676 
2677 	ret = begin_cmd(sctx, BTRFS_SEND_C_FILEATTR);
2678 	if (ret < 0)
2679 		goto out;
2680 
2681 	ret = get_cur_path(sctx, ino, gen, p);
2682 	if (ret < 0)
2683 		goto out;
2684 	TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2685 	TLV_PUT_U64(sctx, BTRFS_SEND_A_FILEATTR, fileattr);
2686 
2687 	ret = send_cmd(sctx);
2688 
2689 tlv_put_failure:
2690 out:
2691 	fs_path_free(p);
2692 	return ret;
2693 }
2694 
2695 static int send_chown(struct send_ctx *sctx, u64 ino, u64 gen, u64 uid, u64 gid)
2696 {
2697 	struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2698 	int ret = 0;
2699 	struct fs_path *p;
2700 
2701 	btrfs_debug(fs_info, "send_chown %llu uid=%llu, gid=%llu",
2702 		    ino, uid, gid);
2703 
2704 	p = fs_path_alloc();
2705 	if (!p)
2706 		return -ENOMEM;
2707 
2708 	ret = begin_cmd(sctx, BTRFS_SEND_C_CHOWN);
2709 	if (ret < 0)
2710 		goto out;
2711 
2712 	ret = get_cur_path(sctx, ino, gen, p);
2713 	if (ret < 0)
2714 		goto out;
2715 	TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2716 	TLV_PUT_U64(sctx, BTRFS_SEND_A_UID, uid);
2717 	TLV_PUT_U64(sctx, BTRFS_SEND_A_GID, gid);
2718 
2719 	ret = send_cmd(sctx);
2720 
2721 tlv_put_failure:
2722 out:
2723 	fs_path_free(p);
2724 	return ret;
2725 }
2726 
2727 static int send_utimes(struct send_ctx *sctx, u64 ino, u64 gen)
2728 {
2729 	struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2730 	int ret = 0;
2731 	struct fs_path *p = NULL;
2732 	struct btrfs_inode_item *ii;
2733 	struct btrfs_path *path = NULL;
2734 	struct extent_buffer *eb;
2735 	struct btrfs_key key;
2736 	int slot;
2737 
2738 	btrfs_debug(fs_info, "send_utimes %llu", ino);
2739 
2740 	p = fs_path_alloc();
2741 	if (!p)
2742 		return -ENOMEM;
2743 
2744 	path = alloc_path_for_send();
2745 	if (!path) {
2746 		ret = -ENOMEM;
2747 		goto out;
2748 	}
2749 
2750 	key.objectid = ino;
2751 	key.type = BTRFS_INODE_ITEM_KEY;
2752 	key.offset = 0;
2753 	ret = btrfs_search_slot(NULL, sctx->send_root, &key, path, 0, 0);
2754 	if (ret > 0)
2755 		ret = -ENOENT;
2756 	if (ret < 0)
2757 		goto out;
2758 
2759 	eb = path->nodes[0];
2760 	slot = path->slots[0];
2761 	ii = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
2762 
2763 	ret = begin_cmd(sctx, BTRFS_SEND_C_UTIMES);
2764 	if (ret < 0)
2765 		goto out;
2766 
2767 	ret = get_cur_path(sctx, ino, gen, p);
2768 	if (ret < 0)
2769 		goto out;
2770 	TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2771 	TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_ATIME, eb, &ii->atime);
2772 	TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_MTIME, eb, &ii->mtime);
2773 	TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_CTIME, eb, &ii->ctime);
2774 	if (sctx->proto >= 2)
2775 		TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_OTIME, eb, &ii->otime);
2776 
2777 	ret = send_cmd(sctx);
2778 
2779 tlv_put_failure:
2780 out:
2781 	fs_path_free(p);
2782 	btrfs_free_path(path);
2783 	return ret;
2784 }
2785 
2786 /*
2787  * If the cache is full, we can't remove entries from it and do a call to
2788  * send_utimes() for each respective inode, because we might be finishing
2789  * processing an inode that is a directory and it just got renamed, and existing
2790  * entries in the cache may refer to inodes that have the directory in their
2791  * full path - in which case we would generate outdated paths (pre-rename)
2792  * for the inodes that the cache entries point to. Instead of prunning the
2793  * cache when inserting, do it after we finish processing each inode at
2794  * finish_inode_if_needed().
2795  */
2796 static int cache_dir_utimes(struct send_ctx *sctx, u64 dir, u64 gen)
2797 {
2798 	struct btrfs_lru_cache_entry *entry;
2799 	int ret;
2800 
2801 	entry = btrfs_lru_cache_lookup(&sctx->dir_utimes_cache, dir, gen);
2802 	if (entry != NULL)
2803 		return 0;
2804 
2805 	/* Caching is optional, don't fail if we can't allocate memory. */
2806 	entry = kmalloc(sizeof(*entry), GFP_KERNEL);
2807 	if (!entry)
2808 		return send_utimes(sctx, dir, gen);
2809 
2810 	entry->key = dir;
2811 	entry->gen = gen;
2812 
2813 	ret = btrfs_lru_cache_store(&sctx->dir_utimes_cache, entry, GFP_KERNEL);
2814 	ASSERT(ret != -EEXIST);
2815 	if (ret) {
2816 		kfree(entry);
2817 		return send_utimes(sctx, dir, gen);
2818 	}
2819 
2820 	return 0;
2821 }
2822 
2823 static int trim_dir_utimes_cache(struct send_ctx *sctx)
2824 {
2825 	while (btrfs_lru_cache_size(&sctx->dir_utimes_cache) >
2826 	       SEND_MAX_DIR_UTIMES_CACHE_SIZE) {
2827 		struct btrfs_lru_cache_entry *lru;
2828 		int ret;
2829 
2830 		lru = btrfs_lru_cache_lru_entry(&sctx->dir_utimes_cache);
2831 		ASSERT(lru != NULL);
2832 
2833 		ret = send_utimes(sctx, lru->key, lru->gen);
2834 		if (ret)
2835 			return ret;
2836 
2837 		btrfs_lru_cache_remove(&sctx->dir_utimes_cache, lru);
2838 	}
2839 
2840 	return 0;
2841 }
2842 
2843 /*
2844  * Sends a BTRFS_SEND_C_MKXXX or SYMLINK command to user space. We don't have
2845  * a valid path yet because we did not process the refs yet. So, the inode
2846  * is created as orphan.
2847  */
2848 static int send_create_inode(struct send_ctx *sctx, u64 ino)
2849 {
2850 	struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2851 	int ret = 0;
2852 	struct fs_path *p;
2853 	int cmd;
2854 	struct btrfs_inode_info info;
2855 	u64 gen;
2856 	u64 mode;
2857 	u64 rdev;
2858 
2859 	btrfs_debug(fs_info, "send_create_inode %llu", ino);
2860 
2861 	p = fs_path_alloc();
2862 	if (!p)
2863 		return -ENOMEM;
2864 
2865 	if (ino != sctx->cur_ino) {
2866 		ret = get_inode_info(sctx->send_root, ino, &info);
2867 		if (ret < 0)
2868 			goto out;
2869 		gen = info.gen;
2870 		mode = info.mode;
2871 		rdev = info.rdev;
2872 	} else {
2873 		gen = sctx->cur_inode_gen;
2874 		mode = sctx->cur_inode_mode;
2875 		rdev = sctx->cur_inode_rdev;
2876 	}
2877 
2878 	if (S_ISREG(mode)) {
2879 		cmd = BTRFS_SEND_C_MKFILE;
2880 	} else if (S_ISDIR(mode)) {
2881 		cmd = BTRFS_SEND_C_MKDIR;
2882 	} else if (S_ISLNK(mode)) {
2883 		cmd = BTRFS_SEND_C_SYMLINK;
2884 	} else if (S_ISCHR(mode) || S_ISBLK(mode)) {
2885 		cmd = BTRFS_SEND_C_MKNOD;
2886 	} else if (S_ISFIFO(mode)) {
2887 		cmd = BTRFS_SEND_C_MKFIFO;
2888 	} else if (S_ISSOCK(mode)) {
2889 		cmd = BTRFS_SEND_C_MKSOCK;
2890 	} else {
2891 		btrfs_warn(sctx->send_root->fs_info, "unexpected inode type %o",
2892 				(int)(mode & S_IFMT));
2893 		ret = -EOPNOTSUPP;
2894 		goto out;
2895 	}
2896 
2897 	ret = begin_cmd(sctx, cmd);
2898 	if (ret < 0)
2899 		goto out;
2900 
2901 	ret = gen_unique_name(sctx, ino, gen, p);
2902 	if (ret < 0)
2903 		goto out;
2904 
2905 	TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2906 	TLV_PUT_U64(sctx, BTRFS_SEND_A_INO, ino);
2907 
2908 	if (S_ISLNK(mode)) {
2909 		fs_path_reset(p);
2910 		ret = read_symlink(sctx->send_root, ino, p);
2911 		if (ret < 0)
2912 			goto out;
2913 		TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH_LINK, p);
2914 	} else if (S_ISCHR(mode) || S_ISBLK(mode) ||
2915 		   S_ISFIFO(mode) || S_ISSOCK(mode)) {
2916 		TLV_PUT_U64(sctx, BTRFS_SEND_A_RDEV, new_encode_dev(rdev));
2917 		TLV_PUT_U64(sctx, BTRFS_SEND_A_MODE, mode);
2918 	}
2919 
2920 	ret = send_cmd(sctx);
2921 	if (ret < 0)
2922 		goto out;
2923 
2924 
2925 tlv_put_failure:
2926 out:
2927 	fs_path_free(p);
2928 	return ret;
2929 }
2930 
2931 static void cache_dir_created(struct send_ctx *sctx, u64 dir)
2932 {
2933 	struct btrfs_lru_cache_entry *entry;
2934 	int ret;
2935 
2936 	/* Caching is optional, ignore any failures. */
2937 	entry = kmalloc(sizeof(*entry), GFP_KERNEL);
2938 	if (!entry)
2939 		return;
2940 
2941 	entry->key = dir;
2942 	entry->gen = 0;
2943 	ret = btrfs_lru_cache_store(&sctx->dir_created_cache, entry, GFP_KERNEL);
2944 	if (ret < 0)
2945 		kfree(entry);
2946 }
2947 
2948 /*
2949  * We need some special handling for inodes that get processed before the parent
2950  * directory got created. See process_recorded_refs for details.
2951  * This function does the check if we already created the dir out of order.
2952  */
2953 static int did_create_dir(struct send_ctx *sctx, u64 dir)
2954 {
2955 	int ret = 0;
2956 	int iter_ret = 0;
2957 	struct btrfs_path *path = NULL;
2958 	struct btrfs_key key;
2959 	struct btrfs_key found_key;
2960 	struct btrfs_key di_key;
2961 	struct btrfs_dir_item *di;
2962 
2963 	if (btrfs_lru_cache_lookup(&sctx->dir_created_cache, dir, 0))
2964 		return 1;
2965 
2966 	path = alloc_path_for_send();
2967 	if (!path)
2968 		return -ENOMEM;
2969 
2970 	key.objectid = dir;
2971 	key.type = BTRFS_DIR_INDEX_KEY;
2972 	key.offset = 0;
2973 
2974 	btrfs_for_each_slot(sctx->send_root, &key, &found_key, path, iter_ret) {
2975 		struct extent_buffer *eb = path->nodes[0];
2976 
2977 		if (found_key.objectid != key.objectid ||
2978 		    found_key.type != key.type) {
2979 			ret = 0;
2980 			break;
2981 		}
2982 
2983 		di = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dir_item);
2984 		btrfs_dir_item_key_to_cpu(eb, di, &di_key);
2985 
2986 		if (di_key.type != BTRFS_ROOT_ITEM_KEY &&
2987 		    di_key.objectid < sctx->send_progress) {
2988 			ret = 1;
2989 			cache_dir_created(sctx, dir);
2990 			break;
2991 		}
2992 	}
2993 	/* Catch error found during iteration */
2994 	if (iter_ret < 0)
2995 		ret = iter_ret;
2996 
2997 	btrfs_free_path(path);
2998 	return ret;
2999 }
3000 
3001 /*
3002  * Only creates the inode if it is:
3003  * 1. Not a directory
3004  * 2. Or a directory which was not created already due to out of order
3005  *    directories. See did_create_dir and process_recorded_refs for details.
3006  */
3007 static int send_create_inode_if_needed(struct send_ctx *sctx)
3008 {
3009 	int ret;
3010 
3011 	if (S_ISDIR(sctx->cur_inode_mode)) {
3012 		ret = did_create_dir(sctx, sctx->cur_ino);
3013 		if (ret < 0)
3014 			return ret;
3015 		else if (ret > 0)
3016 			return 0;
3017 	}
3018 
3019 	ret = send_create_inode(sctx, sctx->cur_ino);
3020 
3021 	if (ret == 0 && S_ISDIR(sctx->cur_inode_mode))
3022 		cache_dir_created(sctx, sctx->cur_ino);
3023 
3024 	return ret;
3025 }
3026 
3027 struct recorded_ref {
3028 	struct list_head list;
3029 	char *name;
3030 	struct fs_path *full_path;
3031 	u64 dir;
3032 	u64 dir_gen;
3033 	int name_len;
3034 	struct rb_node node;
3035 	struct rb_root *root;
3036 };
3037 
3038 static struct recorded_ref *recorded_ref_alloc(void)
3039 {
3040 	struct recorded_ref *ref;
3041 
3042 	ref = kzalloc(sizeof(*ref), GFP_KERNEL);
3043 	if (!ref)
3044 		return NULL;
3045 	RB_CLEAR_NODE(&ref->node);
3046 	INIT_LIST_HEAD(&ref->list);
3047 	return ref;
3048 }
3049 
3050 static void recorded_ref_free(struct recorded_ref *ref)
3051 {
3052 	if (!ref)
3053 		return;
3054 	if (!RB_EMPTY_NODE(&ref->node))
3055 		rb_erase(&ref->node, ref->root);
3056 	list_del(&ref->list);
3057 	fs_path_free(ref->full_path);
3058 	kfree(ref);
3059 }
3060 
3061 static void set_ref_path(struct recorded_ref *ref, struct fs_path *path)
3062 {
3063 	ref->full_path = path;
3064 	ref->name = (char *)kbasename(ref->full_path->start);
3065 	ref->name_len = ref->full_path->end - ref->name;
3066 }
3067 
3068 static int dup_ref(struct recorded_ref *ref, struct list_head *list)
3069 {
3070 	struct recorded_ref *new;
3071 
3072 	new = recorded_ref_alloc();
3073 	if (!new)
3074 		return -ENOMEM;
3075 
3076 	new->dir = ref->dir;
3077 	new->dir_gen = ref->dir_gen;
3078 	list_add_tail(&new->list, list);
3079 	return 0;
3080 }
3081 
3082 static void __free_recorded_refs(struct list_head *head)
3083 {
3084 	struct recorded_ref *cur;
3085 
3086 	while (!list_empty(head)) {
3087 		cur = list_entry(head->next, struct recorded_ref, list);
3088 		recorded_ref_free(cur);
3089 	}
3090 }
3091 
3092 static void free_recorded_refs(struct send_ctx *sctx)
3093 {
3094 	__free_recorded_refs(&sctx->new_refs);
3095 	__free_recorded_refs(&sctx->deleted_refs);
3096 }
3097 
3098 /*
3099  * Renames/moves a file/dir to its orphan name. Used when the first
3100  * ref of an unprocessed inode gets overwritten and for all non empty
3101  * directories.
3102  */
3103 static int orphanize_inode(struct send_ctx *sctx, u64 ino, u64 gen,
3104 			  struct fs_path *path)
3105 {
3106 	int ret;
3107 	struct fs_path *orphan;
3108 
3109 	orphan = fs_path_alloc();
3110 	if (!orphan)
3111 		return -ENOMEM;
3112 
3113 	ret = gen_unique_name(sctx, ino, gen, orphan);
3114 	if (ret < 0)
3115 		goto out;
3116 
3117 	ret = send_rename(sctx, path, orphan);
3118 
3119 out:
3120 	fs_path_free(orphan);
3121 	return ret;
3122 }
3123 
3124 static struct orphan_dir_info *add_orphan_dir_info(struct send_ctx *sctx,
3125 						   u64 dir_ino, u64 dir_gen)
3126 {
3127 	struct rb_node **p = &sctx->orphan_dirs.rb_node;
3128 	struct rb_node *parent = NULL;
3129 	struct orphan_dir_info *entry, *odi;
3130 
3131 	while (*p) {
3132 		parent = *p;
3133 		entry = rb_entry(parent, struct orphan_dir_info, node);
3134 		if (dir_ino < entry->ino)
3135 			p = &(*p)->rb_left;
3136 		else if (dir_ino > entry->ino)
3137 			p = &(*p)->rb_right;
3138 		else if (dir_gen < entry->gen)
3139 			p = &(*p)->rb_left;
3140 		else if (dir_gen > entry->gen)
3141 			p = &(*p)->rb_right;
3142 		else
3143 			return entry;
3144 	}
3145 
3146 	odi = kmalloc(sizeof(*odi), GFP_KERNEL);
3147 	if (!odi)
3148 		return ERR_PTR(-ENOMEM);
3149 	odi->ino = dir_ino;
3150 	odi->gen = dir_gen;
3151 	odi->last_dir_index_offset = 0;
3152 	odi->dir_high_seq_ino = 0;
3153 
3154 	rb_link_node(&odi->node, parent, p);
3155 	rb_insert_color(&odi->node, &sctx->orphan_dirs);
3156 	return odi;
3157 }
3158 
3159 static struct orphan_dir_info *get_orphan_dir_info(struct send_ctx *sctx,
3160 						   u64 dir_ino, u64 gen)
3161 {
3162 	struct rb_node *n = sctx->orphan_dirs.rb_node;
3163 	struct orphan_dir_info *entry;
3164 
3165 	while (n) {
3166 		entry = rb_entry(n, struct orphan_dir_info, node);
3167 		if (dir_ino < entry->ino)
3168 			n = n->rb_left;
3169 		else if (dir_ino > entry->ino)
3170 			n = n->rb_right;
3171 		else if (gen < entry->gen)
3172 			n = n->rb_left;
3173 		else if (gen > entry->gen)
3174 			n = n->rb_right;
3175 		else
3176 			return entry;
3177 	}
3178 	return NULL;
3179 }
3180 
3181 static int is_waiting_for_rm(struct send_ctx *sctx, u64 dir_ino, u64 gen)
3182 {
3183 	struct orphan_dir_info *odi = get_orphan_dir_info(sctx, dir_ino, gen);
3184 
3185 	return odi != NULL;
3186 }
3187 
3188 static void free_orphan_dir_info(struct send_ctx *sctx,
3189 				 struct orphan_dir_info *odi)
3190 {
3191 	if (!odi)
3192 		return;
3193 	rb_erase(&odi->node, &sctx->orphan_dirs);
3194 	kfree(odi);
3195 }
3196 
3197 /*
3198  * Returns 1 if a directory can be removed at this point in time.
3199  * We check this by iterating all dir items and checking if the inode behind
3200  * the dir item was already processed.
3201  */
3202 static int can_rmdir(struct send_ctx *sctx, u64 dir, u64 dir_gen)
3203 {
3204 	int ret = 0;
3205 	int iter_ret = 0;
3206 	struct btrfs_root *root = sctx->parent_root;
3207 	struct btrfs_path *path;
3208 	struct btrfs_key key;
3209 	struct btrfs_key found_key;
3210 	struct btrfs_key loc;
3211 	struct btrfs_dir_item *di;
3212 	struct orphan_dir_info *odi = NULL;
3213 	u64 dir_high_seq_ino = 0;
3214 	u64 last_dir_index_offset = 0;
3215 
3216 	/*
3217 	 * Don't try to rmdir the top/root subvolume dir.
3218 	 */
3219 	if (dir == BTRFS_FIRST_FREE_OBJECTID)
3220 		return 0;
3221 
3222 	odi = get_orphan_dir_info(sctx, dir, dir_gen);
3223 	if (odi && sctx->cur_ino < odi->dir_high_seq_ino)
3224 		return 0;
3225 
3226 	path = alloc_path_for_send();
3227 	if (!path)
3228 		return -ENOMEM;
3229 
3230 	if (!odi) {
3231 		/*
3232 		 * Find the inode number associated with the last dir index
3233 		 * entry. This is very likely the inode with the highest number
3234 		 * of all inodes that have an entry in the directory. We can
3235 		 * then use it to avoid future calls to can_rmdir(), when
3236 		 * processing inodes with a lower number, from having to search
3237 		 * the parent root b+tree for dir index keys.
3238 		 */
3239 		key.objectid = dir;
3240 		key.type = BTRFS_DIR_INDEX_KEY;
3241 		key.offset = (u64)-1;
3242 
3243 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3244 		if (ret < 0) {
3245 			goto out;
3246 		} else if (ret > 0) {
3247 			/* Can't happen, the root is never empty. */
3248 			ASSERT(path->slots[0] > 0);
3249 			if (WARN_ON(path->slots[0] == 0)) {
3250 				ret = -EUCLEAN;
3251 				goto out;
3252 			}
3253 			path->slots[0]--;
3254 		}
3255 
3256 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3257 		if (key.objectid != dir || key.type != BTRFS_DIR_INDEX_KEY) {
3258 			/* No index keys, dir can be removed. */
3259 			ret = 1;
3260 			goto out;
3261 		}
3262 
3263 		di = btrfs_item_ptr(path->nodes[0], path->slots[0],
3264 				    struct btrfs_dir_item);
3265 		btrfs_dir_item_key_to_cpu(path->nodes[0], di, &loc);
3266 		dir_high_seq_ino = loc.objectid;
3267 		if (sctx->cur_ino < dir_high_seq_ino) {
3268 			ret = 0;
3269 			goto out;
3270 		}
3271 
3272 		btrfs_release_path(path);
3273 	}
3274 
3275 	key.objectid = dir;
3276 	key.type = BTRFS_DIR_INDEX_KEY;
3277 	key.offset = (odi ? odi->last_dir_index_offset : 0);
3278 
3279 	btrfs_for_each_slot(root, &key, &found_key, path, iter_ret) {
3280 		struct waiting_dir_move *dm;
3281 
3282 		if (found_key.objectid != key.objectid ||
3283 		    found_key.type != key.type)
3284 			break;
3285 
3286 		di = btrfs_item_ptr(path->nodes[0], path->slots[0],
3287 				struct btrfs_dir_item);
3288 		btrfs_dir_item_key_to_cpu(path->nodes[0], di, &loc);
3289 
3290 		dir_high_seq_ino = max(dir_high_seq_ino, loc.objectid);
3291 		last_dir_index_offset = found_key.offset;
3292 
3293 		dm = get_waiting_dir_move(sctx, loc.objectid);
3294 		if (dm) {
3295 			dm->rmdir_ino = dir;
3296 			dm->rmdir_gen = dir_gen;
3297 			ret = 0;
3298 			goto out;
3299 		}
3300 
3301 		if (loc.objectid > sctx->cur_ino) {
3302 			ret = 0;
3303 			goto out;
3304 		}
3305 	}
3306 	if (iter_ret < 0) {
3307 		ret = iter_ret;
3308 		goto out;
3309 	}
3310 	free_orphan_dir_info(sctx, odi);
3311 
3312 	ret = 1;
3313 
3314 out:
3315 	btrfs_free_path(path);
3316 
3317 	if (ret)
3318 		return ret;
3319 
3320 	if (!odi) {
3321 		odi = add_orphan_dir_info(sctx, dir, dir_gen);
3322 		if (IS_ERR(odi))
3323 			return PTR_ERR(odi);
3324 
3325 		odi->gen = dir_gen;
3326 	}
3327 
3328 	odi->last_dir_index_offset = last_dir_index_offset;
3329 	odi->dir_high_seq_ino = max(odi->dir_high_seq_ino, dir_high_seq_ino);
3330 
3331 	return 0;
3332 }
3333 
3334 static int is_waiting_for_move(struct send_ctx *sctx, u64 ino)
3335 {
3336 	struct waiting_dir_move *entry = get_waiting_dir_move(sctx, ino);
3337 
3338 	return entry != NULL;
3339 }
3340 
3341 static int add_waiting_dir_move(struct send_ctx *sctx, u64 ino, bool orphanized)
3342 {
3343 	struct rb_node **p = &sctx->waiting_dir_moves.rb_node;
3344 	struct rb_node *parent = NULL;
3345 	struct waiting_dir_move *entry, *dm;
3346 
3347 	dm = kmalloc(sizeof(*dm), GFP_KERNEL);
3348 	if (!dm)
3349 		return -ENOMEM;
3350 	dm->ino = ino;
3351 	dm->rmdir_ino = 0;
3352 	dm->rmdir_gen = 0;
3353 	dm->orphanized = orphanized;
3354 
3355 	while (*p) {
3356 		parent = *p;
3357 		entry = rb_entry(parent, struct waiting_dir_move, node);
3358 		if (ino < entry->ino) {
3359 			p = &(*p)->rb_left;
3360 		} else if (ino > entry->ino) {
3361 			p = &(*p)->rb_right;
3362 		} else {
3363 			kfree(dm);
3364 			return -EEXIST;
3365 		}
3366 	}
3367 
3368 	rb_link_node(&dm->node, parent, p);
3369 	rb_insert_color(&dm->node, &sctx->waiting_dir_moves);
3370 	return 0;
3371 }
3372 
3373 static struct waiting_dir_move *
3374 get_waiting_dir_move(struct send_ctx *sctx, u64 ino)
3375 {
3376 	struct rb_node *n = sctx->waiting_dir_moves.rb_node;
3377 	struct waiting_dir_move *entry;
3378 
3379 	while (n) {
3380 		entry = rb_entry(n, struct waiting_dir_move, node);
3381 		if (ino < entry->ino)
3382 			n = n->rb_left;
3383 		else if (ino > entry->ino)
3384 			n = n->rb_right;
3385 		else
3386 			return entry;
3387 	}
3388 	return NULL;
3389 }
3390 
3391 static void free_waiting_dir_move(struct send_ctx *sctx,
3392 				  struct waiting_dir_move *dm)
3393 {
3394 	if (!dm)
3395 		return;
3396 	rb_erase(&dm->node, &sctx->waiting_dir_moves);
3397 	kfree(dm);
3398 }
3399 
3400 static int add_pending_dir_move(struct send_ctx *sctx,
3401 				u64 ino,
3402 				u64 ino_gen,
3403 				u64 parent_ino,
3404 				struct list_head *new_refs,
3405 				struct list_head *deleted_refs,
3406 				const bool is_orphan)
3407 {
3408 	struct rb_node **p = &sctx->pending_dir_moves.rb_node;
3409 	struct rb_node *parent = NULL;
3410 	struct pending_dir_move *entry = NULL, *pm;
3411 	struct recorded_ref *cur;
3412 	int exists = 0;
3413 	int ret;
3414 
3415 	pm = kmalloc(sizeof(*pm), GFP_KERNEL);
3416 	if (!pm)
3417 		return -ENOMEM;
3418 	pm->parent_ino = parent_ino;
3419 	pm->ino = ino;
3420 	pm->gen = ino_gen;
3421 	INIT_LIST_HEAD(&pm->list);
3422 	INIT_LIST_HEAD(&pm->update_refs);
3423 	RB_CLEAR_NODE(&pm->node);
3424 
3425 	while (*p) {
3426 		parent = *p;
3427 		entry = rb_entry(parent, struct pending_dir_move, node);
3428 		if (parent_ino < entry->parent_ino) {
3429 			p = &(*p)->rb_left;
3430 		} else if (parent_ino > entry->parent_ino) {
3431 			p = &(*p)->rb_right;
3432 		} else {
3433 			exists = 1;
3434 			break;
3435 		}
3436 	}
3437 
3438 	list_for_each_entry(cur, deleted_refs, list) {
3439 		ret = dup_ref(cur, &pm->update_refs);
3440 		if (ret < 0)
3441 			goto out;
3442 	}
3443 	list_for_each_entry(cur, new_refs, list) {
3444 		ret = dup_ref(cur, &pm->update_refs);
3445 		if (ret < 0)
3446 			goto out;
3447 	}
3448 
3449 	ret = add_waiting_dir_move(sctx, pm->ino, is_orphan);
3450 	if (ret)
3451 		goto out;
3452 
3453 	if (exists) {
3454 		list_add_tail(&pm->list, &entry->list);
3455 	} else {
3456 		rb_link_node(&pm->node, parent, p);
3457 		rb_insert_color(&pm->node, &sctx->pending_dir_moves);
3458 	}
3459 	ret = 0;
3460 out:
3461 	if (ret) {
3462 		__free_recorded_refs(&pm->update_refs);
3463 		kfree(pm);
3464 	}
3465 	return ret;
3466 }
3467 
3468 static struct pending_dir_move *get_pending_dir_moves(struct send_ctx *sctx,
3469 						      u64 parent_ino)
3470 {
3471 	struct rb_node *n = sctx->pending_dir_moves.rb_node;
3472 	struct pending_dir_move *entry;
3473 
3474 	while (n) {
3475 		entry = rb_entry(n, struct pending_dir_move, node);
3476 		if (parent_ino < entry->parent_ino)
3477 			n = n->rb_left;
3478 		else if (parent_ino > entry->parent_ino)
3479 			n = n->rb_right;
3480 		else
3481 			return entry;
3482 	}
3483 	return NULL;
3484 }
3485 
3486 static int path_loop(struct send_ctx *sctx, struct fs_path *name,
3487 		     u64 ino, u64 gen, u64 *ancestor_ino)
3488 {
3489 	int ret = 0;
3490 	u64 parent_inode = 0;
3491 	u64 parent_gen = 0;
3492 	u64 start_ino = ino;
3493 
3494 	*ancestor_ino = 0;
3495 	while (ino != BTRFS_FIRST_FREE_OBJECTID) {
3496 		fs_path_reset(name);
3497 
3498 		if (is_waiting_for_rm(sctx, ino, gen))
3499 			break;
3500 		if (is_waiting_for_move(sctx, ino)) {
3501 			if (*ancestor_ino == 0)
3502 				*ancestor_ino = ino;
3503 			ret = get_first_ref(sctx->parent_root, ino,
3504 					    &parent_inode, &parent_gen, name);
3505 		} else {
3506 			ret = __get_cur_name_and_parent(sctx, ino, gen,
3507 							&parent_inode,
3508 							&parent_gen, name);
3509 			if (ret > 0) {
3510 				ret = 0;
3511 				break;
3512 			}
3513 		}
3514 		if (ret < 0)
3515 			break;
3516 		if (parent_inode == start_ino) {
3517 			ret = 1;
3518 			if (*ancestor_ino == 0)
3519 				*ancestor_ino = ino;
3520 			break;
3521 		}
3522 		ino = parent_inode;
3523 		gen = parent_gen;
3524 	}
3525 	return ret;
3526 }
3527 
3528 static int apply_dir_move(struct send_ctx *sctx, struct pending_dir_move *pm)
3529 {
3530 	struct fs_path *from_path = NULL;
3531 	struct fs_path *to_path = NULL;
3532 	struct fs_path *name = NULL;
3533 	u64 orig_progress = sctx->send_progress;
3534 	struct recorded_ref *cur;
3535 	u64 parent_ino, parent_gen;
3536 	struct waiting_dir_move *dm = NULL;
3537 	u64 rmdir_ino = 0;
3538 	u64 rmdir_gen;
3539 	u64 ancestor;
3540 	bool is_orphan;
3541 	int ret;
3542 
3543 	name = fs_path_alloc();
3544 	from_path = fs_path_alloc();
3545 	if (!name || !from_path) {
3546 		ret = -ENOMEM;
3547 		goto out;
3548 	}
3549 
3550 	dm = get_waiting_dir_move(sctx, pm->ino);
3551 	ASSERT(dm);
3552 	rmdir_ino = dm->rmdir_ino;
3553 	rmdir_gen = dm->rmdir_gen;
3554 	is_orphan = dm->orphanized;
3555 	free_waiting_dir_move(sctx, dm);
3556 
3557 	if (is_orphan) {
3558 		ret = gen_unique_name(sctx, pm->ino,
3559 				      pm->gen, from_path);
3560 	} else {
3561 		ret = get_first_ref(sctx->parent_root, pm->ino,
3562 				    &parent_ino, &parent_gen, name);
3563 		if (ret < 0)
3564 			goto out;
3565 		ret = get_cur_path(sctx, parent_ino, parent_gen,
3566 				   from_path);
3567 		if (ret < 0)
3568 			goto out;
3569 		ret = fs_path_add_path(from_path, name);
3570 	}
3571 	if (ret < 0)
3572 		goto out;
3573 
3574 	sctx->send_progress = sctx->cur_ino + 1;
3575 	ret = path_loop(sctx, name, pm->ino, pm->gen, &ancestor);
3576 	if (ret < 0)
3577 		goto out;
3578 	if (ret) {
3579 		LIST_HEAD(deleted_refs);
3580 		ASSERT(ancestor > BTRFS_FIRST_FREE_OBJECTID);
3581 		ret = add_pending_dir_move(sctx, pm->ino, pm->gen, ancestor,
3582 					   &pm->update_refs, &deleted_refs,
3583 					   is_orphan);
3584 		if (ret < 0)
3585 			goto out;
3586 		if (rmdir_ino) {
3587 			dm = get_waiting_dir_move(sctx, pm->ino);
3588 			ASSERT(dm);
3589 			dm->rmdir_ino = rmdir_ino;
3590 			dm->rmdir_gen = rmdir_gen;
3591 		}
3592 		goto out;
3593 	}
3594 	fs_path_reset(name);
3595 	to_path = name;
3596 	name = NULL;
3597 	ret = get_cur_path(sctx, pm->ino, pm->gen, to_path);
3598 	if (ret < 0)
3599 		goto out;
3600 
3601 	ret = send_rename(sctx, from_path, to_path);
3602 	if (ret < 0)
3603 		goto out;
3604 
3605 	if (rmdir_ino) {
3606 		struct orphan_dir_info *odi;
3607 		u64 gen;
3608 
3609 		odi = get_orphan_dir_info(sctx, rmdir_ino, rmdir_gen);
3610 		if (!odi) {
3611 			/* already deleted */
3612 			goto finish;
3613 		}
3614 		gen = odi->gen;
3615 
3616 		ret = can_rmdir(sctx, rmdir_ino, gen);
3617 		if (ret < 0)
3618 			goto out;
3619 		if (!ret)
3620 			goto finish;
3621 
3622 		name = fs_path_alloc();
3623 		if (!name) {
3624 			ret = -ENOMEM;
3625 			goto out;
3626 		}
3627 		ret = get_cur_path(sctx, rmdir_ino, gen, name);
3628 		if (ret < 0)
3629 			goto out;
3630 		ret = send_rmdir(sctx, name);
3631 		if (ret < 0)
3632 			goto out;
3633 	}
3634 
3635 finish:
3636 	ret = cache_dir_utimes(sctx, pm->ino, pm->gen);
3637 	if (ret < 0)
3638 		goto out;
3639 
3640 	/*
3641 	 * After rename/move, need to update the utimes of both new parent(s)
3642 	 * and old parent(s).
3643 	 */
3644 	list_for_each_entry(cur, &pm->update_refs, list) {
3645 		/*
3646 		 * The parent inode might have been deleted in the send snapshot
3647 		 */
3648 		ret = get_inode_info(sctx->send_root, cur->dir, NULL);
3649 		if (ret == -ENOENT) {
3650 			ret = 0;
3651 			continue;
3652 		}
3653 		if (ret < 0)
3654 			goto out;
3655 
3656 		ret = cache_dir_utimes(sctx, cur->dir, cur->dir_gen);
3657 		if (ret < 0)
3658 			goto out;
3659 	}
3660 
3661 out:
3662 	fs_path_free(name);
3663 	fs_path_free(from_path);
3664 	fs_path_free(to_path);
3665 	sctx->send_progress = orig_progress;
3666 
3667 	return ret;
3668 }
3669 
3670 static void free_pending_move(struct send_ctx *sctx, struct pending_dir_move *m)
3671 {
3672 	if (!list_empty(&m->list))
3673 		list_del(&m->list);
3674 	if (!RB_EMPTY_NODE(&m->node))
3675 		rb_erase(&m->node, &sctx->pending_dir_moves);
3676 	__free_recorded_refs(&m->update_refs);
3677 	kfree(m);
3678 }
3679 
3680 static void tail_append_pending_moves(struct send_ctx *sctx,
3681 				      struct pending_dir_move *moves,
3682 				      struct list_head *stack)
3683 {
3684 	if (list_empty(&moves->list)) {
3685 		list_add_tail(&moves->list, stack);
3686 	} else {
3687 		LIST_HEAD(list);
3688 		list_splice_init(&moves->list, &list);
3689 		list_add_tail(&moves->list, stack);
3690 		list_splice_tail(&list, stack);
3691 	}
3692 	if (!RB_EMPTY_NODE(&moves->node)) {
3693 		rb_erase(&moves->node, &sctx->pending_dir_moves);
3694 		RB_CLEAR_NODE(&moves->node);
3695 	}
3696 }
3697 
3698 static int apply_children_dir_moves(struct send_ctx *sctx)
3699 {
3700 	struct pending_dir_move *pm;
3701 	LIST_HEAD(stack);
3702 	u64 parent_ino = sctx->cur_ino;
3703 	int ret = 0;
3704 
3705 	pm = get_pending_dir_moves(sctx, parent_ino);
3706 	if (!pm)
3707 		return 0;
3708 
3709 	tail_append_pending_moves(sctx, pm, &stack);
3710 
3711 	while (!list_empty(&stack)) {
3712 		pm = list_first_entry(&stack, struct pending_dir_move, list);
3713 		parent_ino = pm->ino;
3714 		ret = apply_dir_move(sctx, pm);
3715 		free_pending_move(sctx, pm);
3716 		if (ret)
3717 			goto out;
3718 		pm = get_pending_dir_moves(sctx, parent_ino);
3719 		if (pm)
3720 			tail_append_pending_moves(sctx, pm, &stack);
3721 	}
3722 	return 0;
3723 
3724 out:
3725 	while (!list_empty(&stack)) {
3726 		pm = list_first_entry(&stack, struct pending_dir_move, list);
3727 		free_pending_move(sctx, pm);
3728 	}
3729 	return ret;
3730 }
3731 
3732 /*
3733  * We might need to delay a directory rename even when no ancestor directory
3734  * (in the send root) with a higher inode number than ours (sctx->cur_ino) was
3735  * renamed. This happens when we rename a directory to the old name (the name
3736  * in the parent root) of some other unrelated directory that got its rename
3737  * delayed due to some ancestor with higher number that got renamed.
3738  *
3739  * Example:
3740  *
3741  * Parent snapshot:
3742  * .                                       (ino 256)
3743  * |---- a/                                (ino 257)
3744  * |     |---- file                        (ino 260)
3745  * |
3746  * |---- b/                                (ino 258)
3747  * |---- c/                                (ino 259)
3748  *
3749  * Send snapshot:
3750  * .                                       (ino 256)
3751  * |---- a/                                (ino 258)
3752  * |---- x/                                (ino 259)
3753  *       |---- y/                          (ino 257)
3754  *             |----- file                 (ino 260)
3755  *
3756  * Here we can not rename 258 from 'b' to 'a' without the rename of inode 257
3757  * from 'a' to 'x/y' happening first, which in turn depends on the rename of
3758  * inode 259 from 'c' to 'x'. So the order of rename commands the send stream
3759  * must issue is:
3760  *
3761  * 1 - rename 259 from 'c' to 'x'
3762  * 2 - rename 257 from 'a' to 'x/y'
3763  * 3 - rename 258 from 'b' to 'a'
3764  *
3765  * Returns 1 if the rename of sctx->cur_ino needs to be delayed, 0 if it can
3766  * be done right away and < 0 on error.
3767  */
3768 static int wait_for_dest_dir_move(struct send_ctx *sctx,
3769 				  struct recorded_ref *parent_ref,
3770 				  const bool is_orphan)
3771 {
3772 	struct btrfs_fs_info *fs_info = sctx->parent_root->fs_info;
3773 	struct btrfs_path *path;
3774 	struct btrfs_key key;
3775 	struct btrfs_key di_key;
3776 	struct btrfs_dir_item *di;
3777 	u64 left_gen;
3778 	u64 right_gen;
3779 	int ret = 0;
3780 	struct waiting_dir_move *wdm;
3781 
3782 	if (RB_EMPTY_ROOT(&sctx->waiting_dir_moves))
3783 		return 0;
3784 
3785 	path = alloc_path_for_send();
3786 	if (!path)
3787 		return -ENOMEM;
3788 
3789 	key.objectid = parent_ref->dir;
3790 	key.type = BTRFS_DIR_ITEM_KEY;
3791 	key.offset = btrfs_name_hash(parent_ref->name, parent_ref->name_len);
3792 
3793 	ret = btrfs_search_slot(NULL, sctx->parent_root, &key, path, 0, 0);
3794 	if (ret < 0) {
3795 		goto out;
3796 	} else if (ret > 0) {
3797 		ret = 0;
3798 		goto out;
3799 	}
3800 
3801 	di = btrfs_match_dir_item_name(fs_info, path, parent_ref->name,
3802 				       parent_ref->name_len);
3803 	if (!di) {
3804 		ret = 0;
3805 		goto out;
3806 	}
3807 	/*
3808 	 * di_key.objectid has the number of the inode that has a dentry in the
3809 	 * parent directory with the same name that sctx->cur_ino is being
3810 	 * renamed to. We need to check if that inode is in the send root as
3811 	 * well and if it is currently marked as an inode with a pending rename,
3812 	 * if it is, we need to delay the rename of sctx->cur_ino as well, so
3813 	 * that it happens after that other inode is renamed.
3814 	 */
3815 	btrfs_dir_item_key_to_cpu(path->nodes[0], di, &di_key);
3816 	if (di_key.type != BTRFS_INODE_ITEM_KEY) {
3817 		ret = 0;
3818 		goto out;
3819 	}
3820 
3821 	ret = get_inode_gen(sctx->parent_root, di_key.objectid, &left_gen);
3822 	if (ret < 0)
3823 		goto out;
3824 	ret = get_inode_gen(sctx->send_root, di_key.objectid, &right_gen);
3825 	if (ret < 0) {
3826 		if (ret == -ENOENT)
3827 			ret = 0;
3828 		goto out;
3829 	}
3830 
3831 	/* Different inode, no need to delay the rename of sctx->cur_ino */
3832 	if (right_gen != left_gen) {
3833 		ret = 0;
3834 		goto out;
3835 	}
3836 
3837 	wdm = get_waiting_dir_move(sctx, di_key.objectid);
3838 	if (wdm && !wdm->orphanized) {
3839 		ret = add_pending_dir_move(sctx,
3840 					   sctx->cur_ino,
3841 					   sctx->cur_inode_gen,
3842 					   di_key.objectid,
3843 					   &sctx->new_refs,
3844 					   &sctx->deleted_refs,
3845 					   is_orphan);
3846 		if (!ret)
3847 			ret = 1;
3848 	}
3849 out:
3850 	btrfs_free_path(path);
3851 	return ret;
3852 }
3853 
3854 /*
3855  * Check if inode ino2, or any of its ancestors, is inode ino1.
3856  * Return 1 if true, 0 if false and < 0 on error.
3857  */
3858 static int check_ino_in_path(struct btrfs_root *root,
3859 			     const u64 ino1,
3860 			     const u64 ino1_gen,
3861 			     const u64 ino2,
3862 			     const u64 ino2_gen,
3863 			     struct fs_path *fs_path)
3864 {
3865 	u64 ino = ino2;
3866 
3867 	if (ino1 == ino2)
3868 		return ino1_gen == ino2_gen;
3869 
3870 	while (ino > BTRFS_FIRST_FREE_OBJECTID) {
3871 		u64 parent;
3872 		u64 parent_gen;
3873 		int ret;
3874 
3875 		fs_path_reset(fs_path);
3876 		ret = get_first_ref(root, ino, &parent, &parent_gen, fs_path);
3877 		if (ret < 0)
3878 			return ret;
3879 		if (parent == ino1)
3880 			return parent_gen == ino1_gen;
3881 		ino = parent;
3882 	}
3883 	return 0;
3884 }
3885 
3886 /*
3887  * Check if inode ino1 is an ancestor of inode ino2 in the given root for any
3888  * possible path (in case ino2 is not a directory and has multiple hard links).
3889  * Return 1 if true, 0 if false and < 0 on error.
3890  */
3891 static int is_ancestor(struct btrfs_root *root,
3892 		       const u64 ino1,
3893 		       const u64 ino1_gen,
3894 		       const u64 ino2,
3895 		       struct fs_path *fs_path)
3896 {
3897 	bool free_fs_path = false;
3898 	int ret = 0;
3899 	int iter_ret = 0;
3900 	struct btrfs_path *path = NULL;
3901 	struct btrfs_key key;
3902 
3903 	if (!fs_path) {
3904 		fs_path = fs_path_alloc();
3905 		if (!fs_path)
3906 			return -ENOMEM;
3907 		free_fs_path = true;
3908 	}
3909 
3910 	path = alloc_path_for_send();
3911 	if (!path) {
3912 		ret = -ENOMEM;
3913 		goto out;
3914 	}
3915 
3916 	key.objectid = ino2;
3917 	key.type = BTRFS_INODE_REF_KEY;
3918 	key.offset = 0;
3919 
3920 	btrfs_for_each_slot(root, &key, &key, path, iter_ret) {
3921 		struct extent_buffer *leaf = path->nodes[0];
3922 		int slot = path->slots[0];
3923 		u32 cur_offset = 0;
3924 		u32 item_size;
3925 
3926 		if (key.objectid != ino2)
3927 			break;
3928 		if (key.type != BTRFS_INODE_REF_KEY &&
3929 		    key.type != BTRFS_INODE_EXTREF_KEY)
3930 			break;
3931 
3932 		item_size = btrfs_item_size(leaf, slot);
3933 		while (cur_offset < item_size) {
3934 			u64 parent;
3935 			u64 parent_gen;
3936 
3937 			if (key.type == BTRFS_INODE_EXTREF_KEY) {
3938 				unsigned long ptr;
3939 				struct btrfs_inode_extref *extref;
3940 
3941 				ptr = btrfs_item_ptr_offset(leaf, slot);
3942 				extref = (struct btrfs_inode_extref *)
3943 					(ptr + cur_offset);
3944 				parent = btrfs_inode_extref_parent(leaf,
3945 								   extref);
3946 				cur_offset += sizeof(*extref);
3947 				cur_offset += btrfs_inode_extref_name_len(leaf,
3948 								  extref);
3949 			} else {
3950 				parent = key.offset;
3951 				cur_offset = item_size;
3952 			}
3953 
3954 			ret = get_inode_gen(root, parent, &parent_gen);
3955 			if (ret < 0)
3956 				goto out;
3957 			ret = check_ino_in_path(root, ino1, ino1_gen,
3958 						parent, parent_gen, fs_path);
3959 			if (ret)
3960 				goto out;
3961 		}
3962 	}
3963 	ret = 0;
3964 	if (iter_ret < 0)
3965 		ret = iter_ret;
3966 
3967 out:
3968 	btrfs_free_path(path);
3969 	if (free_fs_path)
3970 		fs_path_free(fs_path);
3971 	return ret;
3972 }
3973 
3974 static int wait_for_parent_move(struct send_ctx *sctx,
3975 				struct recorded_ref *parent_ref,
3976 				const bool is_orphan)
3977 {
3978 	int ret = 0;
3979 	u64 ino = parent_ref->dir;
3980 	u64 ino_gen = parent_ref->dir_gen;
3981 	u64 parent_ino_before, parent_ino_after;
3982 	struct fs_path *path_before = NULL;
3983 	struct fs_path *path_after = NULL;
3984 	int len1, len2;
3985 
3986 	path_after = fs_path_alloc();
3987 	path_before = fs_path_alloc();
3988 	if (!path_after || !path_before) {
3989 		ret = -ENOMEM;
3990 		goto out;
3991 	}
3992 
3993 	/*
3994 	 * Our current directory inode may not yet be renamed/moved because some
3995 	 * ancestor (immediate or not) has to be renamed/moved first. So find if
3996 	 * such ancestor exists and make sure our own rename/move happens after
3997 	 * that ancestor is processed to avoid path build infinite loops (done
3998 	 * at get_cur_path()).
3999 	 */
4000 	while (ino > BTRFS_FIRST_FREE_OBJECTID) {
4001 		u64 parent_ino_after_gen;
4002 
4003 		if (is_waiting_for_move(sctx, ino)) {
4004 			/*
4005 			 * If the current inode is an ancestor of ino in the
4006 			 * parent root, we need to delay the rename of the
4007 			 * current inode, otherwise don't delayed the rename
4008 			 * because we can end up with a circular dependency
4009 			 * of renames, resulting in some directories never
4010 			 * getting the respective rename operations issued in
4011 			 * the send stream or getting into infinite path build
4012 			 * loops.
4013 			 */
4014 			ret = is_ancestor(sctx->parent_root,
4015 					  sctx->cur_ino, sctx->cur_inode_gen,
4016 					  ino, path_before);
4017 			if (ret)
4018 				break;
4019 		}
4020 
4021 		fs_path_reset(path_before);
4022 		fs_path_reset(path_after);
4023 
4024 		ret = get_first_ref(sctx->send_root, ino, &parent_ino_after,
4025 				    &parent_ino_after_gen, path_after);
4026 		if (ret < 0)
4027 			goto out;
4028 		ret = get_first_ref(sctx->parent_root, ino, &parent_ino_before,
4029 				    NULL, path_before);
4030 		if (ret < 0 && ret != -ENOENT) {
4031 			goto out;
4032 		} else if (ret == -ENOENT) {
4033 			ret = 0;
4034 			break;
4035 		}
4036 
4037 		len1 = fs_path_len(path_before);
4038 		len2 = fs_path_len(path_after);
4039 		if (ino > sctx->cur_ino &&
4040 		    (parent_ino_before != parent_ino_after || len1 != len2 ||
4041 		     memcmp(path_before->start, path_after->start, len1))) {
4042 			u64 parent_ino_gen;
4043 
4044 			ret = get_inode_gen(sctx->parent_root, ino, &parent_ino_gen);
4045 			if (ret < 0)
4046 				goto out;
4047 			if (ino_gen == parent_ino_gen) {
4048 				ret = 1;
4049 				break;
4050 			}
4051 		}
4052 		ino = parent_ino_after;
4053 		ino_gen = parent_ino_after_gen;
4054 	}
4055 
4056 out:
4057 	fs_path_free(path_before);
4058 	fs_path_free(path_after);
4059 
4060 	if (ret == 1) {
4061 		ret = add_pending_dir_move(sctx,
4062 					   sctx->cur_ino,
4063 					   sctx->cur_inode_gen,
4064 					   ino,
4065 					   &sctx->new_refs,
4066 					   &sctx->deleted_refs,
4067 					   is_orphan);
4068 		if (!ret)
4069 			ret = 1;
4070 	}
4071 
4072 	return ret;
4073 }
4074 
4075 static int update_ref_path(struct send_ctx *sctx, struct recorded_ref *ref)
4076 {
4077 	int ret;
4078 	struct fs_path *new_path;
4079 
4080 	/*
4081 	 * Our reference's name member points to its full_path member string, so
4082 	 * we use here a new path.
4083 	 */
4084 	new_path = fs_path_alloc();
4085 	if (!new_path)
4086 		return -ENOMEM;
4087 
4088 	ret = get_cur_path(sctx, ref->dir, ref->dir_gen, new_path);
4089 	if (ret < 0) {
4090 		fs_path_free(new_path);
4091 		return ret;
4092 	}
4093 	ret = fs_path_add(new_path, ref->name, ref->name_len);
4094 	if (ret < 0) {
4095 		fs_path_free(new_path);
4096 		return ret;
4097 	}
4098 
4099 	fs_path_free(ref->full_path);
4100 	set_ref_path(ref, new_path);
4101 
4102 	return 0;
4103 }
4104 
4105 /*
4106  * When processing the new references for an inode we may orphanize an existing
4107  * directory inode because its old name conflicts with one of the new references
4108  * of the current inode. Later, when processing another new reference of our
4109  * inode, we might need to orphanize another inode, but the path we have in the
4110  * reference reflects the pre-orphanization name of the directory we previously
4111  * orphanized. For example:
4112  *
4113  * parent snapshot looks like:
4114  *
4115  * .                                     (ino 256)
4116  * |----- f1                             (ino 257)
4117  * |----- f2                             (ino 258)
4118  * |----- d1/                            (ino 259)
4119  *        |----- d2/                     (ino 260)
4120  *
4121  * send snapshot looks like:
4122  *
4123  * .                                     (ino 256)
4124  * |----- d1                             (ino 258)
4125  * |----- f2/                            (ino 259)
4126  *        |----- f2_link/                (ino 260)
4127  *        |       |----- f1              (ino 257)
4128  *        |
4129  *        |----- d2                      (ino 258)
4130  *
4131  * When processing inode 257 we compute the name for inode 259 as "d1", and we
4132  * cache it in the name cache. Later when we start processing inode 258, when
4133  * collecting all its new references we set a full path of "d1/d2" for its new
4134  * reference with name "d2". When we start processing the new references we
4135  * start by processing the new reference with name "d1", and this results in
4136  * orphanizing inode 259, since its old reference causes a conflict. Then we
4137  * move on the next new reference, with name "d2", and we find out we must
4138  * orphanize inode 260, as its old reference conflicts with ours - but for the
4139  * orphanization we use a source path corresponding to the path we stored in the
4140  * new reference, which is "d1/d2" and not "o259-6-0/d2" - this makes the
4141  * receiver fail since the path component "d1/" no longer exists, it was renamed
4142  * to "o259-6-0/" when processing the previous new reference. So in this case we
4143  * must recompute the path in the new reference and use it for the new
4144  * orphanization operation.
4145  */
4146 static int refresh_ref_path(struct send_ctx *sctx, struct recorded_ref *ref)
4147 {
4148 	char *name;
4149 	int ret;
4150 
4151 	name = kmemdup(ref->name, ref->name_len, GFP_KERNEL);
4152 	if (!name)
4153 		return -ENOMEM;
4154 
4155 	fs_path_reset(ref->full_path);
4156 	ret = get_cur_path(sctx, ref->dir, ref->dir_gen, ref->full_path);
4157 	if (ret < 0)
4158 		goto out;
4159 
4160 	ret = fs_path_add(ref->full_path, name, ref->name_len);
4161 	if (ret < 0)
4162 		goto out;
4163 
4164 	/* Update the reference's base name pointer. */
4165 	set_ref_path(ref, ref->full_path);
4166 out:
4167 	kfree(name);
4168 	return ret;
4169 }
4170 
4171 /*
4172  * This does all the move/link/unlink/rmdir magic.
4173  */
4174 static int process_recorded_refs(struct send_ctx *sctx, int *pending_move)
4175 {
4176 	struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
4177 	int ret = 0;
4178 	struct recorded_ref *cur;
4179 	struct recorded_ref *cur2;
4180 	LIST_HEAD(check_dirs);
4181 	struct fs_path *valid_path = NULL;
4182 	u64 ow_inode = 0;
4183 	u64 ow_gen;
4184 	u64 ow_mode;
4185 	int did_overwrite = 0;
4186 	int is_orphan = 0;
4187 	u64 last_dir_ino_rm = 0;
4188 	bool can_rename = true;
4189 	bool orphanized_dir = false;
4190 	bool orphanized_ancestor = false;
4191 
4192 	btrfs_debug(fs_info, "process_recorded_refs %llu", sctx->cur_ino);
4193 
4194 	/*
4195 	 * This should never happen as the root dir always has the same ref
4196 	 * which is always '..'
4197 	 */
4198 	if (unlikely(sctx->cur_ino <= BTRFS_FIRST_FREE_OBJECTID)) {
4199 		btrfs_err(fs_info,
4200 			  "send: unexpected inode %llu in process_recorded_refs()",
4201 			  sctx->cur_ino);
4202 		ret = -EINVAL;
4203 		goto out;
4204 	}
4205 
4206 	valid_path = fs_path_alloc();
4207 	if (!valid_path) {
4208 		ret = -ENOMEM;
4209 		goto out;
4210 	}
4211 
4212 	/*
4213 	 * First, check if the first ref of the current inode was overwritten
4214 	 * before. If yes, we know that the current inode was already orphanized
4215 	 * and thus use the orphan name. If not, we can use get_cur_path to
4216 	 * get the path of the first ref as it would like while receiving at
4217 	 * this point in time.
4218 	 * New inodes are always orphan at the beginning, so force to use the
4219 	 * orphan name in this case.
4220 	 * The first ref is stored in valid_path and will be updated if it
4221 	 * gets moved around.
4222 	 */
4223 	if (!sctx->cur_inode_new) {
4224 		ret = did_overwrite_first_ref(sctx, sctx->cur_ino,
4225 				sctx->cur_inode_gen);
4226 		if (ret < 0)
4227 			goto out;
4228 		if (ret)
4229 			did_overwrite = 1;
4230 	}
4231 	if (sctx->cur_inode_new || did_overwrite) {
4232 		ret = gen_unique_name(sctx, sctx->cur_ino,
4233 				sctx->cur_inode_gen, valid_path);
4234 		if (ret < 0)
4235 			goto out;
4236 		is_orphan = 1;
4237 	} else {
4238 		ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen,
4239 				valid_path);
4240 		if (ret < 0)
4241 			goto out;
4242 	}
4243 
4244 	/*
4245 	 * Before doing any rename and link operations, do a first pass on the
4246 	 * new references to orphanize any unprocessed inodes that may have a
4247 	 * reference that conflicts with one of the new references of the current
4248 	 * inode. This needs to happen first because a new reference may conflict
4249 	 * with the old reference of a parent directory, so we must make sure
4250 	 * that the path used for link and rename commands don't use an
4251 	 * orphanized name when an ancestor was not yet orphanized.
4252 	 *
4253 	 * Example:
4254 	 *
4255 	 * Parent snapshot:
4256 	 *
4257 	 * .                                                      (ino 256)
4258 	 * |----- testdir/                                        (ino 259)
4259 	 * |          |----- a                                    (ino 257)
4260 	 * |
4261 	 * |----- b                                               (ino 258)
4262 	 *
4263 	 * Send snapshot:
4264 	 *
4265 	 * .                                                      (ino 256)
4266 	 * |----- testdir_2/                                      (ino 259)
4267 	 * |          |----- a                                    (ino 260)
4268 	 * |
4269 	 * |----- testdir                                         (ino 257)
4270 	 * |----- b                                               (ino 257)
4271 	 * |----- b2                                              (ino 258)
4272 	 *
4273 	 * Processing the new reference for inode 257 with name "b" may happen
4274 	 * before processing the new reference with name "testdir". If so, we
4275 	 * must make sure that by the time we send a link command to create the
4276 	 * hard link "b", inode 259 was already orphanized, since the generated
4277 	 * path in "valid_path" already contains the orphanized name for 259.
4278 	 * We are processing inode 257, so only later when processing 259 we do
4279 	 * the rename operation to change its temporary (orphanized) name to
4280 	 * "testdir_2".
4281 	 */
4282 	list_for_each_entry(cur, &sctx->new_refs, list) {
4283 		ret = get_cur_inode_state(sctx, cur->dir, cur->dir_gen, NULL, NULL);
4284 		if (ret < 0)
4285 			goto out;
4286 		if (ret == inode_state_will_create)
4287 			continue;
4288 
4289 		/*
4290 		 * Check if this new ref would overwrite the first ref of another
4291 		 * unprocessed inode. If yes, orphanize the overwritten inode.
4292 		 * If we find an overwritten ref that is not the first ref,
4293 		 * simply unlink it.
4294 		 */
4295 		ret = will_overwrite_ref(sctx, cur->dir, cur->dir_gen,
4296 				cur->name, cur->name_len,
4297 				&ow_inode, &ow_gen, &ow_mode);
4298 		if (ret < 0)
4299 			goto out;
4300 		if (ret) {
4301 			ret = is_first_ref(sctx->parent_root,
4302 					   ow_inode, cur->dir, cur->name,
4303 					   cur->name_len);
4304 			if (ret < 0)
4305 				goto out;
4306 			if (ret) {
4307 				struct name_cache_entry *nce;
4308 				struct waiting_dir_move *wdm;
4309 
4310 				if (orphanized_dir) {
4311 					ret = refresh_ref_path(sctx, cur);
4312 					if (ret < 0)
4313 						goto out;
4314 				}
4315 
4316 				ret = orphanize_inode(sctx, ow_inode, ow_gen,
4317 						cur->full_path);
4318 				if (ret < 0)
4319 					goto out;
4320 				if (S_ISDIR(ow_mode))
4321 					orphanized_dir = true;
4322 
4323 				/*
4324 				 * If ow_inode has its rename operation delayed
4325 				 * make sure that its orphanized name is used in
4326 				 * the source path when performing its rename
4327 				 * operation.
4328 				 */
4329 				wdm = get_waiting_dir_move(sctx, ow_inode);
4330 				if (wdm)
4331 					wdm->orphanized = true;
4332 
4333 				/*
4334 				 * Make sure we clear our orphanized inode's
4335 				 * name from the name cache. This is because the
4336 				 * inode ow_inode might be an ancestor of some
4337 				 * other inode that will be orphanized as well
4338 				 * later and has an inode number greater than
4339 				 * sctx->send_progress. We need to prevent
4340 				 * future name lookups from using the old name
4341 				 * and get instead the orphan name.
4342 				 */
4343 				nce = name_cache_search(sctx, ow_inode, ow_gen);
4344 				if (nce)
4345 					btrfs_lru_cache_remove(&sctx->name_cache,
4346 							       &nce->entry);
4347 
4348 				/*
4349 				 * ow_inode might currently be an ancestor of
4350 				 * cur_ino, therefore compute valid_path (the
4351 				 * current path of cur_ino) again because it
4352 				 * might contain the pre-orphanization name of
4353 				 * ow_inode, which is no longer valid.
4354 				 */
4355 				ret = is_ancestor(sctx->parent_root,
4356 						  ow_inode, ow_gen,
4357 						  sctx->cur_ino, NULL);
4358 				if (ret > 0) {
4359 					orphanized_ancestor = true;
4360 					fs_path_reset(valid_path);
4361 					ret = get_cur_path(sctx, sctx->cur_ino,
4362 							   sctx->cur_inode_gen,
4363 							   valid_path);
4364 				}
4365 				if (ret < 0)
4366 					goto out;
4367 			} else {
4368 				/*
4369 				 * If we previously orphanized a directory that
4370 				 * collided with a new reference that we already
4371 				 * processed, recompute the current path because
4372 				 * that directory may be part of the path.
4373 				 */
4374 				if (orphanized_dir) {
4375 					ret = refresh_ref_path(sctx, cur);
4376 					if (ret < 0)
4377 						goto out;
4378 				}
4379 				ret = send_unlink(sctx, cur->full_path);
4380 				if (ret < 0)
4381 					goto out;
4382 			}
4383 		}
4384 
4385 	}
4386 
4387 	list_for_each_entry(cur, &sctx->new_refs, list) {
4388 		/*
4389 		 * We may have refs where the parent directory does not exist
4390 		 * yet. This happens if the parent directories inum is higher
4391 		 * than the current inum. To handle this case, we create the
4392 		 * parent directory out of order. But we need to check if this
4393 		 * did already happen before due to other refs in the same dir.
4394 		 */
4395 		ret = get_cur_inode_state(sctx, cur->dir, cur->dir_gen, NULL, NULL);
4396 		if (ret < 0)
4397 			goto out;
4398 		if (ret == inode_state_will_create) {
4399 			ret = 0;
4400 			/*
4401 			 * First check if any of the current inodes refs did
4402 			 * already create the dir.
4403 			 */
4404 			list_for_each_entry(cur2, &sctx->new_refs, list) {
4405 				if (cur == cur2)
4406 					break;
4407 				if (cur2->dir == cur->dir) {
4408 					ret = 1;
4409 					break;
4410 				}
4411 			}
4412 
4413 			/*
4414 			 * If that did not happen, check if a previous inode
4415 			 * did already create the dir.
4416 			 */
4417 			if (!ret)
4418 				ret = did_create_dir(sctx, cur->dir);
4419 			if (ret < 0)
4420 				goto out;
4421 			if (!ret) {
4422 				ret = send_create_inode(sctx, cur->dir);
4423 				if (ret < 0)
4424 					goto out;
4425 				cache_dir_created(sctx, cur->dir);
4426 			}
4427 		}
4428 
4429 		if (S_ISDIR(sctx->cur_inode_mode) && sctx->parent_root) {
4430 			ret = wait_for_dest_dir_move(sctx, cur, is_orphan);
4431 			if (ret < 0)
4432 				goto out;
4433 			if (ret == 1) {
4434 				can_rename = false;
4435 				*pending_move = 1;
4436 			}
4437 		}
4438 
4439 		if (S_ISDIR(sctx->cur_inode_mode) && sctx->parent_root &&
4440 		    can_rename) {
4441 			ret = wait_for_parent_move(sctx, cur, is_orphan);
4442 			if (ret < 0)
4443 				goto out;
4444 			if (ret == 1) {
4445 				can_rename = false;
4446 				*pending_move = 1;
4447 			}
4448 		}
4449 
4450 		/*
4451 		 * link/move the ref to the new place. If we have an orphan
4452 		 * inode, move it and update valid_path. If not, link or move
4453 		 * it depending on the inode mode.
4454 		 */
4455 		if (is_orphan && can_rename) {
4456 			ret = send_rename(sctx, valid_path, cur->full_path);
4457 			if (ret < 0)
4458 				goto out;
4459 			is_orphan = 0;
4460 			ret = fs_path_copy(valid_path, cur->full_path);
4461 			if (ret < 0)
4462 				goto out;
4463 		} else if (can_rename) {
4464 			if (S_ISDIR(sctx->cur_inode_mode)) {
4465 				/*
4466 				 * Dirs can't be linked, so move it. For moved
4467 				 * dirs, we always have one new and one deleted
4468 				 * ref. The deleted ref is ignored later.
4469 				 */
4470 				ret = send_rename(sctx, valid_path,
4471 						  cur->full_path);
4472 				if (!ret)
4473 					ret = fs_path_copy(valid_path,
4474 							   cur->full_path);
4475 				if (ret < 0)
4476 					goto out;
4477 			} else {
4478 				/*
4479 				 * We might have previously orphanized an inode
4480 				 * which is an ancestor of our current inode,
4481 				 * so our reference's full path, which was
4482 				 * computed before any such orphanizations, must
4483 				 * be updated.
4484 				 */
4485 				if (orphanized_dir) {
4486 					ret = update_ref_path(sctx, cur);
4487 					if (ret < 0)
4488 						goto out;
4489 				}
4490 				ret = send_link(sctx, cur->full_path,
4491 						valid_path);
4492 				if (ret < 0)
4493 					goto out;
4494 			}
4495 		}
4496 		ret = dup_ref(cur, &check_dirs);
4497 		if (ret < 0)
4498 			goto out;
4499 	}
4500 
4501 	if (S_ISDIR(sctx->cur_inode_mode) && sctx->cur_inode_deleted) {
4502 		/*
4503 		 * Check if we can already rmdir the directory. If not,
4504 		 * orphanize it. For every dir item inside that gets deleted
4505 		 * later, we do this check again and rmdir it then if possible.
4506 		 * See the use of check_dirs for more details.
4507 		 */
4508 		ret = can_rmdir(sctx, sctx->cur_ino, sctx->cur_inode_gen);
4509 		if (ret < 0)
4510 			goto out;
4511 		if (ret) {
4512 			ret = send_rmdir(sctx, valid_path);
4513 			if (ret < 0)
4514 				goto out;
4515 		} else if (!is_orphan) {
4516 			ret = orphanize_inode(sctx, sctx->cur_ino,
4517 					sctx->cur_inode_gen, valid_path);
4518 			if (ret < 0)
4519 				goto out;
4520 			is_orphan = 1;
4521 		}
4522 
4523 		list_for_each_entry(cur, &sctx->deleted_refs, list) {
4524 			ret = dup_ref(cur, &check_dirs);
4525 			if (ret < 0)
4526 				goto out;
4527 		}
4528 	} else if (S_ISDIR(sctx->cur_inode_mode) &&
4529 		   !list_empty(&sctx->deleted_refs)) {
4530 		/*
4531 		 * We have a moved dir. Add the old parent to check_dirs
4532 		 */
4533 		cur = list_entry(sctx->deleted_refs.next, struct recorded_ref,
4534 				list);
4535 		ret = dup_ref(cur, &check_dirs);
4536 		if (ret < 0)
4537 			goto out;
4538 	} else if (!S_ISDIR(sctx->cur_inode_mode)) {
4539 		/*
4540 		 * We have a non dir inode. Go through all deleted refs and
4541 		 * unlink them if they were not already overwritten by other
4542 		 * inodes.
4543 		 */
4544 		list_for_each_entry(cur, &sctx->deleted_refs, list) {
4545 			ret = did_overwrite_ref(sctx, cur->dir, cur->dir_gen,
4546 					sctx->cur_ino, sctx->cur_inode_gen,
4547 					cur->name, cur->name_len);
4548 			if (ret < 0)
4549 				goto out;
4550 			if (!ret) {
4551 				/*
4552 				 * If we orphanized any ancestor before, we need
4553 				 * to recompute the full path for deleted names,
4554 				 * since any such path was computed before we
4555 				 * processed any references and orphanized any
4556 				 * ancestor inode.
4557 				 */
4558 				if (orphanized_ancestor) {
4559 					ret = update_ref_path(sctx, cur);
4560 					if (ret < 0)
4561 						goto out;
4562 				}
4563 				ret = send_unlink(sctx, cur->full_path);
4564 				if (ret < 0)
4565 					goto out;
4566 			}
4567 			ret = dup_ref(cur, &check_dirs);
4568 			if (ret < 0)
4569 				goto out;
4570 		}
4571 		/*
4572 		 * If the inode is still orphan, unlink the orphan. This may
4573 		 * happen when a previous inode did overwrite the first ref
4574 		 * of this inode and no new refs were added for the current
4575 		 * inode. Unlinking does not mean that the inode is deleted in
4576 		 * all cases. There may still be links to this inode in other
4577 		 * places.
4578 		 */
4579 		if (is_orphan) {
4580 			ret = send_unlink(sctx, valid_path);
4581 			if (ret < 0)
4582 				goto out;
4583 		}
4584 	}
4585 
4586 	/*
4587 	 * We did collect all parent dirs where cur_inode was once located. We
4588 	 * now go through all these dirs and check if they are pending for
4589 	 * deletion and if it's finally possible to perform the rmdir now.
4590 	 * We also update the inode stats of the parent dirs here.
4591 	 */
4592 	list_for_each_entry(cur, &check_dirs, list) {
4593 		/*
4594 		 * In case we had refs into dirs that were not processed yet,
4595 		 * we don't need to do the utime and rmdir logic for these dirs.
4596 		 * The dir will be processed later.
4597 		 */
4598 		if (cur->dir > sctx->cur_ino)
4599 			continue;
4600 
4601 		ret = get_cur_inode_state(sctx, cur->dir, cur->dir_gen, NULL, NULL);
4602 		if (ret < 0)
4603 			goto out;
4604 
4605 		if (ret == inode_state_did_create ||
4606 		    ret == inode_state_no_change) {
4607 			ret = cache_dir_utimes(sctx, cur->dir, cur->dir_gen);
4608 			if (ret < 0)
4609 				goto out;
4610 		} else if (ret == inode_state_did_delete &&
4611 			   cur->dir != last_dir_ino_rm) {
4612 			ret = can_rmdir(sctx, cur->dir, cur->dir_gen);
4613 			if (ret < 0)
4614 				goto out;
4615 			if (ret) {
4616 				ret = get_cur_path(sctx, cur->dir,
4617 						   cur->dir_gen, valid_path);
4618 				if (ret < 0)
4619 					goto out;
4620 				ret = send_rmdir(sctx, valid_path);
4621 				if (ret < 0)
4622 					goto out;
4623 				last_dir_ino_rm = cur->dir;
4624 			}
4625 		}
4626 	}
4627 
4628 	ret = 0;
4629 
4630 out:
4631 	__free_recorded_refs(&check_dirs);
4632 	free_recorded_refs(sctx);
4633 	fs_path_free(valid_path);
4634 	return ret;
4635 }
4636 
4637 static int rbtree_ref_comp(const void *k, const struct rb_node *node)
4638 {
4639 	const struct recorded_ref *data = k;
4640 	const struct recorded_ref *ref = rb_entry(node, struct recorded_ref, node);
4641 	int result;
4642 
4643 	if (data->dir > ref->dir)
4644 		return 1;
4645 	if (data->dir < ref->dir)
4646 		return -1;
4647 	if (data->dir_gen > ref->dir_gen)
4648 		return 1;
4649 	if (data->dir_gen < ref->dir_gen)
4650 		return -1;
4651 	if (data->name_len > ref->name_len)
4652 		return 1;
4653 	if (data->name_len < ref->name_len)
4654 		return -1;
4655 	result = strcmp(data->name, ref->name);
4656 	if (result > 0)
4657 		return 1;
4658 	if (result < 0)
4659 		return -1;
4660 	return 0;
4661 }
4662 
4663 static bool rbtree_ref_less(struct rb_node *node, const struct rb_node *parent)
4664 {
4665 	const struct recorded_ref *entry = rb_entry(node, struct recorded_ref, node);
4666 
4667 	return rbtree_ref_comp(entry, parent) < 0;
4668 }
4669 
4670 static int record_ref_in_tree(struct rb_root *root, struct list_head *refs,
4671 			      struct fs_path *name, u64 dir, u64 dir_gen,
4672 			      struct send_ctx *sctx)
4673 {
4674 	int ret = 0;
4675 	struct fs_path *path = NULL;
4676 	struct recorded_ref *ref = NULL;
4677 
4678 	path = fs_path_alloc();
4679 	if (!path) {
4680 		ret = -ENOMEM;
4681 		goto out;
4682 	}
4683 
4684 	ref = recorded_ref_alloc();
4685 	if (!ref) {
4686 		ret = -ENOMEM;
4687 		goto out;
4688 	}
4689 
4690 	ret = get_cur_path(sctx, dir, dir_gen, path);
4691 	if (ret < 0)
4692 		goto out;
4693 	ret = fs_path_add_path(path, name);
4694 	if (ret < 0)
4695 		goto out;
4696 
4697 	ref->dir = dir;
4698 	ref->dir_gen = dir_gen;
4699 	set_ref_path(ref, path);
4700 	list_add_tail(&ref->list, refs);
4701 	rb_add(&ref->node, root, rbtree_ref_less);
4702 	ref->root = root;
4703 out:
4704 	if (ret) {
4705 		if (path && (!ref || !ref->full_path))
4706 			fs_path_free(path);
4707 		recorded_ref_free(ref);
4708 	}
4709 	return ret;
4710 }
4711 
4712 static int record_new_ref_if_needed(int num, u64 dir, int index,
4713 				    struct fs_path *name, void *ctx)
4714 {
4715 	int ret = 0;
4716 	struct send_ctx *sctx = ctx;
4717 	struct rb_node *node = NULL;
4718 	struct recorded_ref data;
4719 	struct recorded_ref *ref;
4720 	u64 dir_gen;
4721 
4722 	ret = get_inode_gen(sctx->send_root, dir, &dir_gen);
4723 	if (ret < 0)
4724 		goto out;
4725 
4726 	data.dir = dir;
4727 	data.dir_gen = dir_gen;
4728 	set_ref_path(&data, name);
4729 	node = rb_find(&data, &sctx->rbtree_deleted_refs, rbtree_ref_comp);
4730 	if (node) {
4731 		ref = rb_entry(node, struct recorded_ref, node);
4732 		recorded_ref_free(ref);
4733 	} else {
4734 		ret = record_ref_in_tree(&sctx->rbtree_new_refs,
4735 					 &sctx->new_refs, name, dir, dir_gen,
4736 					 sctx);
4737 	}
4738 out:
4739 	return ret;
4740 }
4741 
4742 static int record_deleted_ref_if_needed(int num, u64 dir, int index,
4743 					struct fs_path *name, void *ctx)
4744 {
4745 	int ret = 0;
4746 	struct send_ctx *sctx = ctx;
4747 	struct rb_node *node = NULL;
4748 	struct recorded_ref data;
4749 	struct recorded_ref *ref;
4750 	u64 dir_gen;
4751 
4752 	ret = get_inode_gen(sctx->parent_root, dir, &dir_gen);
4753 	if (ret < 0)
4754 		goto out;
4755 
4756 	data.dir = dir;
4757 	data.dir_gen = dir_gen;
4758 	set_ref_path(&data, name);
4759 	node = rb_find(&data, &sctx->rbtree_new_refs, rbtree_ref_comp);
4760 	if (node) {
4761 		ref = rb_entry(node, struct recorded_ref, node);
4762 		recorded_ref_free(ref);
4763 	} else {
4764 		ret = record_ref_in_tree(&sctx->rbtree_deleted_refs,
4765 					 &sctx->deleted_refs, name, dir,
4766 					 dir_gen, sctx);
4767 	}
4768 out:
4769 	return ret;
4770 }
4771 
4772 static int record_new_ref(struct send_ctx *sctx)
4773 {
4774 	int ret;
4775 
4776 	ret = iterate_inode_ref(sctx->send_root, sctx->left_path,
4777 				sctx->cmp_key, 0, record_new_ref_if_needed, sctx);
4778 	if (ret < 0)
4779 		goto out;
4780 	ret = 0;
4781 
4782 out:
4783 	return ret;
4784 }
4785 
4786 static int record_deleted_ref(struct send_ctx *sctx)
4787 {
4788 	int ret;
4789 
4790 	ret = iterate_inode_ref(sctx->parent_root, sctx->right_path,
4791 				sctx->cmp_key, 0, record_deleted_ref_if_needed,
4792 				sctx);
4793 	if (ret < 0)
4794 		goto out;
4795 	ret = 0;
4796 
4797 out:
4798 	return ret;
4799 }
4800 
4801 static int record_changed_ref(struct send_ctx *sctx)
4802 {
4803 	int ret = 0;
4804 
4805 	ret = iterate_inode_ref(sctx->send_root, sctx->left_path,
4806 			sctx->cmp_key, 0, record_new_ref_if_needed, sctx);
4807 	if (ret < 0)
4808 		goto out;
4809 	ret = iterate_inode_ref(sctx->parent_root, sctx->right_path,
4810 			sctx->cmp_key, 0, record_deleted_ref_if_needed, sctx);
4811 	if (ret < 0)
4812 		goto out;
4813 	ret = 0;
4814 
4815 out:
4816 	return ret;
4817 }
4818 
4819 /*
4820  * Record and process all refs at once. Needed when an inode changes the
4821  * generation number, which means that it was deleted and recreated.
4822  */
4823 static int process_all_refs(struct send_ctx *sctx,
4824 			    enum btrfs_compare_tree_result cmd)
4825 {
4826 	int ret = 0;
4827 	int iter_ret = 0;
4828 	struct btrfs_root *root;
4829 	struct btrfs_path *path;
4830 	struct btrfs_key key;
4831 	struct btrfs_key found_key;
4832 	iterate_inode_ref_t cb;
4833 	int pending_move = 0;
4834 
4835 	path = alloc_path_for_send();
4836 	if (!path)
4837 		return -ENOMEM;
4838 
4839 	if (cmd == BTRFS_COMPARE_TREE_NEW) {
4840 		root = sctx->send_root;
4841 		cb = record_new_ref_if_needed;
4842 	} else if (cmd == BTRFS_COMPARE_TREE_DELETED) {
4843 		root = sctx->parent_root;
4844 		cb = record_deleted_ref_if_needed;
4845 	} else {
4846 		btrfs_err(sctx->send_root->fs_info,
4847 				"Wrong command %d in process_all_refs", cmd);
4848 		ret = -EINVAL;
4849 		goto out;
4850 	}
4851 
4852 	key.objectid = sctx->cmp_key->objectid;
4853 	key.type = BTRFS_INODE_REF_KEY;
4854 	key.offset = 0;
4855 	btrfs_for_each_slot(root, &key, &found_key, path, iter_ret) {
4856 		if (found_key.objectid != key.objectid ||
4857 		    (found_key.type != BTRFS_INODE_REF_KEY &&
4858 		     found_key.type != BTRFS_INODE_EXTREF_KEY))
4859 			break;
4860 
4861 		ret = iterate_inode_ref(root, path, &found_key, 0, cb, sctx);
4862 		if (ret < 0)
4863 			goto out;
4864 	}
4865 	/* Catch error found during iteration */
4866 	if (iter_ret < 0) {
4867 		ret = iter_ret;
4868 		goto out;
4869 	}
4870 	btrfs_release_path(path);
4871 
4872 	/*
4873 	 * We don't actually care about pending_move as we are simply
4874 	 * re-creating this inode and will be rename'ing it into place once we
4875 	 * rename the parent directory.
4876 	 */
4877 	ret = process_recorded_refs(sctx, &pending_move);
4878 out:
4879 	btrfs_free_path(path);
4880 	return ret;
4881 }
4882 
4883 static int send_set_xattr(struct send_ctx *sctx,
4884 			  struct fs_path *path,
4885 			  const char *name, int name_len,
4886 			  const char *data, int data_len)
4887 {
4888 	int ret = 0;
4889 
4890 	ret = begin_cmd(sctx, BTRFS_SEND_C_SET_XATTR);
4891 	if (ret < 0)
4892 		goto out;
4893 
4894 	TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
4895 	TLV_PUT_STRING(sctx, BTRFS_SEND_A_XATTR_NAME, name, name_len);
4896 	TLV_PUT(sctx, BTRFS_SEND_A_XATTR_DATA, data, data_len);
4897 
4898 	ret = send_cmd(sctx);
4899 
4900 tlv_put_failure:
4901 out:
4902 	return ret;
4903 }
4904 
4905 static int send_remove_xattr(struct send_ctx *sctx,
4906 			  struct fs_path *path,
4907 			  const char *name, int name_len)
4908 {
4909 	int ret = 0;
4910 
4911 	ret = begin_cmd(sctx, BTRFS_SEND_C_REMOVE_XATTR);
4912 	if (ret < 0)
4913 		goto out;
4914 
4915 	TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
4916 	TLV_PUT_STRING(sctx, BTRFS_SEND_A_XATTR_NAME, name, name_len);
4917 
4918 	ret = send_cmd(sctx);
4919 
4920 tlv_put_failure:
4921 out:
4922 	return ret;
4923 }
4924 
4925 static int __process_new_xattr(int num, struct btrfs_key *di_key,
4926 			       const char *name, int name_len, const char *data,
4927 			       int data_len, void *ctx)
4928 {
4929 	int ret;
4930 	struct send_ctx *sctx = ctx;
4931 	struct fs_path *p;
4932 	struct posix_acl_xattr_header dummy_acl;
4933 
4934 	/* Capabilities are emitted by finish_inode_if_needed */
4935 	if (!strncmp(name, XATTR_NAME_CAPS, name_len))
4936 		return 0;
4937 
4938 	p = fs_path_alloc();
4939 	if (!p)
4940 		return -ENOMEM;
4941 
4942 	/*
4943 	 * This hack is needed because empty acls are stored as zero byte
4944 	 * data in xattrs. Problem with that is, that receiving these zero byte
4945 	 * acls will fail later. To fix this, we send a dummy acl list that
4946 	 * only contains the version number and no entries.
4947 	 */
4948 	if (!strncmp(name, XATTR_NAME_POSIX_ACL_ACCESS, name_len) ||
4949 	    !strncmp(name, XATTR_NAME_POSIX_ACL_DEFAULT, name_len)) {
4950 		if (data_len == 0) {
4951 			dummy_acl.a_version =
4952 					cpu_to_le32(POSIX_ACL_XATTR_VERSION);
4953 			data = (char *)&dummy_acl;
4954 			data_len = sizeof(dummy_acl);
4955 		}
4956 	}
4957 
4958 	ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
4959 	if (ret < 0)
4960 		goto out;
4961 
4962 	ret = send_set_xattr(sctx, p, name, name_len, data, data_len);
4963 
4964 out:
4965 	fs_path_free(p);
4966 	return ret;
4967 }
4968 
4969 static int __process_deleted_xattr(int num, struct btrfs_key *di_key,
4970 				   const char *name, int name_len,
4971 				   const char *data, int data_len, void *ctx)
4972 {
4973 	int ret;
4974 	struct send_ctx *sctx = ctx;
4975 	struct fs_path *p;
4976 
4977 	p = fs_path_alloc();
4978 	if (!p)
4979 		return -ENOMEM;
4980 
4981 	ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
4982 	if (ret < 0)
4983 		goto out;
4984 
4985 	ret = send_remove_xattr(sctx, p, name, name_len);
4986 
4987 out:
4988 	fs_path_free(p);
4989 	return ret;
4990 }
4991 
4992 static int process_new_xattr(struct send_ctx *sctx)
4993 {
4994 	int ret = 0;
4995 
4996 	ret = iterate_dir_item(sctx->send_root, sctx->left_path,
4997 			       __process_new_xattr, sctx);
4998 
4999 	return ret;
5000 }
5001 
5002 static int process_deleted_xattr(struct send_ctx *sctx)
5003 {
5004 	return iterate_dir_item(sctx->parent_root, sctx->right_path,
5005 				__process_deleted_xattr, sctx);
5006 }
5007 
5008 struct find_xattr_ctx {
5009 	const char *name;
5010 	int name_len;
5011 	int found_idx;
5012 	char *found_data;
5013 	int found_data_len;
5014 };
5015 
5016 static int __find_xattr(int num, struct btrfs_key *di_key, const char *name,
5017 			int name_len, const char *data, int data_len, void *vctx)
5018 {
5019 	struct find_xattr_ctx *ctx = vctx;
5020 
5021 	if (name_len == ctx->name_len &&
5022 	    strncmp(name, ctx->name, name_len) == 0) {
5023 		ctx->found_idx = num;
5024 		ctx->found_data_len = data_len;
5025 		ctx->found_data = kmemdup(data, data_len, GFP_KERNEL);
5026 		if (!ctx->found_data)
5027 			return -ENOMEM;
5028 		return 1;
5029 	}
5030 	return 0;
5031 }
5032 
5033 static int find_xattr(struct btrfs_root *root,
5034 		      struct btrfs_path *path,
5035 		      struct btrfs_key *key,
5036 		      const char *name, int name_len,
5037 		      char **data, int *data_len)
5038 {
5039 	int ret;
5040 	struct find_xattr_ctx ctx;
5041 
5042 	ctx.name = name;
5043 	ctx.name_len = name_len;
5044 	ctx.found_idx = -1;
5045 	ctx.found_data = NULL;
5046 	ctx.found_data_len = 0;
5047 
5048 	ret = iterate_dir_item(root, path, __find_xattr, &ctx);
5049 	if (ret < 0)
5050 		return ret;
5051 
5052 	if (ctx.found_idx == -1)
5053 		return -ENOENT;
5054 	if (data) {
5055 		*data = ctx.found_data;
5056 		*data_len = ctx.found_data_len;
5057 	} else {
5058 		kfree(ctx.found_data);
5059 	}
5060 	return ctx.found_idx;
5061 }
5062 
5063 
5064 static int __process_changed_new_xattr(int num, struct btrfs_key *di_key,
5065 				       const char *name, int name_len,
5066 				       const char *data, int data_len,
5067 				       void *ctx)
5068 {
5069 	int ret;
5070 	struct send_ctx *sctx = ctx;
5071 	char *found_data = NULL;
5072 	int found_data_len  = 0;
5073 
5074 	ret = find_xattr(sctx->parent_root, sctx->right_path,
5075 			 sctx->cmp_key, name, name_len, &found_data,
5076 			 &found_data_len);
5077 	if (ret == -ENOENT) {
5078 		ret = __process_new_xattr(num, di_key, name, name_len, data,
5079 					  data_len, ctx);
5080 	} else if (ret >= 0) {
5081 		if (data_len != found_data_len ||
5082 		    memcmp(data, found_data, data_len)) {
5083 			ret = __process_new_xattr(num, di_key, name, name_len,
5084 						  data, data_len, ctx);
5085 		} else {
5086 			ret = 0;
5087 		}
5088 	}
5089 
5090 	kfree(found_data);
5091 	return ret;
5092 }
5093 
5094 static int __process_changed_deleted_xattr(int num, struct btrfs_key *di_key,
5095 					   const char *name, int name_len,
5096 					   const char *data, int data_len,
5097 					   void *ctx)
5098 {
5099 	int ret;
5100 	struct send_ctx *sctx = ctx;
5101 
5102 	ret = find_xattr(sctx->send_root, sctx->left_path, sctx->cmp_key,
5103 			 name, name_len, NULL, NULL);
5104 	if (ret == -ENOENT)
5105 		ret = __process_deleted_xattr(num, di_key, name, name_len, data,
5106 					      data_len, ctx);
5107 	else if (ret >= 0)
5108 		ret = 0;
5109 
5110 	return ret;
5111 }
5112 
5113 static int process_changed_xattr(struct send_ctx *sctx)
5114 {
5115 	int ret = 0;
5116 
5117 	ret = iterate_dir_item(sctx->send_root, sctx->left_path,
5118 			__process_changed_new_xattr, sctx);
5119 	if (ret < 0)
5120 		goto out;
5121 	ret = iterate_dir_item(sctx->parent_root, sctx->right_path,
5122 			__process_changed_deleted_xattr, sctx);
5123 
5124 out:
5125 	return ret;
5126 }
5127 
5128 static int process_all_new_xattrs(struct send_ctx *sctx)
5129 {
5130 	int ret = 0;
5131 	int iter_ret = 0;
5132 	struct btrfs_root *root;
5133 	struct btrfs_path *path;
5134 	struct btrfs_key key;
5135 	struct btrfs_key found_key;
5136 
5137 	path = alloc_path_for_send();
5138 	if (!path)
5139 		return -ENOMEM;
5140 
5141 	root = sctx->send_root;
5142 
5143 	key.objectid = sctx->cmp_key->objectid;
5144 	key.type = BTRFS_XATTR_ITEM_KEY;
5145 	key.offset = 0;
5146 	btrfs_for_each_slot(root, &key, &found_key, path, iter_ret) {
5147 		if (found_key.objectid != key.objectid ||
5148 		    found_key.type != key.type) {
5149 			ret = 0;
5150 			break;
5151 		}
5152 
5153 		ret = iterate_dir_item(root, path, __process_new_xattr, sctx);
5154 		if (ret < 0)
5155 			break;
5156 	}
5157 	/* Catch error found during iteration */
5158 	if (iter_ret < 0)
5159 		ret = iter_ret;
5160 
5161 	btrfs_free_path(path);
5162 	return ret;
5163 }
5164 
5165 static int send_verity(struct send_ctx *sctx, struct fs_path *path,
5166 		       struct fsverity_descriptor *desc)
5167 {
5168 	int ret;
5169 
5170 	ret = begin_cmd(sctx, BTRFS_SEND_C_ENABLE_VERITY);
5171 	if (ret < 0)
5172 		goto out;
5173 
5174 	TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
5175 	TLV_PUT_U8(sctx, BTRFS_SEND_A_VERITY_ALGORITHM,
5176 			le8_to_cpu(desc->hash_algorithm));
5177 	TLV_PUT_U32(sctx, BTRFS_SEND_A_VERITY_BLOCK_SIZE,
5178 			1U << le8_to_cpu(desc->log_blocksize));
5179 	TLV_PUT(sctx, BTRFS_SEND_A_VERITY_SALT_DATA, desc->salt,
5180 			le8_to_cpu(desc->salt_size));
5181 	TLV_PUT(sctx, BTRFS_SEND_A_VERITY_SIG_DATA, desc->signature,
5182 			le32_to_cpu(desc->sig_size));
5183 
5184 	ret = send_cmd(sctx);
5185 
5186 tlv_put_failure:
5187 out:
5188 	return ret;
5189 }
5190 
5191 static int process_verity(struct send_ctx *sctx)
5192 {
5193 	int ret = 0;
5194 	struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
5195 	struct inode *inode;
5196 	struct fs_path *p;
5197 
5198 	inode = btrfs_iget(fs_info->sb, sctx->cur_ino, sctx->send_root);
5199 	if (IS_ERR(inode))
5200 		return PTR_ERR(inode);
5201 
5202 	ret = btrfs_get_verity_descriptor(inode, NULL, 0);
5203 	if (ret < 0)
5204 		goto iput;
5205 
5206 	if (ret > FS_VERITY_MAX_DESCRIPTOR_SIZE) {
5207 		ret = -EMSGSIZE;
5208 		goto iput;
5209 	}
5210 	if (!sctx->verity_descriptor) {
5211 		sctx->verity_descriptor = kvmalloc(FS_VERITY_MAX_DESCRIPTOR_SIZE,
5212 						   GFP_KERNEL);
5213 		if (!sctx->verity_descriptor) {
5214 			ret = -ENOMEM;
5215 			goto iput;
5216 		}
5217 	}
5218 
5219 	ret = btrfs_get_verity_descriptor(inode, sctx->verity_descriptor, ret);
5220 	if (ret < 0)
5221 		goto iput;
5222 
5223 	p = fs_path_alloc();
5224 	if (!p) {
5225 		ret = -ENOMEM;
5226 		goto iput;
5227 	}
5228 	ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5229 	if (ret < 0)
5230 		goto free_path;
5231 
5232 	ret = send_verity(sctx, p, sctx->verity_descriptor);
5233 	if (ret < 0)
5234 		goto free_path;
5235 
5236 free_path:
5237 	fs_path_free(p);
5238 iput:
5239 	iput(inode);
5240 	return ret;
5241 }
5242 
5243 static inline u64 max_send_read_size(const struct send_ctx *sctx)
5244 {
5245 	return sctx->send_max_size - SZ_16K;
5246 }
5247 
5248 static int put_data_header(struct send_ctx *sctx, u32 len)
5249 {
5250 	if (WARN_ON_ONCE(sctx->put_data))
5251 		return -EINVAL;
5252 	sctx->put_data = true;
5253 	if (sctx->proto >= 2) {
5254 		/*
5255 		 * Since v2, the data attribute header doesn't include a length,
5256 		 * it is implicitly to the end of the command.
5257 		 */
5258 		if (sctx->send_max_size - sctx->send_size < sizeof(__le16) + len)
5259 			return -EOVERFLOW;
5260 		put_unaligned_le16(BTRFS_SEND_A_DATA, sctx->send_buf + sctx->send_size);
5261 		sctx->send_size += sizeof(__le16);
5262 	} else {
5263 		struct btrfs_tlv_header *hdr;
5264 
5265 		if (sctx->send_max_size - sctx->send_size < sizeof(*hdr) + len)
5266 			return -EOVERFLOW;
5267 		hdr = (struct btrfs_tlv_header *)(sctx->send_buf + sctx->send_size);
5268 		put_unaligned_le16(BTRFS_SEND_A_DATA, &hdr->tlv_type);
5269 		put_unaligned_le16(len, &hdr->tlv_len);
5270 		sctx->send_size += sizeof(*hdr);
5271 	}
5272 	return 0;
5273 }
5274 
5275 static int put_file_data(struct send_ctx *sctx, u64 offset, u32 len)
5276 {
5277 	struct btrfs_root *root = sctx->send_root;
5278 	struct btrfs_fs_info *fs_info = root->fs_info;
5279 	struct page *page;
5280 	pgoff_t index = offset >> PAGE_SHIFT;
5281 	pgoff_t last_index;
5282 	unsigned pg_offset = offset_in_page(offset);
5283 	int ret;
5284 
5285 	ret = put_data_header(sctx, len);
5286 	if (ret)
5287 		return ret;
5288 
5289 	last_index = (offset + len - 1) >> PAGE_SHIFT;
5290 
5291 	while (index <= last_index) {
5292 		unsigned cur_len = min_t(unsigned, len,
5293 					 PAGE_SIZE - pg_offset);
5294 
5295 		page = find_lock_page(sctx->cur_inode->i_mapping, index);
5296 		if (!page) {
5297 			page_cache_sync_readahead(sctx->cur_inode->i_mapping,
5298 						  &sctx->ra, NULL, index,
5299 						  last_index + 1 - index);
5300 
5301 			page = find_or_create_page(sctx->cur_inode->i_mapping,
5302 						   index, GFP_KERNEL);
5303 			if (!page) {
5304 				ret = -ENOMEM;
5305 				break;
5306 			}
5307 		}
5308 
5309 		if (PageReadahead(page))
5310 			page_cache_async_readahead(sctx->cur_inode->i_mapping,
5311 						   &sctx->ra, NULL, page_folio(page),
5312 						   index, last_index + 1 - index);
5313 
5314 		if (!PageUptodate(page)) {
5315 			btrfs_read_folio(NULL, page_folio(page));
5316 			lock_page(page);
5317 			if (!PageUptodate(page)) {
5318 				unlock_page(page);
5319 				btrfs_err(fs_info,
5320 			"send: IO error at offset %llu for inode %llu root %llu",
5321 					page_offset(page), sctx->cur_ino,
5322 					sctx->send_root->root_key.objectid);
5323 				put_page(page);
5324 				ret = -EIO;
5325 				break;
5326 			}
5327 		}
5328 
5329 		memcpy_from_page(sctx->send_buf + sctx->send_size, page,
5330 				 pg_offset, cur_len);
5331 		unlock_page(page);
5332 		put_page(page);
5333 		index++;
5334 		pg_offset = 0;
5335 		len -= cur_len;
5336 		sctx->send_size += cur_len;
5337 	}
5338 
5339 	return ret;
5340 }
5341 
5342 /*
5343  * Read some bytes from the current inode/file and send a write command to
5344  * user space.
5345  */
5346 static int send_write(struct send_ctx *sctx, u64 offset, u32 len)
5347 {
5348 	struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
5349 	int ret = 0;
5350 	struct fs_path *p;
5351 
5352 	p = fs_path_alloc();
5353 	if (!p)
5354 		return -ENOMEM;
5355 
5356 	btrfs_debug(fs_info, "send_write offset=%llu, len=%d", offset, len);
5357 
5358 	ret = begin_cmd(sctx, BTRFS_SEND_C_WRITE);
5359 	if (ret < 0)
5360 		goto out;
5361 
5362 	ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5363 	if (ret < 0)
5364 		goto out;
5365 
5366 	TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5367 	TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5368 	ret = put_file_data(sctx, offset, len);
5369 	if (ret < 0)
5370 		goto out;
5371 
5372 	ret = send_cmd(sctx);
5373 
5374 tlv_put_failure:
5375 out:
5376 	fs_path_free(p);
5377 	return ret;
5378 }
5379 
5380 /*
5381  * Send a clone command to user space.
5382  */
5383 static int send_clone(struct send_ctx *sctx,
5384 		      u64 offset, u32 len,
5385 		      struct clone_root *clone_root)
5386 {
5387 	int ret = 0;
5388 	struct fs_path *p;
5389 	u64 gen;
5390 
5391 	btrfs_debug(sctx->send_root->fs_info,
5392 		    "send_clone offset=%llu, len=%d, clone_root=%llu, clone_inode=%llu, clone_offset=%llu",
5393 		    offset, len, clone_root->root->root_key.objectid,
5394 		    clone_root->ino, clone_root->offset);
5395 
5396 	p = fs_path_alloc();
5397 	if (!p)
5398 		return -ENOMEM;
5399 
5400 	ret = begin_cmd(sctx, BTRFS_SEND_C_CLONE);
5401 	if (ret < 0)
5402 		goto out;
5403 
5404 	ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5405 	if (ret < 0)
5406 		goto out;
5407 
5408 	TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5409 	TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_LEN, len);
5410 	TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5411 
5412 	if (clone_root->root == sctx->send_root) {
5413 		ret = get_inode_gen(sctx->send_root, clone_root->ino, &gen);
5414 		if (ret < 0)
5415 			goto out;
5416 		ret = get_cur_path(sctx, clone_root->ino, gen, p);
5417 	} else {
5418 		ret = get_inode_path(clone_root->root, clone_root->ino, p);
5419 	}
5420 	if (ret < 0)
5421 		goto out;
5422 
5423 	/*
5424 	 * If the parent we're using has a received_uuid set then use that as
5425 	 * our clone source as that is what we will look for when doing a
5426 	 * receive.
5427 	 *
5428 	 * This covers the case that we create a snapshot off of a received
5429 	 * subvolume and then use that as the parent and try to receive on a
5430 	 * different host.
5431 	 */
5432 	if (!btrfs_is_empty_uuid(clone_root->root->root_item.received_uuid))
5433 		TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
5434 			     clone_root->root->root_item.received_uuid);
5435 	else
5436 		TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
5437 			     clone_root->root->root_item.uuid);
5438 	TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_CTRANSID,
5439 		    btrfs_root_ctransid(&clone_root->root->root_item));
5440 	TLV_PUT_PATH(sctx, BTRFS_SEND_A_CLONE_PATH, p);
5441 	TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_OFFSET,
5442 			clone_root->offset);
5443 
5444 	ret = send_cmd(sctx);
5445 
5446 tlv_put_failure:
5447 out:
5448 	fs_path_free(p);
5449 	return ret;
5450 }
5451 
5452 /*
5453  * Send an update extent command to user space.
5454  */
5455 static int send_update_extent(struct send_ctx *sctx,
5456 			      u64 offset, u32 len)
5457 {
5458 	int ret = 0;
5459 	struct fs_path *p;
5460 
5461 	p = fs_path_alloc();
5462 	if (!p)
5463 		return -ENOMEM;
5464 
5465 	ret = begin_cmd(sctx, BTRFS_SEND_C_UPDATE_EXTENT);
5466 	if (ret < 0)
5467 		goto out;
5468 
5469 	ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5470 	if (ret < 0)
5471 		goto out;
5472 
5473 	TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5474 	TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5475 	TLV_PUT_U64(sctx, BTRFS_SEND_A_SIZE, len);
5476 
5477 	ret = send_cmd(sctx);
5478 
5479 tlv_put_failure:
5480 out:
5481 	fs_path_free(p);
5482 	return ret;
5483 }
5484 
5485 static int send_hole(struct send_ctx *sctx, u64 end)
5486 {
5487 	struct fs_path *p = NULL;
5488 	u64 read_size = max_send_read_size(sctx);
5489 	u64 offset = sctx->cur_inode_last_extent;
5490 	int ret = 0;
5491 
5492 	/*
5493 	 * A hole that starts at EOF or beyond it. Since we do not yet support
5494 	 * fallocate (for extent preallocation and hole punching), sending a
5495 	 * write of zeroes starting at EOF or beyond would later require issuing
5496 	 * a truncate operation which would undo the write and achieve nothing.
5497 	 */
5498 	if (offset >= sctx->cur_inode_size)
5499 		return 0;
5500 
5501 	/*
5502 	 * Don't go beyond the inode's i_size due to prealloc extents that start
5503 	 * after the i_size.
5504 	 */
5505 	end = min_t(u64, end, sctx->cur_inode_size);
5506 
5507 	if (sctx->flags & BTRFS_SEND_FLAG_NO_FILE_DATA)
5508 		return send_update_extent(sctx, offset, end - offset);
5509 
5510 	p = fs_path_alloc();
5511 	if (!p)
5512 		return -ENOMEM;
5513 	ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5514 	if (ret < 0)
5515 		goto tlv_put_failure;
5516 	while (offset < end) {
5517 		u64 len = min(end - offset, read_size);
5518 
5519 		ret = begin_cmd(sctx, BTRFS_SEND_C_WRITE);
5520 		if (ret < 0)
5521 			break;
5522 		TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5523 		TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5524 		ret = put_data_header(sctx, len);
5525 		if (ret < 0)
5526 			break;
5527 		memset(sctx->send_buf + sctx->send_size, 0, len);
5528 		sctx->send_size += len;
5529 		ret = send_cmd(sctx);
5530 		if (ret < 0)
5531 			break;
5532 		offset += len;
5533 	}
5534 	sctx->cur_inode_next_write_offset = offset;
5535 tlv_put_failure:
5536 	fs_path_free(p);
5537 	return ret;
5538 }
5539 
5540 static int send_encoded_inline_extent(struct send_ctx *sctx,
5541 				      struct btrfs_path *path, u64 offset,
5542 				      u64 len)
5543 {
5544 	struct btrfs_root *root = sctx->send_root;
5545 	struct btrfs_fs_info *fs_info = root->fs_info;
5546 	struct inode *inode;
5547 	struct fs_path *fspath;
5548 	struct extent_buffer *leaf = path->nodes[0];
5549 	struct btrfs_key key;
5550 	struct btrfs_file_extent_item *ei;
5551 	u64 ram_bytes;
5552 	size_t inline_size;
5553 	int ret;
5554 
5555 	inode = btrfs_iget(fs_info->sb, sctx->cur_ino, root);
5556 	if (IS_ERR(inode))
5557 		return PTR_ERR(inode);
5558 
5559 	fspath = fs_path_alloc();
5560 	if (!fspath) {
5561 		ret = -ENOMEM;
5562 		goto out;
5563 	}
5564 
5565 	ret = begin_cmd(sctx, BTRFS_SEND_C_ENCODED_WRITE);
5566 	if (ret < 0)
5567 		goto out;
5568 
5569 	ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, fspath);
5570 	if (ret < 0)
5571 		goto out;
5572 
5573 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5574 	ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
5575 	ram_bytes = btrfs_file_extent_ram_bytes(leaf, ei);
5576 	inline_size = btrfs_file_extent_inline_item_len(leaf, path->slots[0]);
5577 
5578 	TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, fspath);
5579 	TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5580 	TLV_PUT_U64(sctx, BTRFS_SEND_A_UNENCODED_FILE_LEN,
5581 		    min(key.offset + ram_bytes - offset, len));
5582 	TLV_PUT_U64(sctx, BTRFS_SEND_A_UNENCODED_LEN, ram_bytes);
5583 	TLV_PUT_U64(sctx, BTRFS_SEND_A_UNENCODED_OFFSET, offset - key.offset);
5584 	ret = btrfs_encoded_io_compression_from_extent(fs_info,
5585 				btrfs_file_extent_compression(leaf, ei));
5586 	if (ret < 0)
5587 		goto out;
5588 	TLV_PUT_U32(sctx, BTRFS_SEND_A_COMPRESSION, ret);
5589 
5590 	ret = put_data_header(sctx, inline_size);
5591 	if (ret < 0)
5592 		goto out;
5593 	read_extent_buffer(leaf, sctx->send_buf + sctx->send_size,
5594 			   btrfs_file_extent_inline_start(ei), inline_size);
5595 	sctx->send_size += inline_size;
5596 
5597 	ret = send_cmd(sctx);
5598 
5599 tlv_put_failure:
5600 out:
5601 	fs_path_free(fspath);
5602 	iput(inode);
5603 	return ret;
5604 }
5605 
5606 static int send_encoded_extent(struct send_ctx *sctx, struct btrfs_path *path,
5607 			       u64 offset, u64 len)
5608 {
5609 	struct btrfs_root *root = sctx->send_root;
5610 	struct btrfs_fs_info *fs_info = root->fs_info;
5611 	struct inode *inode;
5612 	struct fs_path *fspath;
5613 	struct extent_buffer *leaf = path->nodes[0];
5614 	struct btrfs_key key;
5615 	struct btrfs_file_extent_item *ei;
5616 	u64 disk_bytenr, disk_num_bytes;
5617 	u32 data_offset;
5618 	struct btrfs_cmd_header *hdr;
5619 	u32 crc;
5620 	int ret;
5621 
5622 	inode = btrfs_iget(fs_info->sb, sctx->cur_ino, root);
5623 	if (IS_ERR(inode))
5624 		return PTR_ERR(inode);
5625 
5626 	fspath = fs_path_alloc();
5627 	if (!fspath) {
5628 		ret = -ENOMEM;
5629 		goto out;
5630 	}
5631 
5632 	ret = begin_cmd(sctx, BTRFS_SEND_C_ENCODED_WRITE);
5633 	if (ret < 0)
5634 		goto out;
5635 
5636 	ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, fspath);
5637 	if (ret < 0)
5638 		goto out;
5639 
5640 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5641 	ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
5642 	disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
5643 	disk_num_bytes = btrfs_file_extent_disk_num_bytes(leaf, ei);
5644 
5645 	TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, fspath);
5646 	TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5647 	TLV_PUT_U64(sctx, BTRFS_SEND_A_UNENCODED_FILE_LEN,
5648 		    min(key.offset + btrfs_file_extent_num_bytes(leaf, ei) - offset,
5649 			len));
5650 	TLV_PUT_U64(sctx, BTRFS_SEND_A_UNENCODED_LEN,
5651 		    btrfs_file_extent_ram_bytes(leaf, ei));
5652 	TLV_PUT_U64(sctx, BTRFS_SEND_A_UNENCODED_OFFSET,
5653 		    offset - key.offset + btrfs_file_extent_offset(leaf, ei));
5654 	ret = btrfs_encoded_io_compression_from_extent(fs_info,
5655 				btrfs_file_extent_compression(leaf, ei));
5656 	if (ret < 0)
5657 		goto out;
5658 	TLV_PUT_U32(sctx, BTRFS_SEND_A_COMPRESSION, ret);
5659 	TLV_PUT_U32(sctx, BTRFS_SEND_A_ENCRYPTION, 0);
5660 
5661 	ret = put_data_header(sctx, disk_num_bytes);
5662 	if (ret < 0)
5663 		goto out;
5664 
5665 	/*
5666 	 * We want to do I/O directly into the send buffer, so get the next page
5667 	 * boundary in the send buffer. This means that there may be a gap
5668 	 * between the beginning of the command and the file data.
5669 	 */
5670 	data_offset = PAGE_ALIGN(sctx->send_size);
5671 	if (data_offset > sctx->send_max_size ||
5672 	    sctx->send_max_size - data_offset < disk_num_bytes) {
5673 		ret = -EOVERFLOW;
5674 		goto out;
5675 	}
5676 
5677 	/*
5678 	 * Note that send_buf is a mapping of send_buf_pages, so this is really
5679 	 * reading into send_buf.
5680 	 */
5681 	ret = btrfs_encoded_read_regular_fill_pages(BTRFS_I(inode), offset,
5682 						    disk_bytenr, disk_num_bytes,
5683 						    sctx->send_buf_pages +
5684 						    (data_offset >> PAGE_SHIFT));
5685 	if (ret)
5686 		goto out;
5687 
5688 	hdr = (struct btrfs_cmd_header *)sctx->send_buf;
5689 	hdr->len = cpu_to_le32(sctx->send_size + disk_num_bytes - sizeof(*hdr));
5690 	hdr->crc = 0;
5691 	crc = btrfs_crc32c(0, sctx->send_buf, sctx->send_size);
5692 	crc = btrfs_crc32c(crc, sctx->send_buf + data_offset, disk_num_bytes);
5693 	hdr->crc = cpu_to_le32(crc);
5694 
5695 	ret = write_buf(sctx->send_filp, sctx->send_buf, sctx->send_size,
5696 			&sctx->send_off);
5697 	if (!ret) {
5698 		ret = write_buf(sctx->send_filp, sctx->send_buf + data_offset,
5699 				disk_num_bytes, &sctx->send_off);
5700 	}
5701 	sctx->send_size = 0;
5702 	sctx->put_data = false;
5703 
5704 tlv_put_failure:
5705 out:
5706 	fs_path_free(fspath);
5707 	iput(inode);
5708 	return ret;
5709 }
5710 
5711 static int send_extent_data(struct send_ctx *sctx, struct btrfs_path *path,
5712 			    const u64 offset, const u64 len)
5713 {
5714 	const u64 end = offset + len;
5715 	struct extent_buffer *leaf = path->nodes[0];
5716 	struct btrfs_file_extent_item *ei;
5717 	u64 read_size = max_send_read_size(sctx);
5718 	u64 sent = 0;
5719 
5720 	if (sctx->flags & BTRFS_SEND_FLAG_NO_FILE_DATA)
5721 		return send_update_extent(sctx, offset, len);
5722 
5723 	ei = btrfs_item_ptr(leaf, path->slots[0],
5724 			    struct btrfs_file_extent_item);
5725 	if ((sctx->flags & BTRFS_SEND_FLAG_COMPRESSED) &&
5726 	    btrfs_file_extent_compression(leaf, ei) != BTRFS_COMPRESS_NONE) {
5727 		bool is_inline = (btrfs_file_extent_type(leaf, ei) ==
5728 				  BTRFS_FILE_EXTENT_INLINE);
5729 
5730 		/*
5731 		 * Send the compressed extent unless the compressed data is
5732 		 * larger than the decompressed data. This can happen if we're
5733 		 * not sending the entire extent, either because it has been
5734 		 * partially overwritten/truncated or because this is a part of
5735 		 * the extent that we couldn't clone in clone_range().
5736 		 */
5737 		if (is_inline &&
5738 		    btrfs_file_extent_inline_item_len(leaf,
5739 						      path->slots[0]) <= len) {
5740 			return send_encoded_inline_extent(sctx, path, offset,
5741 							  len);
5742 		} else if (!is_inline &&
5743 			   btrfs_file_extent_disk_num_bytes(leaf, ei) <= len) {
5744 			return send_encoded_extent(sctx, path, offset, len);
5745 		}
5746 	}
5747 
5748 	if (sctx->cur_inode == NULL) {
5749 		struct btrfs_root *root = sctx->send_root;
5750 
5751 		sctx->cur_inode = btrfs_iget(root->fs_info->sb, sctx->cur_ino, root);
5752 		if (IS_ERR(sctx->cur_inode)) {
5753 			int err = PTR_ERR(sctx->cur_inode);
5754 
5755 			sctx->cur_inode = NULL;
5756 			return err;
5757 		}
5758 		memset(&sctx->ra, 0, sizeof(struct file_ra_state));
5759 		file_ra_state_init(&sctx->ra, sctx->cur_inode->i_mapping);
5760 
5761 		/*
5762 		 * It's very likely there are no pages from this inode in the page
5763 		 * cache, so after reading extents and sending their data, we clean
5764 		 * the page cache to avoid trashing the page cache (adding pressure
5765 		 * to the page cache and forcing eviction of other data more useful
5766 		 * for applications).
5767 		 *
5768 		 * We decide if we should clean the page cache simply by checking
5769 		 * if the inode's mapping nrpages is 0 when we first open it, and
5770 		 * not by using something like filemap_range_has_page() before
5771 		 * reading an extent because when we ask the readahead code to
5772 		 * read a given file range, it may (and almost always does) read
5773 		 * pages from beyond that range (see the documentation for
5774 		 * page_cache_sync_readahead()), so it would not be reliable,
5775 		 * because after reading the first extent future calls to
5776 		 * filemap_range_has_page() would return true because the readahead
5777 		 * on the previous extent resulted in reading pages of the current
5778 		 * extent as well.
5779 		 */
5780 		sctx->clean_page_cache = (sctx->cur_inode->i_mapping->nrpages == 0);
5781 		sctx->page_cache_clear_start = round_down(offset, PAGE_SIZE);
5782 	}
5783 
5784 	while (sent < len) {
5785 		u64 size = min(len - sent, read_size);
5786 		int ret;
5787 
5788 		ret = send_write(sctx, offset + sent, size);
5789 		if (ret < 0)
5790 			return ret;
5791 		sent += size;
5792 	}
5793 
5794 	if (sctx->clean_page_cache && PAGE_ALIGNED(end)) {
5795 		/*
5796 		 * Always operate only on ranges that are a multiple of the page
5797 		 * size. This is not only to prevent zeroing parts of a page in
5798 		 * the case of subpage sector size, but also to guarantee we evict
5799 		 * pages, as passing a range that is smaller than page size does
5800 		 * not evict the respective page (only zeroes part of its content).
5801 		 *
5802 		 * Always start from the end offset of the last range cleared.
5803 		 * This is because the readahead code may (and very often does)
5804 		 * reads pages beyond the range we request for readahead. So if
5805 		 * we have an extent layout like this:
5806 		 *
5807 		 *            [ extent A ] [ extent B ] [ extent C ]
5808 		 *
5809 		 * When we ask page_cache_sync_readahead() to read extent A, it
5810 		 * may also trigger reads for pages of extent B. If we are doing
5811 		 * an incremental send and extent B has not changed between the
5812 		 * parent and send snapshots, some or all of its pages may end
5813 		 * up being read and placed in the page cache. So when truncating
5814 		 * the page cache we always start from the end offset of the
5815 		 * previously processed extent up to the end of the current
5816 		 * extent.
5817 		 */
5818 		truncate_inode_pages_range(&sctx->cur_inode->i_data,
5819 					   sctx->page_cache_clear_start,
5820 					   end - 1);
5821 		sctx->page_cache_clear_start = end;
5822 	}
5823 
5824 	return 0;
5825 }
5826 
5827 /*
5828  * Search for a capability xattr related to sctx->cur_ino. If the capability is
5829  * found, call send_set_xattr function to emit it.
5830  *
5831  * Return 0 if there isn't a capability, or when the capability was emitted
5832  * successfully, or < 0 if an error occurred.
5833  */
5834 static int send_capabilities(struct send_ctx *sctx)
5835 {
5836 	struct fs_path *fspath = NULL;
5837 	struct btrfs_path *path;
5838 	struct btrfs_dir_item *di;
5839 	struct extent_buffer *leaf;
5840 	unsigned long data_ptr;
5841 	char *buf = NULL;
5842 	int buf_len;
5843 	int ret = 0;
5844 
5845 	path = alloc_path_for_send();
5846 	if (!path)
5847 		return -ENOMEM;
5848 
5849 	di = btrfs_lookup_xattr(NULL, sctx->send_root, path, sctx->cur_ino,
5850 				XATTR_NAME_CAPS, strlen(XATTR_NAME_CAPS), 0);
5851 	if (!di) {
5852 		/* There is no xattr for this inode */
5853 		goto out;
5854 	} else if (IS_ERR(di)) {
5855 		ret = PTR_ERR(di);
5856 		goto out;
5857 	}
5858 
5859 	leaf = path->nodes[0];
5860 	buf_len = btrfs_dir_data_len(leaf, di);
5861 
5862 	fspath = fs_path_alloc();
5863 	buf = kmalloc(buf_len, GFP_KERNEL);
5864 	if (!fspath || !buf) {
5865 		ret = -ENOMEM;
5866 		goto out;
5867 	}
5868 
5869 	ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, fspath);
5870 	if (ret < 0)
5871 		goto out;
5872 
5873 	data_ptr = (unsigned long)(di + 1) + btrfs_dir_name_len(leaf, di);
5874 	read_extent_buffer(leaf, buf, data_ptr, buf_len);
5875 
5876 	ret = send_set_xattr(sctx, fspath, XATTR_NAME_CAPS,
5877 			strlen(XATTR_NAME_CAPS), buf, buf_len);
5878 out:
5879 	kfree(buf);
5880 	fs_path_free(fspath);
5881 	btrfs_free_path(path);
5882 	return ret;
5883 }
5884 
5885 static int clone_range(struct send_ctx *sctx, struct btrfs_path *dst_path,
5886 		       struct clone_root *clone_root, const u64 disk_byte,
5887 		       u64 data_offset, u64 offset, u64 len)
5888 {
5889 	struct btrfs_path *path;
5890 	struct btrfs_key key;
5891 	int ret;
5892 	struct btrfs_inode_info info;
5893 	u64 clone_src_i_size = 0;
5894 
5895 	/*
5896 	 * Prevent cloning from a zero offset with a length matching the sector
5897 	 * size because in some scenarios this will make the receiver fail.
5898 	 *
5899 	 * For example, if in the source filesystem the extent at offset 0
5900 	 * has a length of sectorsize and it was written using direct IO, then
5901 	 * it can never be an inline extent (even if compression is enabled).
5902 	 * Then this extent can be cloned in the original filesystem to a non
5903 	 * zero file offset, but it may not be possible to clone in the
5904 	 * destination filesystem because it can be inlined due to compression
5905 	 * on the destination filesystem (as the receiver's write operations are
5906 	 * always done using buffered IO). The same happens when the original
5907 	 * filesystem does not have compression enabled but the destination
5908 	 * filesystem has.
5909 	 */
5910 	if (clone_root->offset == 0 &&
5911 	    len == sctx->send_root->fs_info->sectorsize)
5912 		return send_extent_data(sctx, dst_path, offset, len);
5913 
5914 	path = alloc_path_for_send();
5915 	if (!path)
5916 		return -ENOMEM;
5917 
5918 	/*
5919 	 * There are inodes that have extents that lie behind its i_size. Don't
5920 	 * accept clones from these extents.
5921 	 */
5922 	ret = get_inode_info(clone_root->root, clone_root->ino, &info);
5923 	btrfs_release_path(path);
5924 	if (ret < 0)
5925 		goto out;
5926 	clone_src_i_size = info.size;
5927 
5928 	/*
5929 	 * We can't send a clone operation for the entire range if we find
5930 	 * extent items in the respective range in the source file that
5931 	 * refer to different extents or if we find holes.
5932 	 * So check for that and do a mix of clone and regular write/copy
5933 	 * operations if needed.
5934 	 *
5935 	 * Example:
5936 	 *
5937 	 * mkfs.btrfs -f /dev/sda
5938 	 * mount /dev/sda /mnt
5939 	 * xfs_io -f -c "pwrite -S 0xaa 0K 100K" /mnt/foo
5940 	 * cp --reflink=always /mnt/foo /mnt/bar
5941 	 * xfs_io -c "pwrite -S 0xbb 50K 50K" /mnt/foo
5942 	 * btrfs subvolume snapshot -r /mnt /mnt/snap
5943 	 *
5944 	 * If when we send the snapshot and we are processing file bar (which
5945 	 * has a higher inode number than foo) we blindly send a clone operation
5946 	 * for the [0, 100K[ range from foo to bar, the receiver ends up getting
5947 	 * a file bar that matches the content of file foo - iow, doesn't match
5948 	 * the content from bar in the original filesystem.
5949 	 */
5950 	key.objectid = clone_root->ino;
5951 	key.type = BTRFS_EXTENT_DATA_KEY;
5952 	key.offset = clone_root->offset;
5953 	ret = btrfs_search_slot(NULL, clone_root->root, &key, path, 0, 0);
5954 	if (ret < 0)
5955 		goto out;
5956 	if (ret > 0 && path->slots[0] > 0) {
5957 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1);
5958 		if (key.objectid == clone_root->ino &&
5959 		    key.type == BTRFS_EXTENT_DATA_KEY)
5960 			path->slots[0]--;
5961 	}
5962 
5963 	while (true) {
5964 		struct extent_buffer *leaf = path->nodes[0];
5965 		int slot = path->slots[0];
5966 		struct btrfs_file_extent_item *ei;
5967 		u8 type;
5968 		u64 ext_len;
5969 		u64 clone_len;
5970 		u64 clone_data_offset;
5971 		bool crossed_src_i_size = false;
5972 
5973 		if (slot >= btrfs_header_nritems(leaf)) {
5974 			ret = btrfs_next_leaf(clone_root->root, path);
5975 			if (ret < 0)
5976 				goto out;
5977 			else if (ret > 0)
5978 				break;
5979 			continue;
5980 		}
5981 
5982 		btrfs_item_key_to_cpu(leaf, &key, slot);
5983 
5984 		/*
5985 		 * We might have an implicit trailing hole (NO_HOLES feature
5986 		 * enabled). We deal with it after leaving this loop.
5987 		 */
5988 		if (key.objectid != clone_root->ino ||
5989 		    key.type != BTRFS_EXTENT_DATA_KEY)
5990 			break;
5991 
5992 		ei = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5993 		type = btrfs_file_extent_type(leaf, ei);
5994 		if (type == BTRFS_FILE_EXTENT_INLINE) {
5995 			ext_len = btrfs_file_extent_ram_bytes(leaf, ei);
5996 			ext_len = PAGE_ALIGN(ext_len);
5997 		} else {
5998 			ext_len = btrfs_file_extent_num_bytes(leaf, ei);
5999 		}
6000 
6001 		if (key.offset + ext_len <= clone_root->offset)
6002 			goto next;
6003 
6004 		if (key.offset > clone_root->offset) {
6005 			/* Implicit hole, NO_HOLES feature enabled. */
6006 			u64 hole_len = key.offset - clone_root->offset;
6007 
6008 			if (hole_len > len)
6009 				hole_len = len;
6010 			ret = send_extent_data(sctx, dst_path, offset,
6011 					       hole_len);
6012 			if (ret < 0)
6013 				goto out;
6014 
6015 			len -= hole_len;
6016 			if (len == 0)
6017 				break;
6018 			offset += hole_len;
6019 			clone_root->offset += hole_len;
6020 			data_offset += hole_len;
6021 		}
6022 
6023 		if (key.offset >= clone_root->offset + len)
6024 			break;
6025 
6026 		if (key.offset >= clone_src_i_size)
6027 			break;
6028 
6029 		if (key.offset + ext_len > clone_src_i_size) {
6030 			ext_len = clone_src_i_size - key.offset;
6031 			crossed_src_i_size = true;
6032 		}
6033 
6034 		clone_data_offset = btrfs_file_extent_offset(leaf, ei);
6035 		if (btrfs_file_extent_disk_bytenr(leaf, ei) == disk_byte) {
6036 			clone_root->offset = key.offset;
6037 			if (clone_data_offset < data_offset &&
6038 				clone_data_offset + ext_len > data_offset) {
6039 				u64 extent_offset;
6040 
6041 				extent_offset = data_offset - clone_data_offset;
6042 				ext_len -= extent_offset;
6043 				clone_data_offset += extent_offset;
6044 				clone_root->offset += extent_offset;
6045 			}
6046 		}
6047 
6048 		clone_len = min_t(u64, ext_len, len);
6049 
6050 		if (btrfs_file_extent_disk_bytenr(leaf, ei) == disk_byte &&
6051 		    clone_data_offset == data_offset) {
6052 			const u64 src_end = clone_root->offset + clone_len;
6053 			const u64 sectorsize = SZ_64K;
6054 
6055 			/*
6056 			 * We can't clone the last block, when its size is not
6057 			 * sector size aligned, into the middle of a file. If we
6058 			 * do so, the receiver will get a failure (-EINVAL) when
6059 			 * trying to clone or will silently corrupt the data in
6060 			 * the destination file if it's on a kernel without the
6061 			 * fix introduced by commit ac765f83f1397646
6062 			 * ("Btrfs: fix data corruption due to cloning of eof
6063 			 * block).
6064 			 *
6065 			 * So issue a clone of the aligned down range plus a
6066 			 * regular write for the eof block, if we hit that case.
6067 			 *
6068 			 * Also, we use the maximum possible sector size, 64K,
6069 			 * because we don't know what's the sector size of the
6070 			 * filesystem that receives the stream, so we have to
6071 			 * assume the largest possible sector size.
6072 			 */
6073 			if (src_end == clone_src_i_size &&
6074 			    !IS_ALIGNED(src_end, sectorsize) &&
6075 			    offset + clone_len < sctx->cur_inode_size) {
6076 				u64 slen;
6077 
6078 				slen = ALIGN_DOWN(src_end - clone_root->offset,
6079 						  sectorsize);
6080 				if (slen > 0) {
6081 					ret = send_clone(sctx, offset, slen,
6082 							 clone_root);
6083 					if (ret < 0)
6084 						goto out;
6085 				}
6086 				ret = send_extent_data(sctx, dst_path,
6087 						       offset + slen,
6088 						       clone_len - slen);
6089 			} else {
6090 				ret = send_clone(sctx, offset, clone_len,
6091 						 clone_root);
6092 			}
6093 		} else if (crossed_src_i_size && clone_len < len) {
6094 			/*
6095 			 * If we are at i_size of the clone source inode and we
6096 			 * can not clone from it, terminate the loop. This is
6097 			 * to avoid sending two write operations, one with a
6098 			 * length matching clone_len and the final one after
6099 			 * this loop with a length of len - clone_len.
6100 			 *
6101 			 * When using encoded writes (BTRFS_SEND_FLAG_COMPRESSED
6102 			 * was passed to the send ioctl), this helps avoid
6103 			 * sending an encoded write for an offset that is not
6104 			 * sector size aligned, in case the i_size of the source
6105 			 * inode is not sector size aligned. That will make the
6106 			 * receiver fallback to decompression of the data and
6107 			 * writing it using regular buffered IO, therefore while
6108 			 * not incorrect, it's not optimal due decompression and
6109 			 * possible re-compression at the receiver.
6110 			 */
6111 			break;
6112 		} else {
6113 			ret = send_extent_data(sctx, dst_path, offset,
6114 					       clone_len);
6115 		}
6116 
6117 		if (ret < 0)
6118 			goto out;
6119 
6120 		len -= clone_len;
6121 		if (len == 0)
6122 			break;
6123 		offset += clone_len;
6124 		clone_root->offset += clone_len;
6125 
6126 		/*
6127 		 * If we are cloning from the file we are currently processing,
6128 		 * and using the send root as the clone root, we must stop once
6129 		 * the current clone offset reaches the current eof of the file
6130 		 * at the receiver, otherwise we would issue an invalid clone
6131 		 * operation (source range going beyond eof) and cause the
6132 		 * receiver to fail. So if we reach the current eof, bail out
6133 		 * and fallback to a regular write.
6134 		 */
6135 		if (clone_root->root == sctx->send_root &&
6136 		    clone_root->ino == sctx->cur_ino &&
6137 		    clone_root->offset >= sctx->cur_inode_next_write_offset)
6138 			break;
6139 
6140 		data_offset += clone_len;
6141 next:
6142 		path->slots[0]++;
6143 	}
6144 
6145 	if (len > 0)
6146 		ret = send_extent_data(sctx, dst_path, offset, len);
6147 	else
6148 		ret = 0;
6149 out:
6150 	btrfs_free_path(path);
6151 	return ret;
6152 }
6153 
6154 static int send_write_or_clone(struct send_ctx *sctx,
6155 			       struct btrfs_path *path,
6156 			       struct btrfs_key *key,
6157 			       struct clone_root *clone_root)
6158 {
6159 	int ret = 0;
6160 	u64 offset = key->offset;
6161 	u64 end;
6162 	u64 bs = sctx->send_root->fs_info->sectorsize;
6163 	struct btrfs_file_extent_item *ei;
6164 	u64 disk_byte;
6165 	u64 data_offset;
6166 	u64 num_bytes;
6167 	struct btrfs_inode_info info = { 0 };
6168 
6169 	end = min_t(u64, btrfs_file_extent_end(path), sctx->cur_inode_size);
6170 	if (offset >= end)
6171 		return 0;
6172 
6173 	num_bytes = end - offset;
6174 
6175 	if (!clone_root)
6176 		goto write_data;
6177 
6178 	if (IS_ALIGNED(end, bs))
6179 		goto clone_data;
6180 
6181 	/*
6182 	 * If the extent end is not aligned, we can clone if the extent ends at
6183 	 * the i_size of the inode and the clone range ends at the i_size of the
6184 	 * source inode, otherwise the clone operation fails with -EINVAL.
6185 	 */
6186 	if (end != sctx->cur_inode_size)
6187 		goto write_data;
6188 
6189 	ret = get_inode_info(clone_root->root, clone_root->ino, &info);
6190 	if (ret < 0)
6191 		return ret;
6192 
6193 	if (clone_root->offset + num_bytes == info.size) {
6194 		/*
6195 		 * The final size of our file matches the end offset, but it may
6196 		 * be that its current size is larger, so we have to truncate it
6197 		 * to any value between the start offset of the range and the
6198 		 * final i_size, otherwise the clone operation is invalid
6199 		 * because it's unaligned and it ends before the current EOF.
6200 		 * We do this truncate to the final i_size when we finish
6201 		 * processing the inode, but it's too late by then. And here we
6202 		 * truncate to the start offset of the range because it's always
6203 		 * sector size aligned while if it were the final i_size it
6204 		 * would result in dirtying part of a page, filling part of a
6205 		 * page with zeroes and then having the clone operation at the
6206 		 * receiver trigger IO and wait for it due to the dirty page.
6207 		 */
6208 		if (sctx->parent_root != NULL) {
6209 			ret = send_truncate(sctx, sctx->cur_ino,
6210 					    sctx->cur_inode_gen, offset);
6211 			if (ret < 0)
6212 				return ret;
6213 		}
6214 		goto clone_data;
6215 	}
6216 
6217 write_data:
6218 	ret = send_extent_data(sctx, path, offset, num_bytes);
6219 	sctx->cur_inode_next_write_offset = end;
6220 	return ret;
6221 
6222 clone_data:
6223 	ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
6224 			    struct btrfs_file_extent_item);
6225 	disk_byte = btrfs_file_extent_disk_bytenr(path->nodes[0], ei);
6226 	data_offset = btrfs_file_extent_offset(path->nodes[0], ei);
6227 	ret = clone_range(sctx, path, clone_root, disk_byte, data_offset, offset,
6228 			  num_bytes);
6229 	sctx->cur_inode_next_write_offset = end;
6230 	return ret;
6231 }
6232 
6233 static int is_extent_unchanged(struct send_ctx *sctx,
6234 			       struct btrfs_path *left_path,
6235 			       struct btrfs_key *ekey)
6236 {
6237 	int ret = 0;
6238 	struct btrfs_key key;
6239 	struct btrfs_path *path = NULL;
6240 	struct extent_buffer *eb;
6241 	int slot;
6242 	struct btrfs_key found_key;
6243 	struct btrfs_file_extent_item *ei;
6244 	u64 left_disknr;
6245 	u64 right_disknr;
6246 	u64 left_offset;
6247 	u64 right_offset;
6248 	u64 left_offset_fixed;
6249 	u64 left_len;
6250 	u64 right_len;
6251 	u64 left_gen;
6252 	u64 right_gen;
6253 	u8 left_type;
6254 	u8 right_type;
6255 
6256 	path = alloc_path_for_send();
6257 	if (!path)
6258 		return -ENOMEM;
6259 
6260 	eb = left_path->nodes[0];
6261 	slot = left_path->slots[0];
6262 	ei = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
6263 	left_type = btrfs_file_extent_type(eb, ei);
6264 
6265 	if (left_type != BTRFS_FILE_EXTENT_REG) {
6266 		ret = 0;
6267 		goto out;
6268 	}
6269 	left_disknr = btrfs_file_extent_disk_bytenr(eb, ei);
6270 	left_len = btrfs_file_extent_num_bytes(eb, ei);
6271 	left_offset = btrfs_file_extent_offset(eb, ei);
6272 	left_gen = btrfs_file_extent_generation(eb, ei);
6273 
6274 	/*
6275 	 * Following comments will refer to these graphics. L is the left
6276 	 * extents which we are checking at the moment. 1-8 are the right
6277 	 * extents that we iterate.
6278 	 *
6279 	 *       |-----L-----|
6280 	 * |-1-|-2a-|-3-|-4-|-5-|-6-|
6281 	 *
6282 	 *       |-----L-----|
6283 	 * |--1--|-2b-|...(same as above)
6284 	 *
6285 	 * Alternative situation. Happens on files where extents got split.
6286 	 *       |-----L-----|
6287 	 * |-----------7-----------|-6-|
6288 	 *
6289 	 * Alternative situation. Happens on files which got larger.
6290 	 *       |-----L-----|
6291 	 * |-8-|
6292 	 * Nothing follows after 8.
6293 	 */
6294 
6295 	key.objectid = ekey->objectid;
6296 	key.type = BTRFS_EXTENT_DATA_KEY;
6297 	key.offset = ekey->offset;
6298 	ret = btrfs_search_slot_for_read(sctx->parent_root, &key, path, 0, 0);
6299 	if (ret < 0)
6300 		goto out;
6301 	if (ret) {
6302 		ret = 0;
6303 		goto out;
6304 	}
6305 
6306 	/*
6307 	 * Handle special case where the right side has no extents at all.
6308 	 */
6309 	eb = path->nodes[0];
6310 	slot = path->slots[0];
6311 	btrfs_item_key_to_cpu(eb, &found_key, slot);
6312 	if (found_key.objectid != key.objectid ||
6313 	    found_key.type != key.type) {
6314 		/* If we're a hole then just pretend nothing changed */
6315 		ret = (left_disknr) ? 0 : 1;
6316 		goto out;
6317 	}
6318 
6319 	/*
6320 	 * We're now on 2a, 2b or 7.
6321 	 */
6322 	key = found_key;
6323 	while (key.offset < ekey->offset + left_len) {
6324 		ei = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
6325 		right_type = btrfs_file_extent_type(eb, ei);
6326 		if (right_type != BTRFS_FILE_EXTENT_REG &&
6327 		    right_type != BTRFS_FILE_EXTENT_INLINE) {
6328 			ret = 0;
6329 			goto out;
6330 		}
6331 
6332 		if (right_type == BTRFS_FILE_EXTENT_INLINE) {
6333 			right_len = btrfs_file_extent_ram_bytes(eb, ei);
6334 			right_len = PAGE_ALIGN(right_len);
6335 		} else {
6336 			right_len = btrfs_file_extent_num_bytes(eb, ei);
6337 		}
6338 
6339 		/*
6340 		 * Are we at extent 8? If yes, we know the extent is changed.
6341 		 * This may only happen on the first iteration.
6342 		 */
6343 		if (found_key.offset + right_len <= ekey->offset) {
6344 			/* If we're a hole just pretend nothing changed */
6345 			ret = (left_disknr) ? 0 : 1;
6346 			goto out;
6347 		}
6348 
6349 		/*
6350 		 * We just wanted to see if when we have an inline extent, what
6351 		 * follows it is a regular extent (wanted to check the above
6352 		 * condition for inline extents too). This should normally not
6353 		 * happen but it's possible for example when we have an inline
6354 		 * compressed extent representing data with a size matching
6355 		 * the page size (currently the same as sector size).
6356 		 */
6357 		if (right_type == BTRFS_FILE_EXTENT_INLINE) {
6358 			ret = 0;
6359 			goto out;
6360 		}
6361 
6362 		right_disknr = btrfs_file_extent_disk_bytenr(eb, ei);
6363 		right_offset = btrfs_file_extent_offset(eb, ei);
6364 		right_gen = btrfs_file_extent_generation(eb, ei);
6365 
6366 		left_offset_fixed = left_offset;
6367 		if (key.offset < ekey->offset) {
6368 			/* Fix the right offset for 2a and 7. */
6369 			right_offset += ekey->offset - key.offset;
6370 		} else {
6371 			/* Fix the left offset for all behind 2a and 2b */
6372 			left_offset_fixed += key.offset - ekey->offset;
6373 		}
6374 
6375 		/*
6376 		 * Check if we have the same extent.
6377 		 */
6378 		if (left_disknr != right_disknr ||
6379 		    left_offset_fixed != right_offset ||
6380 		    left_gen != right_gen) {
6381 			ret = 0;
6382 			goto out;
6383 		}
6384 
6385 		/*
6386 		 * Go to the next extent.
6387 		 */
6388 		ret = btrfs_next_item(sctx->parent_root, path);
6389 		if (ret < 0)
6390 			goto out;
6391 		if (!ret) {
6392 			eb = path->nodes[0];
6393 			slot = path->slots[0];
6394 			btrfs_item_key_to_cpu(eb, &found_key, slot);
6395 		}
6396 		if (ret || found_key.objectid != key.objectid ||
6397 		    found_key.type != key.type) {
6398 			key.offset += right_len;
6399 			break;
6400 		}
6401 		if (found_key.offset != key.offset + right_len) {
6402 			ret = 0;
6403 			goto out;
6404 		}
6405 		key = found_key;
6406 	}
6407 
6408 	/*
6409 	 * We're now behind the left extent (treat as unchanged) or at the end
6410 	 * of the right side (treat as changed).
6411 	 */
6412 	if (key.offset >= ekey->offset + left_len)
6413 		ret = 1;
6414 	else
6415 		ret = 0;
6416 
6417 
6418 out:
6419 	btrfs_free_path(path);
6420 	return ret;
6421 }
6422 
6423 static int get_last_extent(struct send_ctx *sctx, u64 offset)
6424 {
6425 	struct btrfs_path *path;
6426 	struct btrfs_root *root = sctx->send_root;
6427 	struct btrfs_key key;
6428 	int ret;
6429 
6430 	path = alloc_path_for_send();
6431 	if (!path)
6432 		return -ENOMEM;
6433 
6434 	sctx->cur_inode_last_extent = 0;
6435 
6436 	key.objectid = sctx->cur_ino;
6437 	key.type = BTRFS_EXTENT_DATA_KEY;
6438 	key.offset = offset;
6439 	ret = btrfs_search_slot_for_read(root, &key, path, 0, 1);
6440 	if (ret < 0)
6441 		goto out;
6442 	ret = 0;
6443 	btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
6444 	if (key.objectid != sctx->cur_ino || key.type != BTRFS_EXTENT_DATA_KEY)
6445 		goto out;
6446 
6447 	sctx->cur_inode_last_extent = btrfs_file_extent_end(path);
6448 out:
6449 	btrfs_free_path(path);
6450 	return ret;
6451 }
6452 
6453 static int range_is_hole_in_parent(struct send_ctx *sctx,
6454 				   const u64 start,
6455 				   const u64 end)
6456 {
6457 	struct btrfs_path *path;
6458 	struct btrfs_key key;
6459 	struct btrfs_root *root = sctx->parent_root;
6460 	u64 search_start = start;
6461 	int ret;
6462 
6463 	path = alloc_path_for_send();
6464 	if (!path)
6465 		return -ENOMEM;
6466 
6467 	key.objectid = sctx->cur_ino;
6468 	key.type = BTRFS_EXTENT_DATA_KEY;
6469 	key.offset = search_start;
6470 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6471 	if (ret < 0)
6472 		goto out;
6473 	if (ret > 0 && path->slots[0] > 0)
6474 		path->slots[0]--;
6475 
6476 	while (search_start < end) {
6477 		struct extent_buffer *leaf = path->nodes[0];
6478 		int slot = path->slots[0];
6479 		struct btrfs_file_extent_item *fi;
6480 		u64 extent_end;
6481 
6482 		if (slot >= btrfs_header_nritems(leaf)) {
6483 			ret = btrfs_next_leaf(root, path);
6484 			if (ret < 0)
6485 				goto out;
6486 			else if (ret > 0)
6487 				break;
6488 			continue;
6489 		}
6490 
6491 		btrfs_item_key_to_cpu(leaf, &key, slot);
6492 		if (key.objectid < sctx->cur_ino ||
6493 		    key.type < BTRFS_EXTENT_DATA_KEY)
6494 			goto next;
6495 		if (key.objectid > sctx->cur_ino ||
6496 		    key.type > BTRFS_EXTENT_DATA_KEY ||
6497 		    key.offset >= end)
6498 			break;
6499 
6500 		fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6501 		extent_end = btrfs_file_extent_end(path);
6502 		if (extent_end <= start)
6503 			goto next;
6504 		if (btrfs_file_extent_disk_bytenr(leaf, fi) == 0) {
6505 			search_start = extent_end;
6506 			goto next;
6507 		}
6508 		ret = 0;
6509 		goto out;
6510 next:
6511 		path->slots[0]++;
6512 	}
6513 	ret = 1;
6514 out:
6515 	btrfs_free_path(path);
6516 	return ret;
6517 }
6518 
6519 static int maybe_send_hole(struct send_ctx *sctx, struct btrfs_path *path,
6520 			   struct btrfs_key *key)
6521 {
6522 	int ret = 0;
6523 
6524 	if (sctx->cur_ino != key->objectid || !need_send_hole(sctx))
6525 		return 0;
6526 
6527 	if (sctx->cur_inode_last_extent == (u64)-1) {
6528 		ret = get_last_extent(sctx, key->offset - 1);
6529 		if (ret)
6530 			return ret;
6531 	}
6532 
6533 	if (path->slots[0] == 0 &&
6534 	    sctx->cur_inode_last_extent < key->offset) {
6535 		/*
6536 		 * We might have skipped entire leafs that contained only
6537 		 * file extent items for our current inode. These leafs have
6538 		 * a generation number smaller (older) than the one in the
6539 		 * current leaf and the leaf our last extent came from, and
6540 		 * are located between these 2 leafs.
6541 		 */
6542 		ret = get_last_extent(sctx, key->offset - 1);
6543 		if (ret)
6544 			return ret;
6545 	}
6546 
6547 	if (sctx->cur_inode_last_extent < key->offset) {
6548 		ret = range_is_hole_in_parent(sctx,
6549 					      sctx->cur_inode_last_extent,
6550 					      key->offset);
6551 		if (ret < 0)
6552 			return ret;
6553 		else if (ret == 0)
6554 			ret = send_hole(sctx, key->offset);
6555 		else
6556 			ret = 0;
6557 	}
6558 	sctx->cur_inode_last_extent = btrfs_file_extent_end(path);
6559 	return ret;
6560 }
6561 
6562 static int process_extent(struct send_ctx *sctx,
6563 			  struct btrfs_path *path,
6564 			  struct btrfs_key *key)
6565 {
6566 	struct clone_root *found_clone = NULL;
6567 	int ret = 0;
6568 
6569 	if (S_ISLNK(sctx->cur_inode_mode))
6570 		return 0;
6571 
6572 	if (sctx->parent_root && !sctx->cur_inode_new) {
6573 		ret = is_extent_unchanged(sctx, path, key);
6574 		if (ret < 0)
6575 			goto out;
6576 		if (ret) {
6577 			ret = 0;
6578 			goto out_hole;
6579 		}
6580 	} else {
6581 		struct btrfs_file_extent_item *ei;
6582 		u8 type;
6583 
6584 		ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
6585 				    struct btrfs_file_extent_item);
6586 		type = btrfs_file_extent_type(path->nodes[0], ei);
6587 		if (type == BTRFS_FILE_EXTENT_PREALLOC ||
6588 		    type == BTRFS_FILE_EXTENT_REG) {
6589 			/*
6590 			 * The send spec does not have a prealloc command yet,
6591 			 * so just leave a hole for prealloc'ed extents until
6592 			 * we have enough commands queued up to justify rev'ing
6593 			 * the send spec.
6594 			 */
6595 			if (type == BTRFS_FILE_EXTENT_PREALLOC) {
6596 				ret = 0;
6597 				goto out;
6598 			}
6599 
6600 			/* Have a hole, just skip it. */
6601 			if (btrfs_file_extent_disk_bytenr(path->nodes[0], ei) == 0) {
6602 				ret = 0;
6603 				goto out;
6604 			}
6605 		}
6606 	}
6607 
6608 	ret = find_extent_clone(sctx, path, key->objectid, key->offset,
6609 			sctx->cur_inode_size, &found_clone);
6610 	if (ret != -ENOENT && ret < 0)
6611 		goto out;
6612 
6613 	ret = send_write_or_clone(sctx, path, key, found_clone);
6614 	if (ret)
6615 		goto out;
6616 out_hole:
6617 	ret = maybe_send_hole(sctx, path, key);
6618 out:
6619 	return ret;
6620 }
6621 
6622 static int process_all_extents(struct send_ctx *sctx)
6623 {
6624 	int ret = 0;
6625 	int iter_ret = 0;
6626 	struct btrfs_root *root;
6627 	struct btrfs_path *path;
6628 	struct btrfs_key key;
6629 	struct btrfs_key found_key;
6630 
6631 	root = sctx->send_root;
6632 	path = alloc_path_for_send();
6633 	if (!path)
6634 		return -ENOMEM;
6635 
6636 	key.objectid = sctx->cmp_key->objectid;
6637 	key.type = BTRFS_EXTENT_DATA_KEY;
6638 	key.offset = 0;
6639 	btrfs_for_each_slot(root, &key, &found_key, path, iter_ret) {
6640 		if (found_key.objectid != key.objectid ||
6641 		    found_key.type != key.type) {
6642 			ret = 0;
6643 			break;
6644 		}
6645 
6646 		ret = process_extent(sctx, path, &found_key);
6647 		if (ret < 0)
6648 			break;
6649 	}
6650 	/* Catch error found during iteration */
6651 	if (iter_ret < 0)
6652 		ret = iter_ret;
6653 
6654 	btrfs_free_path(path);
6655 	return ret;
6656 }
6657 
6658 static int process_recorded_refs_if_needed(struct send_ctx *sctx, int at_end,
6659 					   int *pending_move,
6660 					   int *refs_processed)
6661 {
6662 	int ret = 0;
6663 
6664 	if (sctx->cur_ino == 0)
6665 		goto out;
6666 	if (!at_end && sctx->cur_ino == sctx->cmp_key->objectid &&
6667 	    sctx->cmp_key->type <= BTRFS_INODE_EXTREF_KEY)
6668 		goto out;
6669 	if (list_empty(&sctx->new_refs) && list_empty(&sctx->deleted_refs))
6670 		goto out;
6671 
6672 	ret = process_recorded_refs(sctx, pending_move);
6673 	if (ret < 0)
6674 		goto out;
6675 
6676 	*refs_processed = 1;
6677 out:
6678 	return ret;
6679 }
6680 
6681 static int finish_inode_if_needed(struct send_ctx *sctx, int at_end)
6682 {
6683 	int ret = 0;
6684 	struct btrfs_inode_info info;
6685 	u64 left_mode;
6686 	u64 left_uid;
6687 	u64 left_gid;
6688 	u64 left_fileattr;
6689 	u64 right_mode;
6690 	u64 right_uid;
6691 	u64 right_gid;
6692 	u64 right_fileattr;
6693 	int need_chmod = 0;
6694 	int need_chown = 0;
6695 	bool need_fileattr = false;
6696 	int need_truncate = 1;
6697 	int pending_move = 0;
6698 	int refs_processed = 0;
6699 
6700 	if (sctx->ignore_cur_inode)
6701 		return 0;
6702 
6703 	ret = process_recorded_refs_if_needed(sctx, at_end, &pending_move,
6704 					      &refs_processed);
6705 	if (ret < 0)
6706 		goto out;
6707 
6708 	/*
6709 	 * We have processed the refs and thus need to advance send_progress.
6710 	 * Now, calls to get_cur_xxx will take the updated refs of the current
6711 	 * inode into account.
6712 	 *
6713 	 * On the other hand, if our current inode is a directory and couldn't
6714 	 * be moved/renamed because its parent was renamed/moved too and it has
6715 	 * a higher inode number, we can only move/rename our current inode
6716 	 * after we moved/renamed its parent. Therefore in this case operate on
6717 	 * the old path (pre move/rename) of our current inode, and the
6718 	 * move/rename will be performed later.
6719 	 */
6720 	if (refs_processed && !pending_move)
6721 		sctx->send_progress = sctx->cur_ino + 1;
6722 
6723 	if (sctx->cur_ino == 0 || sctx->cur_inode_deleted)
6724 		goto out;
6725 	if (!at_end && sctx->cmp_key->objectid == sctx->cur_ino)
6726 		goto out;
6727 	ret = get_inode_info(sctx->send_root, sctx->cur_ino, &info);
6728 	if (ret < 0)
6729 		goto out;
6730 	left_mode = info.mode;
6731 	left_uid = info.uid;
6732 	left_gid = info.gid;
6733 	left_fileattr = info.fileattr;
6734 
6735 	if (!sctx->parent_root || sctx->cur_inode_new) {
6736 		need_chown = 1;
6737 		if (!S_ISLNK(sctx->cur_inode_mode))
6738 			need_chmod = 1;
6739 		if (sctx->cur_inode_next_write_offset == sctx->cur_inode_size)
6740 			need_truncate = 0;
6741 	} else {
6742 		u64 old_size;
6743 
6744 		ret = get_inode_info(sctx->parent_root, sctx->cur_ino, &info);
6745 		if (ret < 0)
6746 			goto out;
6747 		old_size = info.size;
6748 		right_mode = info.mode;
6749 		right_uid = info.uid;
6750 		right_gid = info.gid;
6751 		right_fileattr = info.fileattr;
6752 
6753 		if (left_uid != right_uid || left_gid != right_gid)
6754 			need_chown = 1;
6755 		if (!S_ISLNK(sctx->cur_inode_mode) && left_mode != right_mode)
6756 			need_chmod = 1;
6757 		if (!S_ISLNK(sctx->cur_inode_mode) && left_fileattr != right_fileattr)
6758 			need_fileattr = true;
6759 		if ((old_size == sctx->cur_inode_size) ||
6760 		    (sctx->cur_inode_size > old_size &&
6761 		     sctx->cur_inode_next_write_offset == sctx->cur_inode_size))
6762 			need_truncate = 0;
6763 	}
6764 
6765 	if (S_ISREG(sctx->cur_inode_mode)) {
6766 		if (need_send_hole(sctx)) {
6767 			if (sctx->cur_inode_last_extent == (u64)-1 ||
6768 			    sctx->cur_inode_last_extent <
6769 			    sctx->cur_inode_size) {
6770 				ret = get_last_extent(sctx, (u64)-1);
6771 				if (ret)
6772 					goto out;
6773 			}
6774 			if (sctx->cur_inode_last_extent < sctx->cur_inode_size) {
6775 				ret = range_is_hole_in_parent(sctx,
6776 						      sctx->cur_inode_last_extent,
6777 						      sctx->cur_inode_size);
6778 				if (ret < 0) {
6779 					goto out;
6780 				} else if (ret == 0) {
6781 					ret = send_hole(sctx, sctx->cur_inode_size);
6782 					if (ret < 0)
6783 						goto out;
6784 				} else {
6785 					/* Range is already a hole, skip. */
6786 					ret = 0;
6787 				}
6788 			}
6789 		}
6790 		if (need_truncate) {
6791 			ret = send_truncate(sctx, sctx->cur_ino,
6792 					    sctx->cur_inode_gen,
6793 					    sctx->cur_inode_size);
6794 			if (ret < 0)
6795 				goto out;
6796 		}
6797 	}
6798 
6799 	if (need_chown) {
6800 		ret = send_chown(sctx, sctx->cur_ino, sctx->cur_inode_gen,
6801 				left_uid, left_gid);
6802 		if (ret < 0)
6803 			goto out;
6804 	}
6805 	if (need_chmod) {
6806 		ret = send_chmod(sctx, sctx->cur_ino, sctx->cur_inode_gen,
6807 				left_mode);
6808 		if (ret < 0)
6809 			goto out;
6810 	}
6811 	if (need_fileattr) {
6812 		ret = send_fileattr(sctx, sctx->cur_ino, sctx->cur_inode_gen,
6813 				    left_fileattr);
6814 		if (ret < 0)
6815 			goto out;
6816 	}
6817 
6818 	if (proto_cmd_ok(sctx, BTRFS_SEND_C_ENABLE_VERITY)
6819 	    && sctx->cur_inode_needs_verity) {
6820 		ret = process_verity(sctx);
6821 		if (ret < 0)
6822 			goto out;
6823 	}
6824 
6825 	ret = send_capabilities(sctx);
6826 	if (ret < 0)
6827 		goto out;
6828 
6829 	/*
6830 	 * If other directory inodes depended on our current directory
6831 	 * inode's move/rename, now do their move/rename operations.
6832 	 */
6833 	if (!is_waiting_for_move(sctx, sctx->cur_ino)) {
6834 		ret = apply_children_dir_moves(sctx);
6835 		if (ret)
6836 			goto out;
6837 		/*
6838 		 * Need to send that every time, no matter if it actually
6839 		 * changed between the two trees as we have done changes to
6840 		 * the inode before. If our inode is a directory and it's
6841 		 * waiting to be moved/renamed, we will send its utimes when
6842 		 * it's moved/renamed, therefore we don't need to do it here.
6843 		 */
6844 		sctx->send_progress = sctx->cur_ino + 1;
6845 
6846 		/*
6847 		 * If the current inode is a non-empty directory, delay issuing
6848 		 * the utimes command for it, as it's very likely we have inodes
6849 		 * with an higher number inside it. We want to issue the utimes
6850 		 * command only after adding all dentries to it.
6851 		 */
6852 		if (S_ISDIR(sctx->cur_inode_mode) && sctx->cur_inode_size > 0)
6853 			ret = cache_dir_utimes(sctx, sctx->cur_ino, sctx->cur_inode_gen);
6854 		else
6855 			ret = send_utimes(sctx, sctx->cur_ino, sctx->cur_inode_gen);
6856 
6857 		if (ret < 0)
6858 			goto out;
6859 	}
6860 
6861 out:
6862 	if (!ret)
6863 		ret = trim_dir_utimes_cache(sctx);
6864 
6865 	return ret;
6866 }
6867 
6868 static void close_current_inode(struct send_ctx *sctx)
6869 {
6870 	u64 i_size;
6871 
6872 	if (sctx->cur_inode == NULL)
6873 		return;
6874 
6875 	i_size = i_size_read(sctx->cur_inode);
6876 
6877 	/*
6878 	 * If we are doing an incremental send, we may have extents between the
6879 	 * last processed extent and the i_size that have not been processed
6880 	 * because they haven't changed but we may have read some of their pages
6881 	 * through readahead, see the comments at send_extent_data().
6882 	 */
6883 	if (sctx->clean_page_cache && sctx->page_cache_clear_start < i_size)
6884 		truncate_inode_pages_range(&sctx->cur_inode->i_data,
6885 					   sctx->page_cache_clear_start,
6886 					   round_up(i_size, PAGE_SIZE) - 1);
6887 
6888 	iput(sctx->cur_inode);
6889 	sctx->cur_inode = NULL;
6890 }
6891 
6892 static int changed_inode(struct send_ctx *sctx,
6893 			 enum btrfs_compare_tree_result result)
6894 {
6895 	int ret = 0;
6896 	struct btrfs_key *key = sctx->cmp_key;
6897 	struct btrfs_inode_item *left_ii = NULL;
6898 	struct btrfs_inode_item *right_ii = NULL;
6899 	u64 left_gen = 0;
6900 	u64 right_gen = 0;
6901 
6902 	close_current_inode(sctx);
6903 
6904 	sctx->cur_ino = key->objectid;
6905 	sctx->cur_inode_new_gen = false;
6906 	sctx->cur_inode_last_extent = (u64)-1;
6907 	sctx->cur_inode_next_write_offset = 0;
6908 	sctx->ignore_cur_inode = false;
6909 
6910 	/*
6911 	 * Set send_progress to current inode. This will tell all get_cur_xxx
6912 	 * functions that the current inode's refs are not updated yet. Later,
6913 	 * when process_recorded_refs is finished, it is set to cur_ino + 1.
6914 	 */
6915 	sctx->send_progress = sctx->cur_ino;
6916 
6917 	if (result == BTRFS_COMPARE_TREE_NEW ||
6918 	    result == BTRFS_COMPARE_TREE_CHANGED) {
6919 		left_ii = btrfs_item_ptr(sctx->left_path->nodes[0],
6920 				sctx->left_path->slots[0],
6921 				struct btrfs_inode_item);
6922 		left_gen = btrfs_inode_generation(sctx->left_path->nodes[0],
6923 				left_ii);
6924 	} else {
6925 		right_ii = btrfs_item_ptr(sctx->right_path->nodes[0],
6926 				sctx->right_path->slots[0],
6927 				struct btrfs_inode_item);
6928 		right_gen = btrfs_inode_generation(sctx->right_path->nodes[0],
6929 				right_ii);
6930 	}
6931 	if (result == BTRFS_COMPARE_TREE_CHANGED) {
6932 		right_ii = btrfs_item_ptr(sctx->right_path->nodes[0],
6933 				sctx->right_path->slots[0],
6934 				struct btrfs_inode_item);
6935 
6936 		right_gen = btrfs_inode_generation(sctx->right_path->nodes[0],
6937 				right_ii);
6938 
6939 		/*
6940 		 * The cur_ino = root dir case is special here. We can't treat
6941 		 * the inode as deleted+reused because it would generate a
6942 		 * stream that tries to delete/mkdir the root dir.
6943 		 */
6944 		if (left_gen != right_gen &&
6945 		    sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID)
6946 			sctx->cur_inode_new_gen = true;
6947 	}
6948 
6949 	/*
6950 	 * Normally we do not find inodes with a link count of zero (orphans)
6951 	 * because the most common case is to create a snapshot and use it
6952 	 * for a send operation. However other less common use cases involve
6953 	 * using a subvolume and send it after turning it to RO mode just
6954 	 * after deleting all hard links of a file while holding an open
6955 	 * file descriptor against it or turning a RO snapshot into RW mode,
6956 	 * keep an open file descriptor against a file, delete it and then
6957 	 * turn the snapshot back to RO mode before using it for a send
6958 	 * operation. The former is what the receiver operation does.
6959 	 * Therefore, if we want to send these snapshots soon after they're
6960 	 * received, we need to handle orphan inodes as well. Moreover, orphans
6961 	 * can appear not only in the send snapshot but also in the parent
6962 	 * snapshot. Here are several cases:
6963 	 *
6964 	 * Case 1: BTRFS_COMPARE_TREE_NEW
6965 	 *       |  send snapshot  | action
6966 	 * --------------------------------
6967 	 * nlink |        0        | ignore
6968 	 *
6969 	 * Case 2: BTRFS_COMPARE_TREE_DELETED
6970 	 *       | parent snapshot | action
6971 	 * ----------------------------------
6972 	 * nlink |        0        | as usual
6973 	 * Note: No unlinks will be sent because there're no paths for it.
6974 	 *
6975 	 * Case 3: BTRFS_COMPARE_TREE_CHANGED
6976 	 *           |       | parent snapshot | send snapshot | action
6977 	 * -----------------------------------------------------------------------
6978 	 * subcase 1 | nlink |        0        |       0       | ignore
6979 	 * subcase 2 | nlink |       >0        |       0       | new_gen(deletion)
6980 	 * subcase 3 | nlink |        0        |      >0       | new_gen(creation)
6981 	 *
6982 	 */
6983 	if (result == BTRFS_COMPARE_TREE_NEW) {
6984 		if (btrfs_inode_nlink(sctx->left_path->nodes[0], left_ii) == 0) {
6985 			sctx->ignore_cur_inode = true;
6986 			goto out;
6987 		}
6988 		sctx->cur_inode_gen = left_gen;
6989 		sctx->cur_inode_new = true;
6990 		sctx->cur_inode_deleted = false;
6991 		sctx->cur_inode_size = btrfs_inode_size(
6992 				sctx->left_path->nodes[0], left_ii);
6993 		sctx->cur_inode_mode = btrfs_inode_mode(
6994 				sctx->left_path->nodes[0], left_ii);
6995 		sctx->cur_inode_rdev = btrfs_inode_rdev(
6996 				sctx->left_path->nodes[0], left_ii);
6997 		if (sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID)
6998 			ret = send_create_inode_if_needed(sctx);
6999 	} else if (result == BTRFS_COMPARE_TREE_DELETED) {
7000 		sctx->cur_inode_gen = right_gen;
7001 		sctx->cur_inode_new = false;
7002 		sctx->cur_inode_deleted = true;
7003 		sctx->cur_inode_size = btrfs_inode_size(
7004 				sctx->right_path->nodes[0], right_ii);
7005 		sctx->cur_inode_mode = btrfs_inode_mode(
7006 				sctx->right_path->nodes[0], right_ii);
7007 	} else if (result == BTRFS_COMPARE_TREE_CHANGED) {
7008 		u32 new_nlinks, old_nlinks;
7009 
7010 		new_nlinks = btrfs_inode_nlink(sctx->left_path->nodes[0], left_ii);
7011 		old_nlinks = btrfs_inode_nlink(sctx->right_path->nodes[0], right_ii);
7012 		if (new_nlinks == 0 && old_nlinks == 0) {
7013 			sctx->ignore_cur_inode = true;
7014 			goto out;
7015 		} else if (new_nlinks == 0 || old_nlinks == 0) {
7016 			sctx->cur_inode_new_gen = 1;
7017 		}
7018 		/*
7019 		 * We need to do some special handling in case the inode was
7020 		 * reported as changed with a changed generation number. This
7021 		 * means that the original inode was deleted and new inode
7022 		 * reused the same inum. So we have to treat the old inode as
7023 		 * deleted and the new one as new.
7024 		 */
7025 		if (sctx->cur_inode_new_gen) {
7026 			/*
7027 			 * First, process the inode as if it was deleted.
7028 			 */
7029 			if (old_nlinks > 0) {
7030 				sctx->cur_inode_gen = right_gen;
7031 				sctx->cur_inode_new = false;
7032 				sctx->cur_inode_deleted = true;
7033 				sctx->cur_inode_size = btrfs_inode_size(
7034 						sctx->right_path->nodes[0], right_ii);
7035 				sctx->cur_inode_mode = btrfs_inode_mode(
7036 						sctx->right_path->nodes[0], right_ii);
7037 				ret = process_all_refs(sctx,
7038 						BTRFS_COMPARE_TREE_DELETED);
7039 				if (ret < 0)
7040 					goto out;
7041 			}
7042 
7043 			/*
7044 			 * Now process the inode as if it was new.
7045 			 */
7046 			if (new_nlinks > 0) {
7047 				sctx->cur_inode_gen = left_gen;
7048 				sctx->cur_inode_new = true;
7049 				sctx->cur_inode_deleted = false;
7050 				sctx->cur_inode_size = btrfs_inode_size(
7051 						sctx->left_path->nodes[0],
7052 						left_ii);
7053 				sctx->cur_inode_mode = btrfs_inode_mode(
7054 						sctx->left_path->nodes[0],
7055 						left_ii);
7056 				sctx->cur_inode_rdev = btrfs_inode_rdev(
7057 						sctx->left_path->nodes[0],
7058 						left_ii);
7059 				ret = send_create_inode_if_needed(sctx);
7060 				if (ret < 0)
7061 					goto out;
7062 
7063 				ret = process_all_refs(sctx, BTRFS_COMPARE_TREE_NEW);
7064 				if (ret < 0)
7065 					goto out;
7066 				/*
7067 				 * Advance send_progress now as we did not get
7068 				 * into process_recorded_refs_if_needed in the
7069 				 * new_gen case.
7070 				 */
7071 				sctx->send_progress = sctx->cur_ino + 1;
7072 
7073 				/*
7074 				 * Now process all extents and xattrs of the
7075 				 * inode as if they were all new.
7076 				 */
7077 				ret = process_all_extents(sctx);
7078 				if (ret < 0)
7079 					goto out;
7080 				ret = process_all_new_xattrs(sctx);
7081 				if (ret < 0)
7082 					goto out;
7083 			}
7084 		} else {
7085 			sctx->cur_inode_gen = left_gen;
7086 			sctx->cur_inode_new = false;
7087 			sctx->cur_inode_new_gen = false;
7088 			sctx->cur_inode_deleted = false;
7089 			sctx->cur_inode_size = btrfs_inode_size(
7090 					sctx->left_path->nodes[0], left_ii);
7091 			sctx->cur_inode_mode = btrfs_inode_mode(
7092 					sctx->left_path->nodes[0], left_ii);
7093 		}
7094 	}
7095 
7096 out:
7097 	return ret;
7098 }
7099 
7100 /*
7101  * We have to process new refs before deleted refs, but compare_trees gives us
7102  * the new and deleted refs mixed. To fix this, we record the new/deleted refs
7103  * first and later process them in process_recorded_refs.
7104  * For the cur_inode_new_gen case, we skip recording completely because
7105  * changed_inode did already initiate processing of refs. The reason for this is
7106  * that in this case, compare_tree actually compares the refs of 2 different
7107  * inodes. To fix this, process_all_refs is used in changed_inode to handle all
7108  * refs of the right tree as deleted and all refs of the left tree as new.
7109  */
7110 static int changed_ref(struct send_ctx *sctx,
7111 		       enum btrfs_compare_tree_result result)
7112 {
7113 	int ret = 0;
7114 
7115 	if (sctx->cur_ino != sctx->cmp_key->objectid) {
7116 		inconsistent_snapshot_error(sctx, result, "reference");
7117 		return -EIO;
7118 	}
7119 
7120 	if (!sctx->cur_inode_new_gen &&
7121 	    sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID) {
7122 		if (result == BTRFS_COMPARE_TREE_NEW)
7123 			ret = record_new_ref(sctx);
7124 		else if (result == BTRFS_COMPARE_TREE_DELETED)
7125 			ret = record_deleted_ref(sctx);
7126 		else if (result == BTRFS_COMPARE_TREE_CHANGED)
7127 			ret = record_changed_ref(sctx);
7128 	}
7129 
7130 	return ret;
7131 }
7132 
7133 /*
7134  * Process new/deleted/changed xattrs. We skip processing in the
7135  * cur_inode_new_gen case because changed_inode did already initiate processing
7136  * of xattrs. The reason is the same as in changed_ref
7137  */
7138 static int changed_xattr(struct send_ctx *sctx,
7139 			 enum btrfs_compare_tree_result result)
7140 {
7141 	int ret = 0;
7142 
7143 	if (sctx->cur_ino != sctx->cmp_key->objectid) {
7144 		inconsistent_snapshot_error(sctx, result, "xattr");
7145 		return -EIO;
7146 	}
7147 
7148 	if (!sctx->cur_inode_new_gen && !sctx->cur_inode_deleted) {
7149 		if (result == BTRFS_COMPARE_TREE_NEW)
7150 			ret = process_new_xattr(sctx);
7151 		else if (result == BTRFS_COMPARE_TREE_DELETED)
7152 			ret = process_deleted_xattr(sctx);
7153 		else if (result == BTRFS_COMPARE_TREE_CHANGED)
7154 			ret = process_changed_xattr(sctx);
7155 	}
7156 
7157 	return ret;
7158 }
7159 
7160 /*
7161  * Process new/deleted/changed extents. We skip processing in the
7162  * cur_inode_new_gen case because changed_inode did already initiate processing
7163  * of extents. The reason is the same as in changed_ref
7164  */
7165 static int changed_extent(struct send_ctx *sctx,
7166 			  enum btrfs_compare_tree_result result)
7167 {
7168 	int ret = 0;
7169 
7170 	/*
7171 	 * We have found an extent item that changed without the inode item
7172 	 * having changed. This can happen either after relocation (where the
7173 	 * disk_bytenr of an extent item is replaced at
7174 	 * relocation.c:replace_file_extents()) or after deduplication into a
7175 	 * file in both the parent and send snapshots (where an extent item can
7176 	 * get modified or replaced with a new one). Note that deduplication
7177 	 * updates the inode item, but it only changes the iversion (sequence
7178 	 * field in the inode item) of the inode, so if a file is deduplicated
7179 	 * the same amount of times in both the parent and send snapshots, its
7180 	 * iversion becomes the same in both snapshots, whence the inode item is
7181 	 * the same on both snapshots.
7182 	 */
7183 	if (sctx->cur_ino != sctx->cmp_key->objectid)
7184 		return 0;
7185 
7186 	if (!sctx->cur_inode_new_gen && !sctx->cur_inode_deleted) {
7187 		if (result != BTRFS_COMPARE_TREE_DELETED)
7188 			ret = process_extent(sctx, sctx->left_path,
7189 					sctx->cmp_key);
7190 	}
7191 
7192 	return ret;
7193 }
7194 
7195 static int changed_verity(struct send_ctx *sctx, enum btrfs_compare_tree_result result)
7196 {
7197 	int ret = 0;
7198 
7199 	if (!sctx->cur_inode_new_gen && !sctx->cur_inode_deleted) {
7200 		if (result == BTRFS_COMPARE_TREE_NEW)
7201 			sctx->cur_inode_needs_verity = true;
7202 	}
7203 	return ret;
7204 }
7205 
7206 static int dir_changed(struct send_ctx *sctx, u64 dir)
7207 {
7208 	u64 orig_gen, new_gen;
7209 	int ret;
7210 
7211 	ret = get_inode_gen(sctx->send_root, dir, &new_gen);
7212 	if (ret)
7213 		return ret;
7214 
7215 	ret = get_inode_gen(sctx->parent_root, dir, &orig_gen);
7216 	if (ret)
7217 		return ret;
7218 
7219 	return (orig_gen != new_gen) ? 1 : 0;
7220 }
7221 
7222 static int compare_refs(struct send_ctx *sctx, struct btrfs_path *path,
7223 			struct btrfs_key *key)
7224 {
7225 	struct btrfs_inode_extref *extref;
7226 	struct extent_buffer *leaf;
7227 	u64 dirid = 0, last_dirid = 0;
7228 	unsigned long ptr;
7229 	u32 item_size;
7230 	u32 cur_offset = 0;
7231 	int ref_name_len;
7232 	int ret = 0;
7233 
7234 	/* Easy case, just check this one dirid */
7235 	if (key->type == BTRFS_INODE_REF_KEY) {
7236 		dirid = key->offset;
7237 
7238 		ret = dir_changed(sctx, dirid);
7239 		goto out;
7240 	}
7241 
7242 	leaf = path->nodes[0];
7243 	item_size = btrfs_item_size(leaf, path->slots[0]);
7244 	ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
7245 	while (cur_offset < item_size) {
7246 		extref = (struct btrfs_inode_extref *)(ptr +
7247 						       cur_offset);
7248 		dirid = btrfs_inode_extref_parent(leaf, extref);
7249 		ref_name_len = btrfs_inode_extref_name_len(leaf, extref);
7250 		cur_offset += ref_name_len + sizeof(*extref);
7251 		if (dirid == last_dirid)
7252 			continue;
7253 		ret = dir_changed(sctx, dirid);
7254 		if (ret)
7255 			break;
7256 		last_dirid = dirid;
7257 	}
7258 out:
7259 	return ret;
7260 }
7261 
7262 /*
7263  * Updates compare related fields in sctx and simply forwards to the actual
7264  * changed_xxx functions.
7265  */
7266 static int changed_cb(struct btrfs_path *left_path,
7267 		      struct btrfs_path *right_path,
7268 		      struct btrfs_key *key,
7269 		      enum btrfs_compare_tree_result result,
7270 		      struct send_ctx *sctx)
7271 {
7272 	int ret = 0;
7273 
7274 	/*
7275 	 * We can not hold the commit root semaphore here. This is because in
7276 	 * the case of sending and receiving to the same filesystem, using a
7277 	 * pipe, could result in a deadlock:
7278 	 *
7279 	 * 1) The task running send blocks on the pipe because it's full;
7280 	 *
7281 	 * 2) The task running receive, which is the only consumer of the pipe,
7282 	 *    is waiting for a transaction commit (for example due to a space
7283 	 *    reservation when doing a write or triggering a transaction commit
7284 	 *    when creating a subvolume);
7285 	 *
7286 	 * 3) The transaction is waiting to write lock the commit root semaphore,
7287 	 *    but can not acquire it since it's being held at 1).
7288 	 *
7289 	 * Down this call chain we write to the pipe through kernel_write().
7290 	 * The same type of problem can also happen when sending to a file that
7291 	 * is stored in the same filesystem - when reserving space for a write
7292 	 * into the file, we can trigger a transaction commit.
7293 	 *
7294 	 * Our caller has supplied us with clones of leaves from the send and
7295 	 * parent roots, so we're safe here from a concurrent relocation and
7296 	 * further reallocation of metadata extents while we are here. Below we
7297 	 * also assert that the leaves are clones.
7298 	 */
7299 	lockdep_assert_not_held(&sctx->send_root->fs_info->commit_root_sem);
7300 
7301 	/*
7302 	 * We always have a send root, so left_path is never NULL. We will not
7303 	 * have a leaf when we have reached the end of the send root but have
7304 	 * not yet reached the end of the parent root.
7305 	 */
7306 	if (left_path->nodes[0])
7307 		ASSERT(test_bit(EXTENT_BUFFER_UNMAPPED,
7308 				&left_path->nodes[0]->bflags));
7309 	/*
7310 	 * When doing a full send we don't have a parent root, so right_path is
7311 	 * NULL. When doing an incremental send, we may have reached the end of
7312 	 * the parent root already, so we don't have a leaf at right_path.
7313 	 */
7314 	if (right_path && right_path->nodes[0])
7315 		ASSERT(test_bit(EXTENT_BUFFER_UNMAPPED,
7316 				&right_path->nodes[0]->bflags));
7317 
7318 	if (result == BTRFS_COMPARE_TREE_SAME) {
7319 		if (key->type == BTRFS_INODE_REF_KEY ||
7320 		    key->type == BTRFS_INODE_EXTREF_KEY) {
7321 			ret = compare_refs(sctx, left_path, key);
7322 			if (!ret)
7323 				return 0;
7324 			if (ret < 0)
7325 				return ret;
7326 		} else if (key->type == BTRFS_EXTENT_DATA_KEY) {
7327 			return maybe_send_hole(sctx, left_path, key);
7328 		} else {
7329 			return 0;
7330 		}
7331 		result = BTRFS_COMPARE_TREE_CHANGED;
7332 		ret = 0;
7333 	}
7334 
7335 	sctx->left_path = left_path;
7336 	sctx->right_path = right_path;
7337 	sctx->cmp_key = key;
7338 
7339 	ret = finish_inode_if_needed(sctx, 0);
7340 	if (ret < 0)
7341 		goto out;
7342 
7343 	/* Ignore non-FS objects */
7344 	if (key->objectid == BTRFS_FREE_INO_OBJECTID ||
7345 	    key->objectid == BTRFS_FREE_SPACE_OBJECTID)
7346 		goto out;
7347 
7348 	if (key->type == BTRFS_INODE_ITEM_KEY) {
7349 		ret = changed_inode(sctx, result);
7350 	} else if (!sctx->ignore_cur_inode) {
7351 		if (key->type == BTRFS_INODE_REF_KEY ||
7352 		    key->type == BTRFS_INODE_EXTREF_KEY)
7353 			ret = changed_ref(sctx, result);
7354 		else if (key->type == BTRFS_XATTR_ITEM_KEY)
7355 			ret = changed_xattr(sctx, result);
7356 		else if (key->type == BTRFS_EXTENT_DATA_KEY)
7357 			ret = changed_extent(sctx, result);
7358 		else if (key->type == BTRFS_VERITY_DESC_ITEM_KEY &&
7359 			 key->offset == 0)
7360 			ret = changed_verity(sctx, result);
7361 	}
7362 
7363 out:
7364 	return ret;
7365 }
7366 
7367 static int search_key_again(const struct send_ctx *sctx,
7368 			    struct btrfs_root *root,
7369 			    struct btrfs_path *path,
7370 			    const struct btrfs_key *key)
7371 {
7372 	int ret;
7373 
7374 	if (!path->need_commit_sem)
7375 		lockdep_assert_held_read(&root->fs_info->commit_root_sem);
7376 
7377 	/*
7378 	 * Roots used for send operations are readonly and no one can add,
7379 	 * update or remove keys from them, so we should be able to find our
7380 	 * key again. The only exception is deduplication, which can operate on
7381 	 * readonly roots and add, update or remove keys to/from them - but at
7382 	 * the moment we don't allow it to run in parallel with send.
7383 	 */
7384 	ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
7385 	ASSERT(ret <= 0);
7386 	if (ret > 0) {
7387 		btrfs_print_tree(path->nodes[path->lowest_level], false);
7388 		btrfs_err(root->fs_info,
7389 "send: key (%llu %u %llu) not found in %s root %llu, lowest_level %d, slot %d",
7390 			  key->objectid, key->type, key->offset,
7391 			  (root == sctx->parent_root ? "parent" : "send"),
7392 			  root->root_key.objectid, path->lowest_level,
7393 			  path->slots[path->lowest_level]);
7394 		return -EUCLEAN;
7395 	}
7396 
7397 	return ret;
7398 }
7399 
7400 static int full_send_tree(struct send_ctx *sctx)
7401 {
7402 	int ret;
7403 	struct btrfs_root *send_root = sctx->send_root;
7404 	struct btrfs_key key;
7405 	struct btrfs_fs_info *fs_info = send_root->fs_info;
7406 	struct btrfs_path *path;
7407 
7408 	path = alloc_path_for_send();
7409 	if (!path)
7410 		return -ENOMEM;
7411 	path->reada = READA_FORWARD_ALWAYS;
7412 
7413 	key.objectid = BTRFS_FIRST_FREE_OBJECTID;
7414 	key.type = BTRFS_INODE_ITEM_KEY;
7415 	key.offset = 0;
7416 
7417 	down_read(&fs_info->commit_root_sem);
7418 	sctx->last_reloc_trans = fs_info->last_reloc_trans;
7419 	up_read(&fs_info->commit_root_sem);
7420 
7421 	ret = btrfs_search_slot_for_read(send_root, &key, path, 1, 0);
7422 	if (ret < 0)
7423 		goto out;
7424 	if (ret)
7425 		goto out_finish;
7426 
7427 	while (1) {
7428 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
7429 
7430 		ret = changed_cb(path, NULL, &key,
7431 				 BTRFS_COMPARE_TREE_NEW, sctx);
7432 		if (ret < 0)
7433 			goto out;
7434 
7435 		down_read(&fs_info->commit_root_sem);
7436 		if (fs_info->last_reloc_trans > sctx->last_reloc_trans) {
7437 			sctx->last_reloc_trans = fs_info->last_reloc_trans;
7438 			up_read(&fs_info->commit_root_sem);
7439 			/*
7440 			 * A transaction used for relocating a block group was
7441 			 * committed or is about to finish its commit. Release
7442 			 * our path (leaf) and restart the search, so that we
7443 			 * avoid operating on any file extent items that are
7444 			 * stale, with a disk_bytenr that reflects a pre
7445 			 * relocation value. This way we avoid as much as
7446 			 * possible to fallback to regular writes when checking
7447 			 * if we can clone file ranges.
7448 			 */
7449 			btrfs_release_path(path);
7450 			ret = search_key_again(sctx, send_root, path, &key);
7451 			if (ret < 0)
7452 				goto out;
7453 		} else {
7454 			up_read(&fs_info->commit_root_sem);
7455 		}
7456 
7457 		ret = btrfs_next_item(send_root, path);
7458 		if (ret < 0)
7459 			goto out;
7460 		if (ret) {
7461 			ret  = 0;
7462 			break;
7463 		}
7464 	}
7465 
7466 out_finish:
7467 	ret = finish_inode_if_needed(sctx, 1);
7468 
7469 out:
7470 	btrfs_free_path(path);
7471 	return ret;
7472 }
7473 
7474 static int replace_node_with_clone(struct btrfs_path *path, int level)
7475 {
7476 	struct extent_buffer *clone;
7477 
7478 	clone = btrfs_clone_extent_buffer(path->nodes[level]);
7479 	if (!clone)
7480 		return -ENOMEM;
7481 
7482 	free_extent_buffer(path->nodes[level]);
7483 	path->nodes[level] = clone;
7484 
7485 	return 0;
7486 }
7487 
7488 static int tree_move_down(struct btrfs_path *path, int *level, u64 reada_min_gen)
7489 {
7490 	struct extent_buffer *eb;
7491 	struct extent_buffer *parent = path->nodes[*level];
7492 	int slot = path->slots[*level];
7493 	const int nritems = btrfs_header_nritems(parent);
7494 	u64 reada_max;
7495 	u64 reada_done = 0;
7496 
7497 	lockdep_assert_held_read(&parent->fs_info->commit_root_sem);
7498 	ASSERT(*level != 0);
7499 
7500 	eb = btrfs_read_node_slot(parent, slot);
7501 	if (IS_ERR(eb))
7502 		return PTR_ERR(eb);
7503 
7504 	/*
7505 	 * Trigger readahead for the next leaves we will process, so that it is
7506 	 * very likely that when we need them they are already in memory and we
7507 	 * will not block on disk IO. For nodes we only do readahead for one,
7508 	 * since the time window between processing nodes is typically larger.
7509 	 */
7510 	reada_max = (*level == 1 ? SZ_128K : eb->fs_info->nodesize);
7511 
7512 	for (slot++; slot < nritems && reada_done < reada_max; slot++) {
7513 		if (btrfs_node_ptr_generation(parent, slot) > reada_min_gen) {
7514 			btrfs_readahead_node_child(parent, slot);
7515 			reada_done += eb->fs_info->nodesize;
7516 		}
7517 	}
7518 
7519 	path->nodes[*level - 1] = eb;
7520 	path->slots[*level - 1] = 0;
7521 	(*level)--;
7522 
7523 	if (*level == 0)
7524 		return replace_node_with_clone(path, 0);
7525 
7526 	return 0;
7527 }
7528 
7529 static int tree_move_next_or_upnext(struct btrfs_path *path,
7530 				    int *level, int root_level)
7531 {
7532 	int ret = 0;
7533 	int nritems;
7534 	nritems = btrfs_header_nritems(path->nodes[*level]);
7535 
7536 	path->slots[*level]++;
7537 
7538 	while (path->slots[*level] >= nritems) {
7539 		if (*level == root_level) {
7540 			path->slots[*level] = nritems - 1;
7541 			return -1;
7542 		}
7543 
7544 		/* move upnext */
7545 		path->slots[*level] = 0;
7546 		free_extent_buffer(path->nodes[*level]);
7547 		path->nodes[*level] = NULL;
7548 		(*level)++;
7549 		path->slots[*level]++;
7550 
7551 		nritems = btrfs_header_nritems(path->nodes[*level]);
7552 		ret = 1;
7553 	}
7554 	return ret;
7555 }
7556 
7557 /*
7558  * Returns 1 if it had to move up and next. 0 is returned if it moved only next
7559  * or down.
7560  */
7561 static int tree_advance(struct btrfs_path *path,
7562 			int *level, int root_level,
7563 			int allow_down,
7564 			struct btrfs_key *key,
7565 			u64 reada_min_gen)
7566 {
7567 	int ret;
7568 
7569 	if (*level == 0 || !allow_down) {
7570 		ret = tree_move_next_or_upnext(path, level, root_level);
7571 	} else {
7572 		ret = tree_move_down(path, level, reada_min_gen);
7573 	}
7574 
7575 	/*
7576 	 * Even if we have reached the end of a tree, ret is -1, update the key
7577 	 * anyway, so that in case we need to restart due to a block group
7578 	 * relocation, we can assert that the last key of the root node still
7579 	 * exists in the tree.
7580 	 */
7581 	if (*level == 0)
7582 		btrfs_item_key_to_cpu(path->nodes[*level], key,
7583 				      path->slots[*level]);
7584 	else
7585 		btrfs_node_key_to_cpu(path->nodes[*level], key,
7586 				      path->slots[*level]);
7587 
7588 	return ret;
7589 }
7590 
7591 static int tree_compare_item(struct btrfs_path *left_path,
7592 			     struct btrfs_path *right_path,
7593 			     char *tmp_buf)
7594 {
7595 	int cmp;
7596 	int len1, len2;
7597 	unsigned long off1, off2;
7598 
7599 	len1 = btrfs_item_size(left_path->nodes[0], left_path->slots[0]);
7600 	len2 = btrfs_item_size(right_path->nodes[0], right_path->slots[0]);
7601 	if (len1 != len2)
7602 		return 1;
7603 
7604 	off1 = btrfs_item_ptr_offset(left_path->nodes[0], left_path->slots[0]);
7605 	off2 = btrfs_item_ptr_offset(right_path->nodes[0],
7606 				right_path->slots[0]);
7607 
7608 	read_extent_buffer(left_path->nodes[0], tmp_buf, off1, len1);
7609 
7610 	cmp = memcmp_extent_buffer(right_path->nodes[0], tmp_buf, off2, len1);
7611 	if (cmp)
7612 		return 1;
7613 	return 0;
7614 }
7615 
7616 /*
7617  * A transaction used for relocating a block group was committed or is about to
7618  * finish its commit. Release our paths and restart the search, so that we are
7619  * not using stale extent buffers:
7620  *
7621  * 1) For levels > 0, we are only holding references of extent buffers, without
7622  *    any locks on them, which does not prevent them from having been relocated
7623  *    and reallocated after the last time we released the commit root semaphore.
7624  *    The exception are the root nodes, for which we always have a clone, see
7625  *    the comment at btrfs_compare_trees();
7626  *
7627  * 2) For leaves, level 0, we are holding copies (clones) of extent buffers, so
7628  *    we are safe from the concurrent relocation and reallocation. However they
7629  *    can have file extent items with a pre relocation disk_bytenr value, so we
7630  *    restart the start from the current commit roots and clone the new leaves so
7631  *    that we get the post relocation disk_bytenr values. Not doing so, could
7632  *    make us clone the wrong data in case there are new extents using the old
7633  *    disk_bytenr that happen to be shared.
7634  */
7635 static int restart_after_relocation(struct btrfs_path *left_path,
7636 				    struct btrfs_path *right_path,
7637 				    const struct btrfs_key *left_key,
7638 				    const struct btrfs_key *right_key,
7639 				    int left_level,
7640 				    int right_level,
7641 				    const struct send_ctx *sctx)
7642 {
7643 	int root_level;
7644 	int ret;
7645 
7646 	lockdep_assert_held_read(&sctx->send_root->fs_info->commit_root_sem);
7647 
7648 	btrfs_release_path(left_path);
7649 	btrfs_release_path(right_path);
7650 
7651 	/*
7652 	 * Since keys can not be added or removed to/from our roots because they
7653 	 * are readonly and we do not allow deduplication to run in parallel
7654 	 * (which can add, remove or change keys), the layout of the trees should
7655 	 * not change.
7656 	 */
7657 	left_path->lowest_level = left_level;
7658 	ret = search_key_again(sctx, sctx->send_root, left_path, left_key);
7659 	if (ret < 0)
7660 		return ret;
7661 
7662 	right_path->lowest_level = right_level;
7663 	ret = search_key_again(sctx, sctx->parent_root, right_path, right_key);
7664 	if (ret < 0)
7665 		return ret;
7666 
7667 	/*
7668 	 * If the lowest level nodes are leaves, clone them so that they can be
7669 	 * safely used by changed_cb() while not under the protection of the
7670 	 * commit root semaphore, even if relocation and reallocation happens in
7671 	 * parallel.
7672 	 */
7673 	if (left_level == 0) {
7674 		ret = replace_node_with_clone(left_path, 0);
7675 		if (ret < 0)
7676 			return ret;
7677 	}
7678 
7679 	if (right_level == 0) {
7680 		ret = replace_node_with_clone(right_path, 0);
7681 		if (ret < 0)
7682 			return ret;
7683 	}
7684 
7685 	/*
7686 	 * Now clone the root nodes (unless they happen to be the leaves we have
7687 	 * already cloned). This is to protect against concurrent snapshotting of
7688 	 * the send and parent roots (see the comment at btrfs_compare_trees()).
7689 	 */
7690 	root_level = btrfs_header_level(sctx->send_root->commit_root);
7691 	if (root_level > 0) {
7692 		ret = replace_node_with_clone(left_path, root_level);
7693 		if (ret < 0)
7694 			return ret;
7695 	}
7696 
7697 	root_level = btrfs_header_level(sctx->parent_root->commit_root);
7698 	if (root_level > 0) {
7699 		ret = replace_node_with_clone(right_path, root_level);
7700 		if (ret < 0)
7701 			return ret;
7702 	}
7703 
7704 	return 0;
7705 }
7706 
7707 /*
7708  * This function compares two trees and calls the provided callback for
7709  * every changed/new/deleted item it finds.
7710  * If shared tree blocks are encountered, whole subtrees are skipped, making
7711  * the compare pretty fast on snapshotted subvolumes.
7712  *
7713  * This currently works on commit roots only. As commit roots are read only,
7714  * we don't do any locking. The commit roots are protected with transactions.
7715  * Transactions are ended and rejoined when a commit is tried in between.
7716  *
7717  * This function checks for modifications done to the trees while comparing.
7718  * If it detects a change, it aborts immediately.
7719  */
7720 static int btrfs_compare_trees(struct btrfs_root *left_root,
7721 			struct btrfs_root *right_root, struct send_ctx *sctx)
7722 {
7723 	struct btrfs_fs_info *fs_info = left_root->fs_info;
7724 	int ret;
7725 	int cmp;
7726 	struct btrfs_path *left_path = NULL;
7727 	struct btrfs_path *right_path = NULL;
7728 	struct btrfs_key left_key;
7729 	struct btrfs_key right_key;
7730 	char *tmp_buf = NULL;
7731 	int left_root_level;
7732 	int right_root_level;
7733 	int left_level;
7734 	int right_level;
7735 	int left_end_reached = 0;
7736 	int right_end_reached = 0;
7737 	int advance_left = 0;
7738 	int advance_right = 0;
7739 	u64 left_blockptr;
7740 	u64 right_blockptr;
7741 	u64 left_gen;
7742 	u64 right_gen;
7743 	u64 reada_min_gen;
7744 
7745 	left_path = btrfs_alloc_path();
7746 	if (!left_path) {
7747 		ret = -ENOMEM;
7748 		goto out;
7749 	}
7750 	right_path = btrfs_alloc_path();
7751 	if (!right_path) {
7752 		ret = -ENOMEM;
7753 		goto out;
7754 	}
7755 
7756 	tmp_buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
7757 	if (!tmp_buf) {
7758 		ret = -ENOMEM;
7759 		goto out;
7760 	}
7761 
7762 	left_path->search_commit_root = 1;
7763 	left_path->skip_locking = 1;
7764 	right_path->search_commit_root = 1;
7765 	right_path->skip_locking = 1;
7766 
7767 	/*
7768 	 * Strategy: Go to the first items of both trees. Then do
7769 	 *
7770 	 * If both trees are at level 0
7771 	 *   Compare keys of current items
7772 	 *     If left < right treat left item as new, advance left tree
7773 	 *       and repeat
7774 	 *     If left > right treat right item as deleted, advance right tree
7775 	 *       and repeat
7776 	 *     If left == right do deep compare of items, treat as changed if
7777 	 *       needed, advance both trees and repeat
7778 	 * If both trees are at the same level but not at level 0
7779 	 *   Compare keys of current nodes/leafs
7780 	 *     If left < right advance left tree and repeat
7781 	 *     If left > right advance right tree and repeat
7782 	 *     If left == right compare blockptrs of the next nodes/leafs
7783 	 *       If they match advance both trees but stay at the same level
7784 	 *         and repeat
7785 	 *       If they don't match advance both trees while allowing to go
7786 	 *         deeper and repeat
7787 	 * If tree levels are different
7788 	 *   Advance the tree that needs it and repeat
7789 	 *
7790 	 * Advancing a tree means:
7791 	 *   If we are at level 0, try to go to the next slot. If that's not
7792 	 *   possible, go one level up and repeat. Stop when we found a level
7793 	 *   where we could go to the next slot. We may at this point be on a
7794 	 *   node or a leaf.
7795 	 *
7796 	 *   If we are not at level 0 and not on shared tree blocks, go one
7797 	 *   level deeper.
7798 	 *
7799 	 *   If we are not at level 0 and on shared tree blocks, go one slot to
7800 	 *   the right if possible or go up and right.
7801 	 */
7802 
7803 	down_read(&fs_info->commit_root_sem);
7804 	left_level = btrfs_header_level(left_root->commit_root);
7805 	left_root_level = left_level;
7806 	/*
7807 	 * We clone the root node of the send and parent roots to prevent races
7808 	 * with snapshot creation of these roots. Snapshot creation COWs the
7809 	 * root node of a tree, so after the transaction is committed the old
7810 	 * extent can be reallocated while this send operation is still ongoing.
7811 	 * So we clone them, under the commit root semaphore, to be race free.
7812 	 */
7813 	left_path->nodes[left_level] =
7814 			btrfs_clone_extent_buffer(left_root->commit_root);
7815 	if (!left_path->nodes[left_level]) {
7816 		ret = -ENOMEM;
7817 		goto out_unlock;
7818 	}
7819 
7820 	right_level = btrfs_header_level(right_root->commit_root);
7821 	right_root_level = right_level;
7822 	right_path->nodes[right_level] =
7823 			btrfs_clone_extent_buffer(right_root->commit_root);
7824 	if (!right_path->nodes[right_level]) {
7825 		ret = -ENOMEM;
7826 		goto out_unlock;
7827 	}
7828 	/*
7829 	 * Our right root is the parent root, while the left root is the "send"
7830 	 * root. We know that all new nodes/leaves in the left root must have
7831 	 * a generation greater than the right root's generation, so we trigger
7832 	 * readahead for those nodes and leaves of the left root, as we know we
7833 	 * will need to read them at some point.
7834 	 */
7835 	reada_min_gen = btrfs_header_generation(right_root->commit_root);
7836 
7837 	if (left_level == 0)
7838 		btrfs_item_key_to_cpu(left_path->nodes[left_level],
7839 				&left_key, left_path->slots[left_level]);
7840 	else
7841 		btrfs_node_key_to_cpu(left_path->nodes[left_level],
7842 				&left_key, left_path->slots[left_level]);
7843 	if (right_level == 0)
7844 		btrfs_item_key_to_cpu(right_path->nodes[right_level],
7845 				&right_key, right_path->slots[right_level]);
7846 	else
7847 		btrfs_node_key_to_cpu(right_path->nodes[right_level],
7848 				&right_key, right_path->slots[right_level]);
7849 
7850 	sctx->last_reloc_trans = fs_info->last_reloc_trans;
7851 
7852 	while (1) {
7853 		if (need_resched() ||
7854 		    rwsem_is_contended(&fs_info->commit_root_sem)) {
7855 			up_read(&fs_info->commit_root_sem);
7856 			cond_resched();
7857 			down_read(&fs_info->commit_root_sem);
7858 		}
7859 
7860 		if (fs_info->last_reloc_trans > sctx->last_reloc_trans) {
7861 			ret = restart_after_relocation(left_path, right_path,
7862 						       &left_key, &right_key,
7863 						       left_level, right_level,
7864 						       sctx);
7865 			if (ret < 0)
7866 				goto out_unlock;
7867 			sctx->last_reloc_trans = fs_info->last_reloc_trans;
7868 		}
7869 
7870 		if (advance_left && !left_end_reached) {
7871 			ret = tree_advance(left_path, &left_level,
7872 					left_root_level,
7873 					advance_left != ADVANCE_ONLY_NEXT,
7874 					&left_key, reada_min_gen);
7875 			if (ret == -1)
7876 				left_end_reached = ADVANCE;
7877 			else if (ret < 0)
7878 				goto out_unlock;
7879 			advance_left = 0;
7880 		}
7881 		if (advance_right && !right_end_reached) {
7882 			ret = tree_advance(right_path, &right_level,
7883 					right_root_level,
7884 					advance_right != ADVANCE_ONLY_NEXT,
7885 					&right_key, reada_min_gen);
7886 			if (ret == -1)
7887 				right_end_reached = ADVANCE;
7888 			else if (ret < 0)
7889 				goto out_unlock;
7890 			advance_right = 0;
7891 		}
7892 
7893 		if (left_end_reached && right_end_reached) {
7894 			ret = 0;
7895 			goto out_unlock;
7896 		} else if (left_end_reached) {
7897 			if (right_level == 0) {
7898 				up_read(&fs_info->commit_root_sem);
7899 				ret = changed_cb(left_path, right_path,
7900 						&right_key,
7901 						BTRFS_COMPARE_TREE_DELETED,
7902 						sctx);
7903 				if (ret < 0)
7904 					goto out;
7905 				down_read(&fs_info->commit_root_sem);
7906 			}
7907 			advance_right = ADVANCE;
7908 			continue;
7909 		} else if (right_end_reached) {
7910 			if (left_level == 0) {
7911 				up_read(&fs_info->commit_root_sem);
7912 				ret = changed_cb(left_path, right_path,
7913 						&left_key,
7914 						BTRFS_COMPARE_TREE_NEW,
7915 						sctx);
7916 				if (ret < 0)
7917 					goto out;
7918 				down_read(&fs_info->commit_root_sem);
7919 			}
7920 			advance_left = ADVANCE;
7921 			continue;
7922 		}
7923 
7924 		if (left_level == 0 && right_level == 0) {
7925 			up_read(&fs_info->commit_root_sem);
7926 			cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
7927 			if (cmp < 0) {
7928 				ret = changed_cb(left_path, right_path,
7929 						&left_key,
7930 						BTRFS_COMPARE_TREE_NEW,
7931 						sctx);
7932 				advance_left = ADVANCE;
7933 			} else if (cmp > 0) {
7934 				ret = changed_cb(left_path, right_path,
7935 						&right_key,
7936 						BTRFS_COMPARE_TREE_DELETED,
7937 						sctx);
7938 				advance_right = ADVANCE;
7939 			} else {
7940 				enum btrfs_compare_tree_result result;
7941 
7942 				WARN_ON(!extent_buffer_uptodate(left_path->nodes[0]));
7943 				ret = tree_compare_item(left_path, right_path,
7944 							tmp_buf);
7945 				if (ret)
7946 					result = BTRFS_COMPARE_TREE_CHANGED;
7947 				else
7948 					result = BTRFS_COMPARE_TREE_SAME;
7949 				ret = changed_cb(left_path, right_path,
7950 						 &left_key, result, sctx);
7951 				advance_left = ADVANCE;
7952 				advance_right = ADVANCE;
7953 			}
7954 
7955 			if (ret < 0)
7956 				goto out;
7957 			down_read(&fs_info->commit_root_sem);
7958 		} else if (left_level == right_level) {
7959 			cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
7960 			if (cmp < 0) {
7961 				advance_left = ADVANCE;
7962 			} else if (cmp > 0) {
7963 				advance_right = ADVANCE;
7964 			} else {
7965 				left_blockptr = btrfs_node_blockptr(
7966 						left_path->nodes[left_level],
7967 						left_path->slots[left_level]);
7968 				right_blockptr = btrfs_node_blockptr(
7969 						right_path->nodes[right_level],
7970 						right_path->slots[right_level]);
7971 				left_gen = btrfs_node_ptr_generation(
7972 						left_path->nodes[left_level],
7973 						left_path->slots[left_level]);
7974 				right_gen = btrfs_node_ptr_generation(
7975 						right_path->nodes[right_level],
7976 						right_path->slots[right_level]);
7977 				if (left_blockptr == right_blockptr &&
7978 				    left_gen == right_gen) {
7979 					/*
7980 					 * As we're on a shared block, don't
7981 					 * allow to go deeper.
7982 					 */
7983 					advance_left = ADVANCE_ONLY_NEXT;
7984 					advance_right = ADVANCE_ONLY_NEXT;
7985 				} else {
7986 					advance_left = ADVANCE;
7987 					advance_right = ADVANCE;
7988 				}
7989 			}
7990 		} else if (left_level < right_level) {
7991 			advance_right = ADVANCE;
7992 		} else {
7993 			advance_left = ADVANCE;
7994 		}
7995 	}
7996 
7997 out_unlock:
7998 	up_read(&fs_info->commit_root_sem);
7999 out:
8000 	btrfs_free_path(left_path);
8001 	btrfs_free_path(right_path);
8002 	kvfree(tmp_buf);
8003 	return ret;
8004 }
8005 
8006 static int send_subvol(struct send_ctx *sctx)
8007 {
8008 	int ret;
8009 
8010 	if (!(sctx->flags & BTRFS_SEND_FLAG_OMIT_STREAM_HEADER)) {
8011 		ret = send_header(sctx);
8012 		if (ret < 0)
8013 			goto out;
8014 	}
8015 
8016 	ret = send_subvol_begin(sctx);
8017 	if (ret < 0)
8018 		goto out;
8019 
8020 	if (sctx->parent_root) {
8021 		ret = btrfs_compare_trees(sctx->send_root, sctx->parent_root, sctx);
8022 		if (ret < 0)
8023 			goto out;
8024 		ret = finish_inode_if_needed(sctx, 1);
8025 		if (ret < 0)
8026 			goto out;
8027 	} else {
8028 		ret = full_send_tree(sctx);
8029 		if (ret < 0)
8030 			goto out;
8031 	}
8032 
8033 out:
8034 	free_recorded_refs(sctx);
8035 	return ret;
8036 }
8037 
8038 /*
8039  * If orphan cleanup did remove any orphans from a root, it means the tree
8040  * was modified and therefore the commit root is not the same as the current
8041  * root anymore. This is a problem, because send uses the commit root and
8042  * therefore can see inode items that don't exist in the current root anymore,
8043  * and for example make calls to btrfs_iget, which will do tree lookups based
8044  * on the current root and not on the commit root. Those lookups will fail,
8045  * returning a -ESTALE error, and making send fail with that error. So make
8046  * sure a send does not see any orphans we have just removed, and that it will
8047  * see the same inodes regardless of whether a transaction commit happened
8048  * before it started (meaning that the commit root will be the same as the
8049  * current root) or not.
8050  */
8051 static int ensure_commit_roots_uptodate(struct send_ctx *sctx)
8052 {
8053 	int i;
8054 	struct btrfs_trans_handle *trans = NULL;
8055 
8056 again:
8057 	if (sctx->parent_root &&
8058 	    sctx->parent_root->node != sctx->parent_root->commit_root)
8059 		goto commit_trans;
8060 
8061 	for (i = 0; i < sctx->clone_roots_cnt; i++)
8062 		if (sctx->clone_roots[i].root->node !=
8063 		    sctx->clone_roots[i].root->commit_root)
8064 			goto commit_trans;
8065 
8066 	if (trans)
8067 		return btrfs_end_transaction(trans);
8068 
8069 	return 0;
8070 
8071 commit_trans:
8072 	/* Use any root, all fs roots will get their commit roots updated. */
8073 	if (!trans) {
8074 		trans = btrfs_join_transaction(sctx->send_root);
8075 		if (IS_ERR(trans))
8076 			return PTR_ERR(trans);
8077 		goto again;
8078 	}
8079 
8080 	return btrfs_commit_transaction(trans);
8081 }
8082 
8083 /*
8084  * Make sure any existing dellaloc is flushed for any root used by a send
8085  * operation so that we do not miss any data and we do not race with writeback
8086  * finishing and changing a tree while send is using the tree. This could
8087  * happen if a subvolume is in RW mode, has delalloc, is turned to RO mode and
8088  * a send operation then uses the subvolume.
8089  * After flushing delalloc ensure_commit_roots_uptodate() must be called.
8090  */
8091 static int flush_delalloc_roots(struct send_ctx *sctx)
8092 {
8093 	struct btrfs_root *root = sctx->parent_root;
8094 	int ret;
8095 	int i;
8096 
8097 	if (root) {
8098 		ret = btrfs_start_delalloc_snapshot(root, false);
8099 		if (ret)
8100 			return ret;
8101 		btrfs_wait_ordered_extents(root, U64_MAX, 0, U64_MAX);
8102 	}
8103 
8104 	for (i = 0; i < sctx->clone_roots_cnt; i++) {
8105 		root = sctx->clone_roots[i].root;
8106 		ret = btrfs_start_delalloc_snapshot(root, false);
8107 		if (ret)
8108 			return ret;
8109 		btrfs_wait_ordered_extents(root, U64_MAX, 0, U64_MAX);
8110 	}
8111 
8112 	return 0;
8113 }
8114 
8115 static void btrfs_root_dec_send_in_progress(struct btrfs_root* root)
8116 {
8117 	spin_lock(&root->root_item_lock);
8118 	root->send_in_progress--;
8119 	/*
8120 	 * Not much left to do, we don't know why it's unbalanced and
8121 	 * can't blindly reset it to 0.
8122 	 */
8123 	if (root->send_in_progress < 0)
8124 		btrfs_err(root->fs_info,
8125 			  "send_in_progress unbalanced %d root %llu",
8126 			  root->send_in_progress, root->root_key.objectid);
8127 	spin_unlock(&root->root_item_lock);
8128 }
8129 
8130 static void dedupe_in_progress_warn(const struct btrfs_root *root)
8131 {
8132 	btrfs_warn_rl(root->fs_info,
8133 "cannot use root %llu for send while deduplications on it are in progress (%d in progress)",
8134 		      root->root_key.objectid, root->dedupe_in_progress);
8135 }
8136 
8137 long btrfs_ioctl_send(struct inode *inode, struct btrfs_ioctl_send_args *arg)
8138 {
8139 	int ret = 0;
8140 	struct btrfs_root *send_root = BTRFS_I(inode)->root;
8141 	struct btrfs_fs_info *fs_info = send_root->fs_info;
8142 	struct btrfs_root *clone_root;
8143 	struct send_ctx *sctx = NULL;
8144 	u32 i;
8145 	u64 *clone_sources_tmp = NULL;
8146 	int clone_sources_to_rollback = 0;
8147 	size_t alloc_size;
8148 	int sort_clone_roots = 0;
8149 	struct btrfs_lru_cache_entry *entry;
8150 	struct btrfs_lru_cache_entry *tmp;
8151 
8152 	if (!capable(CAP_SYS_ADMIN))
8153 		return -EPERM;
8154 
8155 	/*
8156 	 * The subvolume must remain read-only during send, protect against
8157 	 * making it RW. This also protects against deletion.
8158 	 */
8159 	spin_lock(&send_root->root_item_lock);
8160 	if (btrfs_root_readonly(send_root) && send_root->dedupe_in_progress) {
8161 		dedupe_in_progress_warn(send_root);
8162 		spin_unlock(&send_root->root_item_lock);
8163 		return -EAGAIN;
8164 	}
8165 	send_root->send_in_progress++;
8166 	spin_unlock(&send_root->root_item_lock);
8167 
8168 	/*
8169 	 * Userspace tools do the checks and warn the user if it's
8170 	 * not RO.
8171 	 */
8172 	if (!btrfs_root_readonly(send_root)) {
8173 		ret = -EPERM;
8174 		goto out;
8175 	}
8176 
8177 	/*
8178 	 * Check that we don't overflow at later allocations, we request
8179 	 * clone_sources_count + 1 items, and compare to unsigned long inside
8180 	 * access_ok. Also set an upper limit for allocation size so this can't
8181 	 * easily exhaust memory. Max number of clone sources is about 200K.
8182 	 */
8183 	if (arg->clone_sources_count > SZ_8M / sizeof(struct clone_root)) {
8184 		ret = -EINVAL;
8185 		goto out;
8186 	}
8187 
8188 	if (arg->flags & ~BTRFS_SEND_FLAG_MASK) {
8189 		ret = -EOPNOTSUPP;
8190 		goto out;
8191 	}
8192 
8193 	sctx = kzalloc(sizeof(struct send_ctx), GFP_KERNEL);
8194 	if (!sctx) {
8195 		ret = -ENOMEM;
8196 		goto out;
8197 	}
8198 
8199 	INIT_LIST_HEAD(&sctx->new_refs);
8200 	INIT_LIST_HEAD(&sctx->deleted_refs);
8201 
8202 	btrfs_lru_cache_init(&sctx->name_cache, SEND_MAX_NAME_CACHE_SIZE);
8203 	btrfs_lru_cache_init(&sctx->backref_cache, SEND_MAX_BACKREF_CACHE_SIZE);
8204 	btrfs_lru_cache_init(&sctx->dir_created_cache,
8205 			     SEND_MAX_DIR_CREATED_CACHE_SIZE);
8206 	/*
8207 	 * This cache is periodically trimmed to a fixed size elsewhere, see
8208 	 * cache_dir_utimes() and trim_dir_utimes_cache().
8209 	 */
8210 	btrfs_lru_cache_init(&sctx->dir_utimes_cache, 0);
8211 
8212 	sctx->pending_dir_moves = RB_ROOT;
8213 	sctx->waiting_dir_moves = RB_ROOT;
8214 	sctx->orphan_dirs = RB_ROOT;
8215 	sctx->rbtree_new_refs = RB_ROOT;
8216 	sctx->rbtree_deleted_refs = RB_ROOT;
8217 
8218 	sctx->flags = arg->flags;
8219 
8220 	if (arg->flags & BTRFS_SEND_FLAG_VERSION) {
8221 		if (arg->version > BTRFS_SEND_STREAM_VERSION) {
8222 			ret = -EPROTO;
8223 			goto out;
8224 		}
8225 		/* Zero means "use the highest version" */
8226 		sctx->proto = arg->version ?: BTRFS_SEND_STREAM_VERSION;
8227 	} else {
8228 		sctx->proto = 1;
8229 	}
8230 	if ((arg->flags & BTRFS_SEND_FLAG_COMPRESSED) && sctx->proto < 2) {
8231 		ret = -EINVAL;
8232 		goto out;
8233 	}
8234 
8235 	sctx->send_filp = fget(arg->send_fd);
8236 	if (!sctx->send_filp || !(sctx->send_filp->f_mode & FMODE_WRITE)) {
8237 		ret = -EBADF;
8238 		goto out;
8239 	}
8240 
8241 	sctx->send_root = send_root;
8242 	/*
8243 	 * Unlikely but possible, if the subvolume is marked for deletion but
8244 	 * is slow to remove the directory entry, send can still be started
8245 	 */
8246 	if (btrfs_root_dead(sctx->send_root)) {
8247 		ret = -EPERM;
8248 		goto out;
8249 	}
8250 
8251 	sctx->clone_roots_cnt = arg->clone_sources_count;
8252 
8253 	if (sctx->proto >= 2) {
8254 		u32 send_buf_num_pages;
8255 
8256 		sctx->send_max_size = BTRFS_SEND_BUF_SIZE_V2;
8257 		sctx->send_buf = vmalloc(sctx->send_max_size);
8258 		if (!sctx->send_buf) {
8259 			ret = -ENOMEM;
8260 			goto out;
8261 		}
8262 		send_buf_num_pages = sctx->send_max_size >> PAGE_SHIFT;
8263 		sctx->send_buf_pages = kcalloc(send_buf_num_pages,
8264 					       sizeof(*sctx->send_buf_pages),
8265 					       GFP_KERNEL);
8266 		if (!sctx->send_buf_pages) {
8267 			ret = -ENOMEM;
8268 			goto out;
8269 		}
8270 		for (i = 0; i < send_buf_num_pages; i++) {
8271 			sctx->send_buf_pages[i] =
8272 				vmalloc_to_page(sctx->send_buf + (i << PAGE_SHIFT));
8273 		}
8274 	} else {
8275 		sctx->send_max_size = BTRFS_SEND_BUF_SIZE_V1;
8276 		sctx->send_buf = kvmalloc(sctx->send_max_size, GFP_KERNEL);
8277 	}
8278 	if (!sctx->send_buf) {
8279 		ret = -ENOMEM;
8280 		goto out;
8281 	}
8282 
8283 	sctx->clone_roots = kvcalloc(arg->clone_sources_count + 1,
8284 				     sizeof(*sctx->clone_roots),
8285 				     GFP_KERNEL);
8286 	if (!sctx->clone_roots) {
8287 		ret = -ENOMEM;
8288 		goto out;
8289 	}
8290 
8291 	alloc_size = array_size(sizeof(*arg->clone_sources),
8292 				arg->clone_sources_count);
8293 
8294 	if (arg->clone_sources_count) {
8295 		clone_sources_tmp = kvmalloc(alloc_size, GFP_KERNEL);
8296 		if (!clone_sources_tmp) {
8297 			ret = -ENOMEM;
8298 			goto out;
8299 		}
8300 
8301 		ret = copy_from_user(clone_sources_tmp, arg->clone_sources,
8302 				alloc_size);
8303 		if (ret) {
8304 			ret = -EFAULT;
8305 			goto out;
8306 		}
8307 
8308 		for (i = 0; i < arg->clone_sources_count; i++) {
8309 			clone_root = btrfs_get_fs_root(fs_info,
8310 						clone_sources_tmp[i], true);
8311 			if (IS_ERR(clone_root)) {
8312 				ret = PTR_ERR(clone_root);
8313 				goto out;
8314 			}
8315 			spin_lock(&clone_root->root_item_lock);
8316 			if (!btrfs_root_readonly(clone_root) ||
8317 			    btrfs_root_dead(clone_root)) {
8318 				spin_unlock(&clone_root->root_item_lock);
8319 				btrfs_put_root(clone_root);
8320 				ret = -EPERM;
8321 				goto out;
8322 			}
8323 			if (clone_root->dedupe_in_progress) {
8324 				dedupe_in_progress_warn(clone_root);
8325 				spin_unlock(&clone_root->root_item_lock);
8326 				btrfs_put_root(clone_root);
8327 				ret = -EAGAIN;
8328 				goto out;
8329 			}
8330 			clone_root->send_in_progress++;
8331 			spin_unlock(&clone_root->root_item_lock);
8332 
8333 			sctx->clone_roots[i].root = clone_root;
8334 			clone_sources_to_rollback = i + 1;
8335 		}
8336 		kvfree(clone_sources_tmp);
8337 		clone_sources_tmp = NULL;
8338 	}
8339 
8340 	if (arg->parent_root) {
8341 		sctx->parent_root = btrfs_get_fs_root(fs_info, arg->parent_root,
8342 						      true);
8343 		if (IS_ERR(sctx->parent_root)) {
8344 			ret = PTR_ERR(sctx->parent_root);
8345 			goto out;
8346 		}
8347 
8348 		spin_lock(&sctx->parent_root->root_item_lock);
8349 		sctx->parent_root->send_in_progress++;
8350 		if (!btrfs_root_readonly(sctx->parent_root) ||
8351 				btrfs_root_dead(sctx->parent_root)) {
8352 			spin_unlock(&sctx->parent_root->root_item_lock);
8353 			ret = -EPERM;
8354 			goto out;
8355 		}
8356 		if (sctx->parent_root->dedupe_in_progress) {
8357 			dedupe_in_progress_warn(sctx->parent_root);
8358 			spin_unlock(&sctx->parent_root->root_item_lock);
8359 			ret = -EAGAIN;
8360 			goto out;
8361 		}
8362 		spin_unlock(&sctx->parent_root->root_item_lock);
8363 	}
8364 
8365 	/*
8366 	 * Clones from send_root are allowed, but only if the clone source
8367 	 * is behind the current send position. This is checked while searching
8368 	 * for possible clone sources.
8369 	 */
8370 	sctx->clone_roots[sctx->clone_roots_cnt++].root =
8371 		btrfs_grab_root(sctx->send_root);
8372 
8373 	/* We do a bsearch later */
8374 	sort(sctx->clone_roots, sctx->clone_roots_cnt,
8375 			sizeof(*sctx->clone_roots), __clone_root_cmp_sort,
8376 			NULL);
8377 	sort_clone_roots = 1;
8378 
8379 	ret = flush_delalloc_roots(sctx);
8380 	if (ret)
8381 		goto out;
8382 
8383 	ret = ensure_commit_roots_uptodate(sctx);
8384 	if (ret)
8385 		goto out;
8386 
8387 	ret = send_subvol(sctx);
8388 	if (ret < 0)
8389 		goto out;
8390 
8391 	btrfs_lru_cache_for_each_entry_safe(&sctx->dir_utimes_cache, entry, tmp) {
8392 		ret = send_utimes(sctx, entry->key, entry->gen);
8393 		if (ret < 0)
8394 			goto out;
8395 		btrfs_lru_cache_remove(&sctx->dir_utimes_cache, entry);
8396 	}
8397 
8398 	if (!(sctx->flags & BTRFS_SEND_FLAG_OMIT_END_CMD)) {
8399 		ret = begin_cmd(sctx, BTRFS_SEND_C_END);
8400 		if (ret < 0)
8401 			goto out;
8402 		ret = send_cmd(sctx);
8403 		if (ret < 0)
8404 			goto out;
8405 	}
8406 
8407 out:
8408 	WARN_ON(sctx && !ret && !RB_EMPTY_ROOT(&sctx->pending_dir_moves));
8409 	while (sctx && !RB_EMPTY_ROOT(&sctx->pending_dir_moves)) {
8410 		struct rb_node *n;
8411 		struct pending_dir_move *pm;
8412 
8413 		n = rb_first(&sctx->pending_dir_moves);
8414 		pm = rb_entry(n, struct pending_dir_move, node);
8415 		while (!list_empty(&pm->list)) {
8416 			struct pending_dir_move *pm2;
8417 
8418 			pm2 = list_first_entry(&pm->list,
8419 					       struct pending_dir_move, list);
8420 			free_pending_move(sctx, pm2);
8421 		}
8422 		free_pending_move(sctx, pm);
8423 	}
8424 
8425 	WARN_ON(sctx && !ret && !RB_EMPTY_ROOT(&sctx->waiting_dir_moves));
8426 	while (sctx && !RB_EMPTY_ROOT(&sctx->waiting_dir_moves)) {
8427 		struct rb_node *n;
8428 		struct waiting_dir_move *dm;
8429 
8430 		n = rb_first(&sctx->waiting_dir_moves);
8431 		dm = rb_entry(n, struct waiting_dir_move, node);
8432 		rb_erase(&dm->node, &sctx->waiting_dir_moves);
8433 		kfree(dm);
8434 	}
8435 
8436 	WARN_ON(sctx && !ret && !RB_EMPTY_ROOT(&sctx->orphan_dirs));
8437 	while (sctx && !RB_EMPTY_ROOT(&sctx->orphan_dirs)) {
8438 		struct rb_node *n;
8439 		struct orphan_dir_info *odi;
8440 
8441 		n = rb_first(&sctx->orphan_dirs);
8442 		odi = rb_entry(n, struct orphan_dir_info, node);
8443 		free_orphan_dir_info(sctx, odi);
8444 	}
8445 
8446 	if (sort_clone_roots) {
8447 		for (i = 0; i < sctx->clone_roots_cnt; i++) {
8448 			btrfs_root_dec_send_in_progress(
8449 					sctx->clone_roots[i].root);
8450 			btrfs_put_root(sctx->clone_roots[i].root);
8451 		}
8452 	} else {
8453 		for (i = 0; sctx && i < clone_sources_to_rollback; i++) {
8454 			btrfs_root_dec_send_in_progress(
8455 					sctx->clone_roots[i].root);
8456 			btrfs_put_root(sctx->clone_roots[i].root);
8457 		}
8458 
8459 		btrfs_root_dec_send_in_progress(send_root);
8460 	}
8461 	if (sctx && !IS_ERR_OR_NULL(sctx->parent_root)) {
8462 		btrfs_root_dec_send_in_progress(sctx->parent_root);
8463 		btrfs_put_root(sctx->parent_root);
8464 	}
8465 
8466 	kvfree(clone_sources_tmp);
8467 
8468 	if (sctx) {
8469 		if (sctx->send_filp)
8470 			fput(sctx->send_filp);
8471 
8472 		kvfree(sctx->clone_roots);
8473 		kfree(sctx->send_buf_pages);
8474 		kvfree(sctx->send_buf);
8475 		kvfree(sctx->verity_descriptor);
8476 
8477 		close_current_inode(sctx);
8478 
8479 		btrfs_lru_cache_clear(&sctx->name_cache);
8480 		btrfs_lru_cache_clear(&sctx->backref_cache);
8481 		btrfs_lru_cache_clear(&sctx->dir_created_cache);
8482 		btrfs_lru_cache_clear(&sctx->dir_utimes_cache);
8483 
8484 		kfree(sctx);
8485 	}
8486 
8487 	return ret;
8488 }
8489