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