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