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