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