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