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