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