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