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