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