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