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