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