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