xref: /openbmc/linux/fs/btrfs/extent_map.c (revision 6f69e2a3)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include <linux/err.h>
4 #include <linux/slab.h>
5 #include <linux/spinlock.h>
6 #include "ctree.h"
7 #include "volumes.h"
8 #include "extent_map.h"
9 #include "compression.h"
10 
11 
12 static struct kmem_cache *extent_map_cache;
13 
14 int __init extent_map_init(void)
15 {
16 	extent_map_cache = kmem_cache_create("btrfs_extent_map",
17 			sizeof(struct extent_map), 0,
18 			SLAB_MEM_SPREAD, NULL);
19 	if (!extent_map_cache)
20 		return -ENOMEM;
21 	return 0;
22 }
23 
24 void __cold extent_map_exit(void)
25 {
26 	kmem_cache_destroy(extent_map_cache);
27 }
28 
29 /**
30  * extent_map_tree_init - initialize extent map tree
31  * @tree:		tree to initialize
32  *
33  * Initialize the extent tree @tree.  Should be called for each new inode
34  * or other user of the extent_map interface.
35  */
36 void extent_map_tree_init(struct extent_map_tree *tree)
37 {
38 	tree->map = RB_ROOT_CACHED;
39 	INIT_LIST_HEAD(&tree->modified_extents);
40 	rwlock_init(&tree->lock);
41 }
42 
43 /**
44  * alloc_extent_map - allocate new extent map structure
45  *
46  * Allocate a new extent_map structure.  The new structure is
47  * returned with a reference count of one and needs to be
48  * freed using free_extent_map()
49  */
50 struct extent_map *alloc_extent_map(void)
51 {
52 	struct extent_map *em;
53 	em = kmem_cache_zalloc(extent_map_cache, GFP_NOFS);
54 	if (!em)
55 		return NULL;
56 	RB_CLEAR_NODE(&em->rb_node);
57 	em->flags = 0;
58 	em->compress_type = BTRFS_COMPRESS_NONE;
59 	em->generation = 0;
60 	refcount_set(&em->refs, 1);
61 	INIT_LIST_HEAD(&em->list);
62 	return em;
63 }
64 
65 /**
66  * free_extent_map - drop reference count of an extent_map
67  * @em:		extent map being released
68  *
69  * Drops the reference out on @em by one and free the structure
70  * if the reference count hits zero.
71  */
72 void free_extent_map(struct extent_map *em)
73 {
74 	if (!em)
75 		return;
76 	WARN_ON(refcount_read(&em->refs) == 0);
77 	if (refcount_dec_and_test(&em->refs)) {
78 		WARN_ON(extent_map_in_tree(em));
79 		WARN_ON(!list_empty(&em->list));
80 		if (test_bit(EXTENT_FLAG_FS_MAPPING, &em->flags))
81 			kfree(em->map_lookup);
82 		kmem_cache_free(extent_map_cache, em);
83 	}
84 }
85 
86 /* simple helper to do math around the end of an extent, handling wrap */
87 static u64 range_end(u64 start, u64 len)
88 {
89 	if (start + len < start)
90 		return (u64)-1;
91 	return start + len;
92 }
93 
94 static int tree_insert(struct rb_root_cached *root, struct extent_map *em)
95 {
96 	struct rb_node **p = &root->rb_root.rb_node;
97 	struct rb_node *parent = NULL;
98 	struct extent_map *entry = NULL;
99 	struct rb_node *orig_parent = NULL;
100 	u64 end = range_end(em->start, em->len);
101 	bool leftmost = true;
102 
103 	while (*p) {
104 		parent = *p;
105 		entry = rb_entry(parent, struct extent_map, rb_node);
106 
107 		if (em->start < entry->start) {
108 			p = &(*p)->rb_left;
109 		} else if (em->start >= extent_map_end(entry)) {
110 			p = &(*p)->rb_right;
111 			leftmost = false;
112 		} else {
113 			return -EEXIST;
114 		}
115 	}
116 
117 	orig_parent = parent;
118 	while (parent && em->start >= extent_map_end(entry)) {
119 		parent = rb_next(parent);
120 		entry = rb_entry(parent, struct extent_map, rb_node);
121 	}
122 	if (parent)
123 		if (end > entry->start && em->start < extent_map_end(entry))
124 			return -EEXIST;
125 
126 	parent = orig_parent;
127 	entry = rb_entry(parent, struct extent_map, rb_node);
128 	while (parent && em->start < entry->start) {
129 		parent = rb_prev(parent);
130 		entry = rb_entry(parent, struct extent_map, rb_node);
131 	}
132 	if (parent)
133 		if (end > entry->start && em->start < extent_map_end(entry))
134 			return -EEXIST;
135 
136 	rb_link_node(&em->rb_node, orig_parent, p);
137 	rb_insert_color_cached(&em->rb_node, root, leftmost);
138 	return 0;
139 }
140 
141 /*
142  * search through the tree for an extent_map with a given offset.  If
143  * it can't be found, try to find some neighboring extents
144  */
145 static struct rb_node *__tree_search(struct rb_root *root, u64 offset,
146 				     struct rb_node **prev_ret,
147 				     struct rb_node **next_ret)
148 {
149 	struct rb_node *n = root->rb_node;
150 	struct rb_node *prev = NULL;
151 	struct rb_node *orig_prev = NULL;
152 	struct extent_map *entry;
153 	struct extent_map *prev_entry = NULL;
154 
155 	while (n) {
156 		entry = rb_entry(n, struct extent_map, rb_node);
157 		prev = n;
158 		prev_entry = entry;
159 
160 		if (offset < entry->start)
161 			n = n->rb_left;
162 		else if (offset >= extent_map_end(entry))
163 			n = n->rb_right;
164 		else
165 			return n;
166 	}
167 
168 	if (prev_ret) {
169 		orig_prev = prev;
170 		while (prev && offset >= extent_map_end(prev_entry)) {
171 			prev = rb_next(prev);
172 			prev_entry = rb_entry(prev, struct extent_map, rb_node);
173 		}
174 		*prev_ret = prev;
175 		prev = orig_prev;
176 	}
177 
178 	if (next_ret) {
179 		prev_entry = rb_entry(prev, struct extent_map, rb_node);
180 		while (prev && offset < prev_entry->start) {
181 			prev = rb_prev(prev);
182 			prev_entry = rb_entry(prev, struct extent_map, rb_node);
183 		}
184 		*next_ret = prev;
185 	}
186 	return NULL;
187 }
188 
189 /* check to see if two extent_map structs are adjacent and safe to merge */
190 static int mergable_maps(struct extent_map *prev, struct extent_map *next)
191 {
192 	if (test_bit(EXTENT_FLAG_PINNED, &prev->flags))
193 		return 0;
194 
195 	/*
196 	 * don't merge compressed extents, we need to know their
197 	 * actual size
198 	 */
199 	if (test_bit(EXTENT_FLAG_COMPRESSED, &prev->flags))
200 		return 0;
201 
202 	if (test_bit(EXTENT_FLAG_LOGGING, &prev->flags) ||
203 	    test_bit(EXTENT_FLAG_LOGGING, &next->flags))
204 		return 0;
205 
206 	/*
207 	 * We don't want to merge stuff that hasn't been written to the log yet
208 	 * since it may not reflect exactly what is on disk, and that would be
209 	 * bad.
210 	 */
211 	if (!list_empty(&prev->list) || !list_empty(&next->list))
212 		return 0;
213 
214 	ASSERT(next->block_start != EXTENT_MAP_DELALLOC &&
215 	       prev->block_start != EXTENT_MAP_DELALLOC);
216 
217 	if (prev->map_lookup || next->map_lookup)
218 		ASSERT(test_bit(EXTENT_FLAG_FS_MAPPING, &prev->flags) &&
219 		       test_bit(EXTENT_FLAG_FS_MAPPING, &next->flags));
220 
221 	if (extent_map_end(prev) == next->start &&
222 	    prev->flags == next->flags &&
223 	    prev->map_lookup == next->map_lookup &&
224 	    ((next->block_start == EXTENT_MAP_HOLE &&
225 	      prev->block_start == EXTENT_MAP_HOLE) ||
226 	     (next->block_start == EXTENT_MAP_INLINE &&
227 	      prev->block_start == EXTENT_MAP_INLINE) ||
228 	     (next->block_start < EXTENT_MAP_LAST_BYTE - 1 &&
229 	      next->block_start == extent_map_block_end(prev)))) {
230 		return 1;
231 	}
232 	return 0;
233 }
234 
235 static void try_merge_map(struct extent_map_tree *tree, struct extent_map *em)
236 {
237 	struct extent_map *merge = NULL;
238 	struct rb_node *rb;
239 
240 	if (em->start != 0) {
241 		rb = rb_prev(&em->rb_node);
242 		if (rb)
243 			merge = rb_entry(rb, struct extent_map, rb_node);
244 		if (rb && mergable_maps(merge, em)) {
245 			em->start = merge->start;
246 			em->orig_start = merge->orig_start;
247 			em->len += merge->len;
248 			em->block_len += merge->block_len;
249 			em->block_start = merge->block_start;
250 			em->mod_len = (em->mod_len + em->mod_start) - merge->mod_start;
251 			em->mod_start = merge->mod_start;
252 			em->generation = max(em->generation, merge->generation);
253 
254 			rb_erase_cached(&merge->rb_node, &tree->map);
255 			RB_CLEAR_NODE(&merge->rb_node);
256 			free_extent_map(merge);
257 		}
258 	}
259 
260 	rb = rb_next(&em->rb_node);
261 	if (rb)
262 		merge = rb_entry(rb, struct extent_map, rb_node);
263 	if (rb && mergable_maps(em, merge)) {
264 		em->len += merge->len;
265 		em->block_len += merge->block_len;
266 		rb_erase_cached(&merge->rb_node, &tree->map);
267 		RB_CLEAR_NODE(&merge->rb_node);
268 		em->mod_len = (merge->mod_start + merge->mod_len) - em->mod_start;
269 		em->generation = max(em->generation, merge->generation);
270 		free_extent_map(merge);
271 	}
272 }
273 
274 /**
275  * unpin_extent_cache - unpin an extent from the cache
276  * @tree:	tree to unpin the extent in
277  * @start:	logical offset in the file
278  * @len:	length of the extent
279  * @gen:	generation that this extent has been modified in
280  *
281  * Called after an extent has been written to disk properly.  Set the generation
282  * to the generation that actually added the file item to the inode so we know
283  * we need to sync this extent when we call fsync().
284  */
285 int unpin_extent_cache(struct extent_map_tree *tree, u64 start, u64 len,
286 		       u64 gen)
287 {
288 	int ret = 0;
289 	struct extent_map *em;
290 	bool prealloc = false;
291 
292 	write_lock(&tree->lock);
293 	em = lookup_extent_mapping(tree, start, len);
294 
295 	WARN_ON(!em || em->start != start);
296 
297 	if (!em)
298 		goto out;
299 
300 	em->generation = gen;
301 	clear_bit(EXTENT_FLAG_PINNED, &em->flags);
302 	em->mod_start = em->start;
303 	em->mod_len = em->len;
304 
305 	if (test_bit(EXTENT_FLAG_FILLING, &em->flags)) {
306 		prealloc = true;
307 		clear_bit(EXTENT_FLAG_FILLING, &em->flags);
308 	}
309 
310 	try_merge_map(tree, em);
311 
312 	if (prealloc) {
313 		em->mod_start = em->start;
314 		em->mod_len = em->len;
315 	}
316 
317 	free_extent_map(em);
318 out:
319 	write_unlock(&tree->lock);
320 	return ret;
321 
322 }
323 
324 void clear_em_logging(struct extent_map_tree *tree, struct extent_map *em)
325 {
326 	clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
327 	if (extent_map_in_tree(em))
328 		try_merge_map(tree, em);
329 }
330 
331 static inline void setup_extent_mapping(struct extent_map_tree *tree,
332 					struct extent_map *em,
333 					int modified)
334 {
335 	refcount_inc(&em->refs);
336 	em->mod_start = em->start;
337 	em->mod_len = em->len;
338 
339 	if (modified)
340 		list_move(&em->list, &tree->modified_extents);
341 	else
342 		try_merge_map(tree, em);
343 }
344 
345 static void extent_map_device_set_bits(struct extent_map *em, unsigned bits)
346 {
347 	struct map_lookup *map = em->map_lookup;
348 	u64 stripe_size = em->orig_block_len;
349 	int i;
350 
351 	for (i = 0; i < map->num_stripes; i++) {
352 		struct btrfs_bio_stripe *stripe = &map->stripes[i];
353 		struct btrfs_device *device = stripe->dev;
354 
355 		set_extent_bits_nowait(&device->alloc_state, stripe->physical,
356 				 stripe->physical + stripe_size - 1, bits);
357 	}
358 }
359 
360 static void extent_map_device_clear_bits(struct extent_map *em, unsigned bits)
361 {
362 	struct map_lookup *map = em->map_lookup;
363 	u64 stripe_size = em->orig_block_len;
364 	int i;
365 
366 	for (i = 0; i < map->num_stripes; i++) {
367 		struct btrfs_bio_stripe *stripe = &map->stripes[i];
368 		struct btrfs_device *device = stripe->dev;
369 
370 		__clear_extent_bit(&device->alloc_state, stripe->physical,
371 				   stripe->physical + stripe_size - 1, bits,
372 				   0, 0, NULL, GFP_NOWAIT, NULL);
373 	}
374 }
375 
376 /**
377  * add_extent_mapping - add new extent map to the extent tree
378  * @tree:	tree to insert new map in
379  * @em:		map to insert
380  *
381  * Insert @em into @tree or perform a simple forward/backward merge with
382  * existing mappings.  The extent_map struct passed in will be inserted
383  * into the tree directly, with an additional reference taken, or a
384  * reference dropped if the merge attempt was successful.
385  */
386 int add_extent_mapping(struct extent_map_tree *tree,
387 		       struct extent_map *em, int modified)
388 {
389 	int ret = 0;
390 
391 	lockdep_assert_held_write(&tree->lock);
392 
393 	ret = tree_insert(&tree->map, em);
394 	if (ret)
395 		goto out;
396 
397 	setup_extent_mapping(tree, em, modified);
398 	if (test_bit(EXTENT_FLAG_FS_MAPPING, &em->flags)) {
399 		extent_map_device_set_bits(em, CHUNK_ALLOCATED);
400 		extent_map_device_clear_bits(em, CHUNK_TRIMMED);
401 	}
402 out:
403 	return ret;
404 }
405 
406 static struct extent_map *
407 __lookup_extent_mapping(struct extent_map_tree *tree,
408 			u64 start, u64 len, int strict)
409 {
410 	struct extent_map *em;
411 	struct rb_node *rb_node;
412 	struct rb_node *prev = NULL;
413 	struct rb_node *next = NULL;
414 	u64 end = range_end(start, len);
415 
416 	rb_node = __tree_search(&tree->map.rb_root, start, &prev, &next);
417 	if (!rb_node) {
418 		if (prev)
419 			rb_node = prev;
420 		else if (next)
421 			rb_node = next;
422 		else
423 			return NULL;
424 	}
425 
426 	em = rb_entry(rb_node, struct extent_map, rb_node);
427 
428 	if (strict && !(end > em->start && start < extent_map_end(em)))
429 		return NULL;
430 
431 	refcount_inc(&em->refs);
432 	return em;
433 }
434 
435 /**
436  * lookup_extent_mapping - lookup extent_map
437  * @tree:	tree to lookup in
438  * @start:	byte offset to start the search
439  * @len:	length of the lookup range
440  *
441  * Find and return the first extent_map struct in @tree that intersects the
442  * [start, len] range.  There may be additional objects in the tree that
443  * intersect, so check the object returned carefully to make sure that no
444  * additional lookups are needed.
445  */
446 struct extent_map *lookup_extent_mapping(struct extent_map_tree *tree,
447 					 u64 start, u64 len)
448 {
449 	return __lookup_extent_mapping(tree, start, len, 1);
450 }
451 
452 /**
453  * search_extent_mapping - find a nearby extent map
454  * @tree:	tree to lookup in
455  * @start:	byte offset to start the search
456  * @len:	length of the lookup range
457  *
458  * Find and return the first extent_map struct in @tree that intersects the
459  * [start, len] range.
460  *
461  * If one can't be found, any nearby extent may be returned
462  */
463 struct extent_map *search_extent_mapping(struct extent_map_tree *tree,
464 					 u64 start, u64 len)
465 {
466 	return __lookup_extent_mapping(tree, start, len, 0);
467 }
468 
469 /**
470  * remove_extent_mapping - removes an extent_map from the extent tree
471  * @tree:	extent tree to remove from
472  * @em:		extent map being removed
473  *
474  * Removes @em from @tree.  No reference counts are dropped, and no checks
475  * are done to see if the range is in use
476  */
477 void remove_extent_mapping(struct extent_map_tree *tree, struct extent_map *em)
478 {
479 	WARN_ON(test_bit(EXTENT_FLAG_PINNED, &em->flags));
480 	rb_erase_cached(&em->rb_node, &tree->map);
481 	if (!test_bit(EXTENT_FLAG_LOGGING, &em->flags))
482 		list_del_init(&em->list);
483 	if (test_bit(EXTENT_FLAG_FS_MAPPING, &em->flags))
484 		extent_map_device_clear_bits(em, CHUNK_ALLOCATED);
485 	RB_CLEAR_NODE(&em->rb_node);
486 }
487 
488 void replace_extent_mapping(struct extent_map_tree *tree,
489 			    struct extent_map *cur,
490 			    struct extent_map *new,
491 			    int modified)
492 {
493 	WARN_ON(test_bit(EXTENT_FLAG_PINNED, &cur->flags));
494 	ASSERT(extent_map_in_tree(cur));
495 	if (!test_bit(EXTENT_FLAG_LOGGING, &cur->flags))
496 		list_del_init(&cur->list);
497 	rb_replace_node_cached(&cur->rb_node, &new->rb_node, &tree->map);
498 	RB_CLEAR_NODE(&cur->rb_node);
499 
500 	setup_extent_mapping(tree, new, modified);
501 }
502 
503 static struct extent_map *next_extent_map(struct extent_map *em)
504 {
505 	struct rb_node *next;
506 
507 	next = rb_next(&em->rb_node);
508 	if (!next)
509 		return NULL;
510 	return container_of(next, struct extent_map, rb_node);
511 }
512 
513 static struct extent_map *prev_extent_map(struct extent_map *em)
514 {
515 	struct rb_node *prev;
516 
517 	prev = rb_prev(&em->rb_node);
518 	if (!prev)
519 		return NULL;
520 	return container_of(prev, struct extent_map, rb_node);
521 }
522 
523 /*
524  * Helper for btrfs_get_extent.  Given an existing extent in the tree,
525  * the existing extent is the nearest extent to map_start,
526  * and an extent that you want to insert, deal with overlap and insert
527  * the best fitted new extent into the tree.
528  */
529 static noinline int merge_extent_mapping(struct extent_map_tree *em_tree,
530 					 struct extent_map *existing,
531 					 struct extent_map *em,
532 					 u64 map_start)
533 {
534 	struct extent_map *prev;
535 	struct extent_map *next;
536 	u64 start;
537 	u64 end;
538 	u64 start_diff;
539 
540 	BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
541 
542 	if (existing->start > map_start) {
543 		next = existing;
544 		prev = prev_extent_map(next);
545 	} else {
546 		prev = existing;
547 		next = next_extent_map(prev);
548 	}
549 
550 	start = prev ? extent_map_end(prev) : em->start;
551 	start = max_t(u64, start, em->start);
552 	end = next ? next->start : extent_map_end(em);
553 	end = min_t(u64, end, extent_map_end(em));
554 	start_diff = start - em->start;
555 	em->start = start;
556 	em->len = end - start;
557 	if (em->block_start < EXTENT_MAP_LAST_BYTE &&
558 	    !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
559 		em->block_start += start_diff;
560 		em->block_len = em->len;
561 	}
562 	return add_extent_mapping(em_tree, em, 0);
563 }
564 
565 /**
566  * btrfs_add_extent_mapping - add extent mapping into em_tree
567  * @fs_info - used for tracepoint
568  * @em_tree - the extent tree into which we want to insert the extent mapping
569  * @em_in   - extent we are inserting
570  * @start   - start of the logical range btrfs_get_extent() is requesting
571  * @len     - length of the logical range btrfs_get_extent() is requesting
572  *
573  * Note that @em_in's range may be different from [start, start+len),
574  * but they must be overlapped.
575  *
576  * Insert @em_in into @em_tree. In case there is an overlapping range, handle
577  * the -EEXIST by either:
578  * a) Returning the existing extent in @em_in if @start is within the
579  *    existing em.
580  * b) Merge the existing extent with @em_in passed in.
581  *
582  * Return 0 on success, otherwise -EEXIST.
583  *
584  */
585 int btrfs_add_extent_mapping(struct btrfs_fs_info *fs_info,
586 			     struct extent_map_tree *em_tree,
587 			     struct extent_map **em_in, u64 start, u64 len)
588 {
589 	int ret;
590 	struct extent_map *em = *em_in;
591 
592 	ret = add_extent_mapping(em_tree, em, 0);
593 	/* it is possible that someone inserted the extent into the tree
594 	 * while we had the lock dropped.  It is also possible that
595 	 * an overlapping map exists in the tree
596 	 */
597 	if (ret == -EEXIST) {
598 		struct extent_map *existing;
599 
600 		ret = 0;
601 
602 		existing = search_extent_mapping(em_tree, start, len);
603 
604 		trace_btrfs_handle_em_exist(fs_info, existing, em, start, len);
605 
606 		/*
607 		 * existing will always be non-NULL, since there must be
608 		 * extent causing the -EEXIST.
609 		 */
610 		if (start >= existing->start &&
611 		    start < extent_map_end(existing)) {
612 			free_extent_map(em);
613 			*em_in = existing;
614 			ret = 0;
615 		} else {
616 			u64 orig_start = em->start;
617 			u64 orig_len = em->len;
618 
619 			/*
620 			 * The existing extent map is the one nearest to
621 			 * the [start, start + len) range which overlaps
622 			 */
623 			ret = merge_extent_mapping(em_tree, existing,
624 						   em, start);
625 			if (ret) {
626 				free_extent_map(em);
627 				*em_in = NULL;
628 				WARN_ONCE(ret,
629 "unexpected error %d: merge existing(start %llu len %llu) with em(start %llu len %llu)\n",
630 					  ret, existing->start, existing->len,
631 					  orig_start, orig_len);
632 			}
633 			free_extent_map(existing);
634 		}
635 	}
636 
637 	ASSERT(ret == 0 || ret == -EEXIST);
638 	return ret;
639 }
640