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