xref: /linux/fs/btrfs/tree-mod-log.c (revision 5d7f3375cd574fc83f0cd30839b21455c0e79ae2)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include "messages.h"
4 #include "tree-mod-log.h"
5 #include "disk-io.h"
6 #include "fs.h"
7 #include "accessors.h"
8 #include "tree-checker.h"
9 
10 struct tree_mod_root {
11 	u64 logical;
12 	u8 level;
13 };
14 
15 struct tree_mod_elem {
16 	struct rb_node node;
17 	u64 logical;
18 	u64 seq;
19 	enum btrfs_mod_log_op op;
20 
21 	/*
22 	 * This is used for BTRFS_MOD_LOG_KEY_* and BTRFS_MOD_LOG_MOVE_KEYS
23 	 * operations.
24 	 */
25 	int slot;
26 
27 	/* This is used for BTRFS_MOD_LOG_KEY* and BTRFS_MOD_LOG_ROOT_REPLACE. */
28 	u64 generation;
29 
30 	union {
31 		/*
32 		 * This is used for the following op types:
33 		 *
34 		 *    BTRFS_MOD_LOG_KEY_REMOVE_WHILE_FREEING
35 		 *    BTRFS_MOD_LOG_KEY_REMOVE_WHILE_MOVING
36 		 *    BTRFS_MOD_LOG_KEY_REMOVE
37 		 *    BTRFS_MOD_LOG_KEY_REPLACE
38 		 */
39 		struct {
40 			struct btrfs_disk_key key;
41 			u64 blockptr;
42 		} slot_change;
43 
44 		/* This is used for op == BTRFS_MOD_LOG_MOVE_KEYS. */
45 		struct {
46 			int dst_slot;
47 			int nr_items;
48 		} move;
49 
50 		/* This is used for op == BTRFS_MOD_LOG_ROOT_REPLACE. */
51 		struct tree_mod_root old_root;
52 	};
53 };
54 
55 /*
56  * Pull a new tree mod seq number for our operation.
57  */
58 static u64 btrfs_inc_tree_mod_seq(struct btrfs_fs_info *fs_info)
59 {
60 	return atomic64_inc_return(&fs_info->tree_mod_seq);
61 }
62 
63 /*
64  * This adds a new blocker to the tree mod log's blocker list if the @elem
65  * passed does not already have a sequence number set. So when a caller expects
66  * to record tree modifications, it should ensure to set elem->seq to zero
67  * before calling btrfs_get_tree_mod_seq.
68  * Returns a fresh, unused tree log modification sequence number, even if no new
69  * blocker was added.
70  */
71 u64 btrfs_get_tree_mod_seq(struct btrfs_fs_info *fs_info,
72 			   struct btrfs_seq_list *elem)
73 {
74 	write_lock(&fs_info->tree_mod_log_lock);
75 	if (!elem->seq) {
76 		elem->seq = btrfs_inc_tree_mod_seq(fs_info);
77 		list_add_tail(&elem->list, &fs_info->tree_mod_seq_list);
78 		set_bit(BTRFS_FS_TREE_MOD_LOG_USERS, &fs_info->flags);
79 	}
80 	write_unlock(&fs_info->tree_mod_log_lock);
81 
82 	return elem->seq;
83 }
84 
85 void btrfs_put_tree_mod_seq(struct btrfs_fs_info *fs_info,
86 			    struct btrfs_seq_list *elem)
87 {
88 	struct rb_root *tm_root;
89 	struct rb_node *node;
90 	struct rb_node *next;
91 	struct tree_mod_elem *tm;
92 	u64 min_seq = BTRFS_SEQ_LAST;
93 	u64 seq_putting = elem->seq;
94 
95 	if (!seq_putting)
96 		return;
97 
98 	write_lock(&fs_info->tree_mod_log_lock);
99 	list_del(&elem->list);
100 	elem->seq = 0;
101 
102 	if (list_empty(&fs_info->tree_mod_seq_list)) {
103 		clear_bit(BTRFS_FS_TREE_MOD_LOG_USERS, &fs_info->flags);
104 	} else {
105 		struct btrfs_seq_list *first;
106 
107 		first = list_first_entry(&fs_info->tree_mod_seq_list,
108 					 struct btrfs_seq_list, list);
109 		if (seq_putting > first->seq) {
110 			/*
111 			 * Blocker with lower sequence number exists, we cannot
112 			 * remove anything from the log.
113 			 */
114 			write_unlock(&fs_info->tree_mod_log_lock);
115 			return;
116 		}
117 		min_seq = first->seq;
118 	}
119 
120 	/*
121 	 * Anything that's lower than the lowest existing (read: blocked)
122 	 * sequence number can be removed from the tree.
123 	 */
124 	tm_root = &fs_info->tree_mod_log;
125 	for (node = rb_first(tm_root); node; node = next) {
126 		next = rb_next(node);
127 		tm = rb_entry(node, struct tree_mod_elem, node);
128 		if (tm->seq >= min_seq)
129 			continue;
130 		rb_erase(node, tm_root);
131 		kfree(tm);
132 	}
133 	write_unlock(&fs_info->tree_mod_log_lock);
134 }
135 
136 /*
137  * Key order of the log:
138  *       node/leaf start address -> sequence
139  *
140  * The 'start address' is the logical address of the *new* root node for root
141  * replace operations, or the logical address of the affected block for all
142  * other operations.
143  */
144 static noinline int tree_mod_log_insert(struct btrfs_fs_info *fs_info,
145 					struct tree_mod_elem *tm)
146 {
147 	struct rb_root *tm_root;
148 	struct rb_node **new;
149 	struct rb_node *parent = NULL;
150 	struct tree_mod_elem *cur;
151 
152 	lockdep_assert_held_write(&fs_info->tree_mod_log_lock);
153 
154 	tm->seq = btrfs_inc_tree_mod_seq(fs_info);
155 
156 	tm_root = &fs_info->tree_mod_log;
157 	new = &tm_root->rb_node;
158 	while (*new) {
159 		cur = rb_entry(*new, struct tree_mod_elem, node);
160 		parent = *new;
161 		if (cur->logical < tm->logical)
162 			new = &((*new)->rb_left);
163 		else if (cur->logical > tm->logical)
164 			new = &((*new)->rb_right);
165 		else if (cur->seq < tm->seq)
166 			new = &((*new)->rb_left);
167 		else if (cur->seq > tm->seq)
168 			new = &((*new)->rb_right);
169 		else
170 			return -EEXIST;
171 	}
172 
173 	rb_link_node(&tm->node, parent, new);
174 	rb_insert_color(&tm->node, tm_root);
175 	return 0;
176 }
177 
178 static inline bool skip_eb_logging(const struct extent_buffer *eb)
179 {
180 	const u64 owner = btrfs_header_owner(eb);
181 
182 	if (btrfs_header_level(eb) == 0)
183 		return true;
184 
185 	/*
186 	 * Tree mod logging exists so that there's a consistent view of the
187 	 * extents and backrefs of inodes even if while a task is iterating over
188 	 * them other tasks are modifying subvolume trees and the extent tree
189 	 * (including running delayed refs). So we only need to log extent
190 	 * buffers from the extent tree and subvolume trees.
191 	 */
192 
193 	if (owner == BTRFS_EXTENT_TREE_OBJECTID)
194 		return false;
195 
196 	if (btrfs_is_fstree(owner))
197 		return false;
198 
199 	return true;
200 }
201 
202 /*
203  * Determines if logging can be omitted. Returns true if it can. Otherwise, it
204  * returns false with the tree_mod_log_lock acquired. The caller must hold
205  * this until all tree mod log insertions are recorded in the rb tree and then
206  * write unlock fs_info::tree_mod_log_lock.
207  */
208 static bool tree_mod_dont_log(struct btrfs_fs_info *fs_info, const struct extent_buffer *eb)
209 {
210 	if (!test_bit(BTRFS_FS_TREE_MOD_LOG_USERS, &fs_info->flags))
211 		return true;
212 	if (eb && skip_eb_logging(eb))
213 		return true;
214 
215 	write_lock(&fs_info->tree_mod_log_lock);
216 	if (list_empty(&(fs_info)->tree_mod_seq_list)) {
217 		write_unlock(&fs_info->tree_mod_log_lock);
218 		return true;
219 	}
220 
221 	return false;
222 }
223 
224 /* Similar to tree_mod_dont_log, but doesn't acquire any locks. */
225 static bool tree_mod_need_log(const struct btrfs_fs_info *fs_info,
226 			      const struct extent_buffer *eb)
227 {
228 	if (!test_bit(BTRFS_FS_TREE_MOD_LOG_USERS, &fs_info->flags))
229 		return false;
230 	if (eb && skip_eb_logging(eb))
231 		return false;
232 
233 	return true;
234 }
235 
236 static struct tree_mod_elem *alloc_tree_mod_elem(const struct extent_buffer *eb,
237 						 int slot,
238 						 enum btrfs_mod_log_op op)
239 {
240 	struct tree_mod_elem *tm;
241 
242 	/* Can't be one of these types, due to union in struct tree_mod_elem. */
243 	ASSERT(op != BTRFS_MOD_LOG_MOVE_KEYS);
244 	ASSERT(op != BTRFS_MOD_LOG_ROOT_REPLACE);
245 
246 	tm = kzalloc_obj(*tm, GFP_NOFS);
247 	if (!tm)
248 		return NULL;
249 
250 	tm->logical = eb->start;
251 	btrfs_node_key(eb, &tm->slot_change.key, slot);
252 	tm->slot_change.blockptr = btrfs_node_blockptr(eb, slot);
253 	tm->op = op;
254 	tm->slot = slot;
255 	tm->generation = btrfs_node_ptr_generation(eb, slot);
256 	RB_CLEAR_NODE(&tm->node);
257 
258 	return tm;
259 }
260 
261 int btrfs_tree_mod_log_insert_key(const struct extent_buffer *eb, int slot,
262 				  enum btrfs_mod_log_op op)
263 {
264 	struct tree_mod_elem *tm;
265 	int ret = 0;
266 
267 	if (!tree_mod_need_log(eb->fs_info, eb))
268 		return 0;
269 
270 	tm = alloc_tree_mod_elem(eb, slot, op);
271 	if (!tm)
272 		ret = -ENOMEM;
273 
274 	if (tree_mod_dont_log(eb->fs_info, eb)) {
275 		kfree(tm);
276 		/*
277 		 * Don't error if we failed to allocate memory because we don't
278 		 * need to log.
279 		 */
280 		return 0;
281 	} else if (ret != 0) {
282 		/*
283 		 * We previously failed to allocate memory and we need to log,
284 		 * so we have to fail.
285 		 */
286 		goto out_unlock;
287 	}
288 
289 	ret = tree_mod_log_insert(eb->fs_info, tm);
290 out_unlock:
291 	write_unlock(&eb->fs_info->tree_mod_log_lock);
292 	if (ret)
293 		kfree(tm);
294 
295 	return ret;
296 }
297 
298 static struct tree_mod_elem *tree_mod_log_alloc_move(const struct extent_buffer *eb,
299 						     int dst_slot, int src_slot,
300 						     int nr_items)
301 {
302 	struct tree_mod_elem *tm;
303 
304 	tm = kzalloc_obj(*tm, GFP_NOFS);
305 	if (!tm)
306 		return ERR_PTR(-ENOMEM);
307 
308 	tm->logical = eb->start;
309 	tm->slot = src_slot;
310 	tm->move.dst_slot = dst_slot;
311 	tm->move.nr_items = nr_items;
312 	tm->op = BTRFS_MOD_LOG_MOVE_KEYS;
313 	RB_CLEAR_NODE(&tm->node);
314 
315 	return tm;
316 }
317 
318 int btrfs_tree_mod_log_insert_move(const struct extent_buffer *eb,
319 				   int dst_slot, int src_slot,
320 				   int nr_items)
321 {
322 	struct tree_mod_elem *tm = NULL;
323 	struct tree_mod_elem **tm_list = NULL;
324 	int ret = 0;
325 	int i;
326 	bool locked = false;
327 
328 	if (!tree_mod_need_log(eb->fs_info, eb))
329 		return 0;
330 
331 	tm_list = kzalloc_objs(struct tree_mod_elem *, nr_items, GFP_NOFS);
332 	if (!tm_list) {
333 		ret = -ENOMEM;
334 		goto lock;
335 	}
336 
337 	tm = tree_mod_log_alloc_move(eb, dst_slot, src_slot, nr_items);
338 	if (IS_ERR(tm)) {
339 		ret = PTR_ERR(tm);
340 		tm = NULL;
341 		goto lock;
342 	}
343 
344 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
345 		tm_list[i] = alloc_tree_mod_elem(eb, i + dst_slot,
346 				BTRFS_MOD_LOG_KEY_REMOVE_WHILE_MOVING);
347 		if (!tm_list[i]) {
348 			ret = -ENOMEM;
349 			goto lock;
350 		}
351 	}
352 
353 lock:
354 	if (tree_mod_dont_log(eb->fs_info, eb)) {
355 		/*
356 		 * Don't error if we failed to allocate memory because we don't
357 		 * need to log.
358 		 */
359 		ret = 0;
360 		goto free_tms;
361 	}
362 	locked = true;
363 
364 	/*
365 	 * We previously failed to allocate memory and we need to log, so we
366 	 * have to fail.
367 	 */
368 	if (ret != 0)
369 		goto free_tms;
370 
371 	/*
372 	 * When we override something during the move, we log these removals.
373 	 * This can only happen when we move towards the beginning of the
374 	 * buffer, i.e. dst_slot < src_slot.
375 	 */
376 	for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
377 		ret = tree_mod_log_insert(eb->fs_info, tm_list[i]);
378 		if (ret)
379 			goto free_tms;
380 	}
381 
382 	ret = tree_mod_log_insert(eb->fs_info, tm);
383 	if (ret)
384 		goto free_tms;
385 	write_unlock(&eb->fs_info->tree_mod_log_lock);
386 	kfree(tm_list);
387 
388 	return 0;
389 
390 free_tms:
391 	if (tm_list) {
392 		for (i = 0; i < nr_items; i++) {
393 			if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
394 				rb_erase(&tm_list[i]->node, &eb->fs_info->tree_mod_log);
395 			kfree(tm_list[i]);
396 		}
397 	}
398 	if (locked)
399 		write_unlock(&eb->fs_info->tree_mod_log_lock);
400 	kfree(tm_list);
401 	kfree(tm);
402 
403 	return ret;
404 }
405 
406 static int tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
407 				struct tree_mod_elem **tm_list,
408 				int nritems)
409 {
410 	int i, j;
411 	int ret;
412 
413 	for (i = nritems - 1; i >= 0; i--) {
414 		ret = tree_mod_log_insert(fs_info, tm_list[i]);
415 		if (ret) {
416 			for (j = nritems - 1; j > i; j--)
417 				rb_erase(&tm_list[j]->node,
418 					 &fs_info->tree_mod_log);
419 			return ret;
420 		}
421 	}
422 
423 	return 0;
424 }
425 
426 int btrfs_tree_mod_log_insert_root(struct extent_buffer *old_root,
427 				   struct extent_buffer *new_root,
428 				   bool log_removal)
429 {
430 	struct btrfs_fs_info *fs_info = old_root->fs_info;
431 	struct tree_mod_elem *tm = NULL;
432 	struct tree_mod_elem **tm_list = NULL;
433 	int nritems = 0;
434 	int ret = 0;
435 	int i;
436 
437 	if (!tree_mod_need_log(fs_info, NULL))
438 		return 0;
439 
440 	if (log_removal && btrfs_header_level(old_root) > 0) {
441 		nritems = btrfs_header_nritems(old_root);
442 		tm_list = kzalloc_objs(struct tree_mod_elem *, nritems,
443 				       GFP_NOFS);
444 		if (!tm_list) {
445 			ret = -ENOMEM;
446 			goto lock;
447 		}
448 		for (i = 0; i < nritems; i++) {
449 			tm_list[i] = alloc_tree_mod_elem(old_root, i,
450 			    BTRFS_MOD_LOG_KEY_REMOVE_WHILE_FREEING);
451 			if (!tm_list[i]) {
452 				ret = -ENOMEM;
453 				goto lock;
454 			}
455 		}
456 	}
457 
458 	tm = kzalloc_obj(*tm, GFP_NOFS);
459 	if (!tm) {
460 		ret = -ENOMEM;
461 		goto lock;
462 	}
463 
464 	tm->logical = new_root->start;
465 	tm->old_root.logical = old_root->start;
466 	tm->old_root.level = btrfs_header_level(old_root);
467 	tm->generation = btrfs_header_generation(old_root);
468 	tm->op = BTRFS_MOD_LOG_ROOT_REPLACE;
469 
470 lock:
471 	if (tree_mod_dont_log(fs_info, NULL)) {
472 		/*
473 		 * Don't error if we failed to allocate memory because we don't
474 		 * need to log.
475 		 */
476 		ret = 0;
477 		goto free_tms;
478 	} else if (ret != 0) {
479 		/*
480 		 * We previously failed to allocate memory and we need to log,
481 		 * so we have to fail.
482 		 */
483 		goto out_unlock;
484 	}
485 
486 	if (tm_list) {
487 		ret = tree_mod_log_free_eb(fs_info, tm_list, nritems);
488 		if (ret)
489 			goto out_unlock;
490 	}
491 
492 	ret = tree_mod_log_insert(fs_info, tm);
493 	if (ret && tm_list) {
494 		for (i = 0; i < nritems; i++)
495 			rb_erase(&tm_list[i]->node, &fs_info->tree_mod_log);
496 	}
497 
498 out_unlock:
499 	write_unlock(&fs_info->tree_mod_log_lock);
500 	if (ret)
501 		goto free_tms;
502 	kfree(tm_list);
503 
504 	return ret;
505 
506 free_tms:
507 	if (tm_list) {
508 		for (i = 0; i < nritems; i++)
509 			kfree(tm_list[i]);
510 		kfree(tm_list);
511 	}
512 	kfree(tm);
513 
514 	return ret;
515 }
516 
517 static struct tree_mod_elem *__tree_mod_log_search(struct btrfs_fs_info *fs_info,
518 						   u64 start, u64 min_seq,
519 						   bool smallest)
520 {
521 	struct rb_root *tm_root;
522 	struct rb_node *node;
523 	struct tree_mod_elem *cur = NULL;
524 	struct tree_mod_elem *found = NULL;
525 
526 	read_lock(&fs_info->tree_mod_log_lock);
527 	tm_root = &fs_info->tree_mod_log;
528 	node = tm_root->rb_node;
529 	while (node) {
530 		cur = rb_entry(node, struct tree_mod_elem, node);
531 		if (cur->logical < start) {
532 			node = node->rb_left;
533 		} else if (cur->logical > start) {
534 			node = node->rb_right;
535 		} else if (cur->seq < min_seq) {
536 			node = node->rb_left;
537 		} else if (!smallest) {
538 			/* We want the node with the highest seq */
539 			if (found)
540 				BUG_ON(found->seq > cur->seq);
541 			found = cur;
542 			node = node->rb_left;
543 		} else if (cur->seq > min_seq) {
544 			/* We want the node with the smallest seq */
545 			if (found)
546 				BUG_ON(found->seq < cur->seq);
547 			found = cur;
548 			node = node->rb_right;
549 		} else {
550 			found = cur;
551 			break;
552 		}
553 	}
554 	read_unlock(&fs_info->tree_mod_log_lock);
555 
556 	return found;
557 }
558 
559 /*
560  * This returns the element from the log with the smallest time sequence
561  * value that's in the log (the oldest log item). Any element with a time
562  * sequence lower than min_seq will be ignored.
563  */
564 static struct tree_mod_elem *tree_mod_log_search_oldest(struct btrfs_fs_info *fs_info,
565 							u64 start, u64 min_seq)
566 {
567 	return __tree_mod_log_search(fs_info, start, min_seq, true);
568 }
569 
570 /*
571  * This returns the element from the log with the largest time sequence
572  * value that's in the log (the most recent log item). Any element with
573  * a time sequence lower than min_seq will be ignored.
574  */
575 static struct tree_mod_elem *tree_mod_log_search(struct btrfs_fs_info *fs_info,
576 						 u64 start, u64 min_seq)
577 {
578 	return __tree_mod_log_search(fs_info, start, min_seq, false);
579 }
580 
581 int btrfs_tree_mod_log_eb_copy(struct extent_buffer *dst,
582 			       const struct extent_buffer *src,
583 			       unsigned long dst_offset,
584 			       unsigned long src_offset,
585 			       int nr_items)
586 {
587 	struct btrfs_fs_info *fs_info = dst->fs_info;
588 	int ret = 0;
589 	struct tree_mod_elem **tm_list = NULL;
590 	struct tree_mod_elem **tm_list_add = NULL;
591 	struct tree_mod_elem **tm_list_rem = NULL;
592 	int i;
593 	bool locked = false;
594 	struct tree_mod_elem *dst_move_tm = NULL;
595 	struct tree_mod_elem *src_move_tm = NULL;
596 	u32 dst_move_nr_items = btrfs_header_nritems(dst) - dst_offset;
597 	u32 src_move_nr_items = btrfs_header_nritems(src) - (src_offset + nr_items);
598 
599 	if (!tree_mod_need_log(fs_info, NULL))
600 		return 0;
601 
602 	if (btrfs_header_level(dst) == 0 && btrfs_header_level(src) == 0)
603 		return 0;
604 
605 	tm_list = kzalloc_objs(struct tree_mod_elem *, nr_items * 2, GFP_NOFS);
606 	if (!tm_list) {
607 		ret = -ENOMEM;
608 		goto lock;
609 	}
610 
611 	if (dst_move_nr_items) {
612 		dst_move_tm = tree_mod_log_alloc_move(dst, dst_offset + nr_items,
613 						      dst_offset, dst_move_nr_items);
614 		if (IS_ERR(dst_move_tm)) {
615 			ret = PTR_ERR(dst_move_tm);
616 			dst_move_tm = NULL;
617 			goto lock;
618 		}
619 	}
620 	if (src_move_nr_items) {
621 		src_move_tm = tree_mod_log_alloc_move(src, src_offset,
622 						      src_offset + nr_items,
623 						      src_move_nr_items);
624 		if (IS_ERR(src_move_tm)) {
625 			ret = PTR_ERR(src_move_tm);
626 			src_move_tm = NULL;
627 			goto lock;
628 		}
629 	}
630 
631 	tm_list_add = tm_list;
632 	tm_list_rem = tm_list + nr_items;
633 	for (i = 0; i < nr_items; i++) {
634 		tm_list_rem[i] = alloc_tree_mod_elem(src, i + src_offset,
635 						     BTRFS_MOD_LOG_KEY_REMOVE);
636 		if (!tm_list_rem[i]) {
637 			ret = -ENOMEM;
638 			goto lock;
639 		}
640 
641 		tm_list_add[i] = alloc_tree_mod_elem(dst, i + dst_offset,
642 						     BTRFS_MOD_LOG_KEY_ADD);
643 		if (!tm_list_add[i]) {
644 			ret = -ENOMEM;
645 			goto lock;
646 		}
647 	}
648 
649 lock:
650 	if (tree_mod_dont_log(fs_info, NULL)) {
651 		/*
652 		 * Don't error if we failed to allocate memory because we don't
653 		 * need to log.
654 		 */
655 		ret = 0;
656 		goto free_tms;
657 	}
658 	locked = true;
659 
660 	/*
661 	 * We previously failed to allocate memory and we need to log, so we
662 	 * have to fail.
663 	 */
664 	if (ret != 0)
665 		goto free_tms;
666 
667 	if (dst_move_tm) {
668 		ret = tree_mod_log_insert(fs_info, dst_move_tm);
669 		if (ret)
670 			goto free_tms;
671 	}
672 	for (i = 0; i < nr_items; i++) {
673 		ret = tree_mod_log_insert(fs_info, tm_list_rem[i]);
674 		if (ret)
675 			goto free_tms;
676 		ret = tree_mod_log_insert(fs_info, tm_list_add[i]);
677 		if (ret)
678 			goto free_tms;
679 	}
680 	if (src_move_tm) {
681 		ret = tree_mod_log_insert(fs_info, src_move_tm);
682 		if (ret)
683 			goto free_tms;
684 	}
685 
686 	write_unlock(&fs_info->tree_mod_log_lock);
687 	kfree(tm_list);
688 
689 	return 0;
690 
691 free_tms:
692 	if (dst_move_tm && !RB_EMPTY_NODE(&dst_move_tm->node))
693 		rb_erase(&dst_move_tm->node, &fs_info->tree_mod_log);
694 	kfree(dst_move_tm);
695 	if (src_move_tm && !RB_EMPTY_NODE(&src_move_tm->node))
696 		rb_erase(&src_move_tm->node, &fs_info->tree_mod_log);
697 	kfree(src_move_tm);
698 	if (tm_list) {
699 		for (i = 0; i < nr_items * 2; i++) {
700 			if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
701 				rb_erase(&tm_list[i]->node, &fs_info->tree_mod_log);
702 			kfree(tm_list[i]);
703 		}
704 	}
705 	if (locked)
706 		write_unlock(&fs_info->tree_mod_log_lock);
707 	kfree(tm_list);
708 
709 	return ret;
710 }
711 
712 int btrfs_tree_mod_log_free_eb(struct extent_buffer *eb)
713 {
714 	struct tree_mod_elem **tm_list = NULL;
715 	int nritems = 0;
716 	int i;
717 	int ret = 0;
718 
719 	if (!tree_mod_need_log(eb->fs_info, eb))
720 		return 0;
721 
722 	nritems = btrfs_header_nritems(eb);
723 	tm_list = kzalloc_objs(struct tree_mod_elem *, nritems, GFP_NOFS);
724 	if (!tm_list) {
725 		ret = -ENOMEM;
726 		goto lock;
727 	}
728 
729 	for (i = 0; i < nritems; i++) {
730 		tm_list[i] = alloc_tree_mod_elem(eb, i,
731 				    BTRFS_MOD_LOG_KEY_REMOVE_WHILE_FREEING);
732 		if (!tm_list[i]) {
733 			ret = -ENOMEM;
734 			goto lock;
735 		}
736 	}
737 
738 lock:
739 	if (tree_mod_dont_log(eb->fs_info, eb)) {
740 		/*
741 		 * Don't error if we failed to allocate memory because we don't
742 		 * need to log.
743 		 */
744 		ret = 0;
745 		goto free_tms;
746 	} else if (ret != 0) {
747 		/*
748 		 * We previously failed to allocate memory and we need to log,
749 		 * so we have to fail.
750 		 */
751 		goto out_unlock;
752 	}
753 
754 	ret = tree_mod_log_free_eb(eb->fs_info, tm_list, nritems);
755 out_unlock:
756 	write_unlock(&eb->fs_info->tree_mod_log_lock);
757 	if (ret)
758 		goto free_tms;
759 	kfree(tm_list);
760 
761 	return 0;
762 
763 free_tms:
764 	if (tm_list) {
765 		for (i = 0; i < nritems; i++)
766 			kfree(tm_list[i]);
767 		kfree(tm_list);
768 	}
769 
770 	return ret;
771 }
772 
773 /*
774  * Returns the logical address of the oldest predecessor of the given root.
775  * Entries older than time_seq are ignored.
776  */
777 static struct tree_mod_elem *tree_mod_log_oldest_root(struct extent_buffer *eb_root,
778 						      u64 time_seq)
779 {
780 	struct tree_mod_elem *tm;
781 	struct tree_mod_elem *found = NULL;
782 	u64 root_logical = eb_root->start;
783 	bool looped = false;
784 
785 	if (!time_seq)
786 		return NULL;
787 
788 	/*
789 	 * The very last operation that's logged for a root is the replacement
790 	 * operation (if it is replaced at all). This has the logical address
791 	 * of the *new* root, making it the very first operation that's logged
792 	 * for this root.
793 	 */
794 	while (1) {
795 		tm = tree_mod_log_search_oldest(eb_root->fs_info, root_logical,
796 						time_seq);
797 		if (!looped && !tm)
798 			return NULL;
799 		/*
800 		 * If there are no tree operation for the oldest root, we simply
801 		 * return it. This should only happen if that (old) root is at
802 		 * level 0.
803 		 */
804 		if (!tm)
805 			break;
806 
807 		/*
808 		 * If there's an operation that's not a root replacement, we
809 		 * found the oldest version of our root. Normally, we'll find a
810 		 * BTRFS_MOD_LOG_KEY_REMOVE_WHILE_FREEING operation here.
811 		 */
812 		if (tm->op != BTRFS_MOD_LOG_ROOT_REPLACE)
813 			break;
814 
815 		found = tm;
816 		root_logical = tm->old_root.logical;
817 		looped = true;
818 	}
819 
820 	/* If there's no old root to return, return what we found instead */
821 	if (!found)
822 		found = tm;
823 
824 	return found;
825 }
826 
827 
828 /*
829  * tm is a pointer to the first operation to rewind within eb. Then, all
830  * previous operations will be rewound (until we reach something older than
831  * time_seq).
832  */
833 static void tree_mod_log_rewind(struct btrfs_fs_info *fs_info,
834 				struct extent_buffer *eb,
835 				u64 time_seq,
836 				struct tree_mod_elem *first_tm)
837 {
838 	u32 n;
839 	struct rb_node *next;
840 	struct tree_mod_elem *tm = first_tm;
841 	unsigned long o_dst;
842 	unsigned long o_src;
843 	unsigned long p_size = sizeof(struct btrfs_key_ptr);
844 	/*
845 	 * max_slot tracks the maximum valid slot of the rewind eb at every
846 	 * step of the rewind. This is in contrast with 'n' which eventually
847 	 * matches the number of items, but can be wrong during moves or if
848 	 * removes overlap on already valid slots (which is probably separately
849 	 * a bug). We do this to validate the offsets of memmoves for rewinding
850 	 * moves and detect invalid memmoves.
851 	 *
852 	 * Since a rewind eb can start empty, max_slot is a signed integer with
853 	 * a special meaning for -1, which is that no slot is valid to move out
854 	 * of. Any other negative value is invalid.
855 	 */
856 	int max_slot;
857 	int move_src_end_slot;
858 	int move_dst_end_slot;
859 
860 	n = btrfs_header_nritems(eb);
861 	max_slot = n - 1;
862 	read_lock(&fs_info->tree_mod_log_lock);
863 	while (tm && tm->seq >= time_seq) {
864 		ASSERT(max_slot >= -1);
865 		/*
866 		 * All the operations are recorded with the operator used for
867 		 * the modification. As we're going backwards, we do the
868 		 * opposite of each operation here.
869 		 */
870 		switch (tm->op) {
871 		case BTRFS_MOD_LOG_KEY_REMOVE_WHILE_FREEING:
872 			BUG_ON(tm->slot < n);
873 			fallthrough;
874 		case BTRFS_MOD_LOG_KEY_REMOVE_WHILE_MOVING:
875 		case BTRFS_MOD_LOG_KEY_REMOVE:
876 			btrfs_set_node_key(eb, &tm->slot_change.key, tm->slot);
877 			btrfs_set_node_blockptr(eb, tm->slot, tm->slot_change.blockptr);
878 			btrfs_set_node_ptr_generation(eb, tm->slot,
879 						      tm->generation);
880 			n++;
881 			if (tm->slot > max_slot)
882 				max_slot = tm->slot;
883 			break;
884 		case BTRFS_MOD_LOG_KEY_REPLACE:
885 			BUG_ON(tm->slot >= n);
886 			btrfs_set_node_key(eb, &tm->slot_change.key, tm->slot);
887 			btrfs_set_node_blockptr(eb, tm->slot, tm->slot_change.blockptr);
888 			btrfs_set_node_ptr_generation(eb, tm->slot,
889 						      tm->generation);
890 			break;
891 		case BTRFS_MOD_LOG_KEY_ADD:
892 			/*
893 			 * It is possible we could have already removed keys
894 			 * behind the known max slot, so this will be an
895 			 * overestimate. In practice, the copy operation
896 			 * inserts them in increasing order, and overestimating
897 			 * just means we miss some warnings, so it's OK. It
898 			 * isn't worth carefully tracking the full array of
899 			 * valid slots to check against when moving.
900 			 */
901 			if (tm->slot == max_slot)
902 				max_slot--;
903 			/* if a move operation is needed it's in the log */
904 			n--;
905 			break;
906 		case BTRFS_MOD_LOG_MOVE_KEYS:
907 			ASSERT(tm->move.nr_items > 0);
908 			move_src_end_slot = tm->move.dst_slot + tm->move.nr_items - 1;
909 			move_dst_end_slot = tm->slot + tm->move.nr_items - 1;
910 			o_dst = btrfs_node_key_ptr_offset(eb, tm->slot);
911 			o_src = btrfs_node_key_ptr_offset(eb, tm->move.dst_slot);
912 			if (WARN_ON(move_src_end_slot > max_slot ||
913 				    tm->move.nr_items <= 0)) {
914 				btrfs_warn(fs_info,
915 "move from invalid tree mod log slot eb %llu slot %d dst_slot %d nr_items %d seq %llu n %u max_slot %d",
916 					   eb->start, tm->slot,
917 					   tm->move.dst_slot, tm->move.nr_items,
918 					   tm->seq, n, max_slot);
919 			}
920 			memmove_extent_buffer(eb, o_dst, o_src,
921 					      tm->move.nr_items * p_size);
922 			max_slot = move_dst_end_slot;
923 			break;
924 		case BTRFS_MOD_LOG_ROOT_REPLACE:
925 			/*
926 			 * This operation is special. For roots, this must be
927 			 * handled explicitly before rewinding.
928 			 * For non-roots, this operation may exist if the node
929 			 * was a root: root A -> child B; then A gets empty and
930 			 * B is promoted to the new root. In the mod log, we'll
931 			 * have a root-replace operation for B, a tree block
932 			 * that is no root. We simply ignore that operation.
933 			 */
934 			break;
935 		}
936 		next = rb_next(&tm->node);
937 		if (!next)
938 			break;
939 		tm = rb_entry(next, struct tree_mod_elem, node);
940 		if (tm->logical != first_tm->logical)
941 			break;
942 	}
943 	read_unlock(&fs_info->tree_mod_log_lock);
944 	btrfs_set_header_nritems(eb, n);
945 }
946 
947 /*
948  * Called with eb read locked. If the buffer cannot be rewound, the same buffer
949  * is returned. If rewind operations happen, a fresh buffer is returned. The
950  * returned buffer is always read-locked. If the returned buffer is not the
951  * input buffer, the lock on the input buffer is released and the input buffer
952  * is freed (its refcount is decremented).
953  */
954 struct extent_buffer *btrfs_tree_mod_log_rewind(struct btrfs_fs_info *fs_info,
955 						struct extent_buffer *eb,
956 						u64 time_seq)
957 {
958 	struct extent_buffer *eb_rewin;
959 	struct tree_mod_elem *tm;
960 
961 	if (!time_seq)
962 		return eb;
963 
964 	if (btrfs_header_level(eb) == 0)
965 		return eb;
966 
967 	tm = tree_mod_log_search(fs_info, eb->start, time_seq);
968 	if (!tm)
969 		return eb;
970 
971 	if (tm->op == BTRFS_MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
972 		BUG_ON(tm->slot != 0);
973 		eb_rewin = alloc_dummy_extent_buffer(fs_info, eb->start);
974 		if (!eb_rewin) {
975 			btrfs_tree_read_unlock(eb);
976 			free_extent_buffer(eb);
977 			return NULL;
978 		}
979 		btrfs_set_header_bytenr(eb_rewin, eb->start);
980 		btrfs_set_header_backref_rev(eb_rewin,
981 					     btrfs_header_backref_rev(eb));
982 		btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
983 		btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
984 	} else {
985 		eb_rewin = btrfs_clone_extent_buffer(eb);
986 		if (!eb_rewin) {
987 			btrfs_tree_read_unlock(eb);
988 			free_extent_buffer(eb);
989 			return NULL;
990 		}
991 	}
992 
993 	btrfs_tree_read_unlock(eb);
994 	free_extent_buffer(eb);
995 
996 	btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb_rewin),
997 				       eb_rewin, btrfs_header_level(eb_rewin));
998 	btrfs_tree_read_lock(eb_rewin);
999 	tree_mod_log_rewind(fs_info, eb_rewin, time_seq, tm);
1000 	WARN_ON(btrfs_header_nritems(eb_rewin) >
1001 		BTRFS_NODEPTRS_PER_BLOCK(fs_info));
1002 
1003 	return eb_rewin;
1004 }
1005 
1006 /*
1007  * Rewind the state of @root's root node to the given @time_seq value.
1008  * If there are no changes, the current root->root_node is returned. If anything
1009  * changed in between, there's a fresh buffer allocated on which the rewind
1010  * operations are done. In any case, the returned buffer is read locked.
1011  * Returns NULL on error (with no locks held).
1012  */
1013 struct extent_buffer *btrfs_get_old_root(struct btrfs_root *root, u64 time_seq)
1014 {
1015 	struct btrfs_fs_info *fs_info = root->fs_info;
1016 	struct tree_mod_elem *tm;
1017 	struct extent_buffer *eb = NULL;
1018 	struct extent_buffer *eb_root;
1019 	u64 eb_root_owner = 0;
1020 	struct extent_buffer *old;
1021 	struct tree_mod_root *old_root = NULL;
1022 	u64 old_generation = 0;
1023 	u64 logical;
1024 	int level;
1025 
1026 	eb_root = btrfs_read_lock_root_node(root);
1027 	tm = tree_mod_log_oldest_root(eb_root, time_seq);
1028 	if (!tm)
1029 		return eb_root;
1030 
1031 	if (tm->op == BTRFS_MOD_LOG_ROOT_REPLACE) {
1032 		old_root = &tm->old_root;
1033 		old_generation = tm->generation;
1034 		logical = old_root->logical;
1035 		level = old_root->level;
1036 	} else {
1037 		logical = eb_root->start;
1038 		level = btrfs_header_level(eb_root);
1039 	}
1040 
1041 	tm = tree_mod_log_search(fs_info, logical, time_seq);
1042 	if (old_root && tm && tm->op != BTRFS_MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
1043 		struct btrfs_tree_parent_check check = { 0 };
1044 
1045 		btrfs_tree_read_unlock(eb_root);
1046 		free_extent_buffer(eb_root);
1047 
1048 		check.level = level;
1049 		check.owner_root = btrfs_root_id(root);
1050 
1051 		old = read_tree_block(fs_info, logical, &check);
1052 		if (WARN_ON(IS_ERR(old))) {
1053 			btrfs_warn(fs_info,
1054 				   "failed to read tree block %llu from get_old_root: %ld",
1055 				   logical, PTR_ERR(old));
1056 		} else {
1057 			struct tree_mod_elem *tm2;
1058 
1059 			btrfs_tree_read_lock(old);
1060 			eb = btrfs_clone_extent_buffer(old);
1061 			/*
1062 			 * After the lookup for the most recent tree mod operation
1063 			 * above and before we locked and cloned the extent buffer
1064 			 * 'old', a new tree mod log operation may have been added.
1065 			 * So lookup for a more recent one to make sure the number
1066 			 * of mod log operations we replay is consistent with the
1067 			 * number of items we have in the cloned extent buffer,
1068 			 * otherwise we can hit a BUG_ON when rewinding the extent
1069 			 * buffer.
1070 			 */
1071 			tm2 = tree_mod_log_search(fs_info, logical, time_seq);
1072 			btrfs_tree_read_unlock(old);
1073 			free_extent_buffer(old);
1074 			ASSERT(tm2);
1075 			ASSERT(tm2 == tm || tm2->seq > tm->seq);
1076 			if (!tm2 || tm2->seq < tm->seq) {
1077 				free_extent_buffer(eb);
1078 				return NULL;
1079 			}
1080 			tm = tm2;
1081 		}
1082 	} else if (old_root) {
1083 		eb_root_owner = btrfs_header_owner(eb_root);
1084 		btrfs_tree_read_unlock(eb_root);
1085 		free_extent_buffer(eb_root);
1086 		eb = alloc_dummy_extent_buffer(fs_info, logical);
1087 	} else {
1088 		eb = btrfs_clone_extent_buffer(eb_root);
1089 		btrfs_tree_read_unlock(eb_root);
1090 		free_extent_buffer(eb_root);
1091 	}
1092 
1093 	if (!eb)
1094 		return NULL;
1095 	if (old_root) {
1096 		btrfs_set_header_bytenr(eb, eb->start);
1097 		btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
1098 		btrfs_set_header_owner(eb, eb_root_owner);
1099 		btrfs_set_header_level(eb, old_root->level);
1100 		btrfs_set_header_generation(eb, old_generation);
1101 	}
1102 	btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb), eb,
1103 				       btrfs_header_level(eb));
1104 	btrfs_tree_read_lock(eb);
1105 	if (tm)
1106 		tree_mod_log_rewind(fs_info, eb, time_seq, tm);
1107 	else
1108 		WARN_ON(btrfs_header_level(eb) != 0);
1109 	WARN_ON(btrfs_header_nritems(eb) > BTRFS_NODEPTRS_PER_BLOCK(fs_info));
1110 
1111 	return eb;
1112 }
1113 
1114 int btrfs_old_root_level(struct btrfs_root *root, u64 time_seq)
1115 {
1116 	struct tree_mod_elem *tm;
1117 	int level;
1118 	struct extent_buffer *eb_root = btrfs_root_node(root);
1119 
1120 	tm = tree_mod_log_oldest_root(eb_root, time_seq);
1121 	if (tm && tm->op == BTRFS_MOD_LOG_ROOT_REPLACE)
1122 		level = tm->old_root.level;
1123 	else
1124 		level = btrfs_header_level(eb_root);
1125 
1126 	free_extent_buffer(eb_root);
1127 
1128 	return level;
1129 }
1130 
1131 /*
1132  * Return the lowest sequence number in the tree modification log.
1133  *
1134  * Return the sequence number of the oldest tree modification log user, which
1135  * corresponds to the lowest sequence number of all existing users. If there are
1136  * no users it returns 0.
1137  */
1138 u64 btrfs_tree_mod_log_lowest_seq(struct btrfs_fs_info *fs_info)
1139 {
1140 	u64 ret = 0;
1141 
1142 	read_lock(&fs_info->tree_mod_log_lock);
1143 	if (!list_empty(&fs_info->tree_mod_seq_list)) {
1144 		struct btrfs_seq_list *elem;
1145 
1146 		elem = list_first_entry(&fs_info->tree_mod_seq_list,
1147 					struct btrfs_seq_list, list);
1148 		ret = elem->seq;
1149 	}
1150 	read_unlock(&fs_info->tree_mod_log_lock);
1151 
1152 	return ret;
1153 }
1154