xref: /openbmc/linux/fs/btrfs/extent_map.c (revision e85de967)
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 "messages.h"
7 #include "ctree.h"
8 #include "volumes.h"
9 #include "extent_map.h"
10 #include "compression.h"
11 #include "btrfs_inode.h"
12 
13 
14 static struct kmem_cache *extent_map_cache;
15 
16 int __init extent_map_init(void)
17 {
18 	extent_map_cache = kmem_cache_create("btrfs_extent_map",
19 			sizeof(struct extent_map), 0,
20 			SLAB_MEM_SPREAD, NULL);
21 	if (!extent_map_cache)
22 		return -ENOMEM;
23 	return 0;
24 }
25 
26 void __cold extent_map_exit(void)
27 {
28 	kmem_cache_destroy(extent_map_cache);
29 }
30 
31 /*
32  * Initialize the extent tree @tree.  Should be called for each new inode or
33  * other user of the extent_map interface.
34  */
35 void extent_map_tree_init(struct extent_map_tree *tree)
36 {
37 	tree->map = RB_ROOT_CACHED;
38 	INIT_LIST_HEAD(&tree->modified_extents);
39 	rwlock_init(&tree->lock);
40 }
41 
42 /*
43  * Allocate a new extent_map structure.  The new structure is returned with a
44  * reference count of one and needs to be freed using free_extent_map()
45  */
46 struct extent_map *alloc_extent_map(void)
47 {
48 	struct extent_map *em;
49 	em = kmem_cache_zalloc(extent_map_cache, GFP_NOFS);
50 	if (!em)
51 		return NULL;
52 	RB_CLEAR_NODE(&em->rb_node);
53 	em->compress_type = BTRFS_COMPRESS_NONE;
54 	refcount_set(&em->refs, 1);
55 	INIT_LIST_HEAD(&em->list);
56 	return em;
57 }
58 
59 /*
60  * Drop the reference out on @em by one and free the structure if the reference
61  * count hits zero.
62  */
63 void free_extent_map(struct extent_map *em)
64 {
65 	if (!em)
66 		return;
67 	if (refcount_dec_and_test(&em->refs)) {
68 		WARN_ON(extent_map_in_tree(em));
69 		WARN_ON(!list_empty(&em->list));
70 		if (test_bit(EXTENT_FLAG_FS_MAPPING, &em->flags))
71 			kfree(em->map_lookup);
72 		kmem_cache_free(extent_map_cache, em);
73 	}
74 }
75 
76 /* Do the math around the end of an extent, handling wrapping. */
77 static u64 range_end(u64 start, u64 len)
78 {
79 	if (start + len < start)
80 		return (u64)-1;
81 	return start + len;
82 }
83 
84 static int tree_insert(struct rb_root_cached *root, struct extent_map *em)
85 {
86 	struct rb_node **p = &root->rb_root.rb_node;
87 	struct rb_node *parent = NULL;
88 	struct extent_map *entry = NULL;
89 	struct rb_node *orig_parent = NULL;
90 	u64 end = range_end(em->start, em->len);
91 	bool leftmost = true;
92 
93 	while (*p) {
94 		parent = *p;
95 		entry = rb_entry(parent, struct extent_map, rb_node);
96 
97 		if (em->start < entry->start) {
98 			p = &(*p)->rb_left;
99 		} else if (em->start >= extent_map_end(entry)) {
100 			p = &(*p)->rb_right;
101 			leftmost = false;
102 		} else {
103 			return -EEXIST;
104 		}
105 	}
106 
107 	orig_parent = parent;
108 	while (parent && em->start >= extent_map_end(entry)) {
109 		parent = rb_next(parent);
110 		entry = rb_entry(parent, struct extent_map, rb_node);
111 	}
112 	if (parent)
113 		if (end > entry->start && em->start < extent_map_end(entry))
114 			return -EEXIST;
115 
116 	parent = orig_parent;
117 	entry = rb_entry(parent, struct extent_map, rb_node);
118 	while (parent && em->start < entry->start) {
119 		parent = rb_prev(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 	rb_link_node(&em->rb_node, orig_parent, p);
127 	rb_insert_color_cached(&em->rb_node, root, leftmost);
128 	return 0;
129 }
130 
131 /*
132  * Search through the tree for an extent_map with a given offset.  If it can't
133  * be found, try to find some neighboring extents
134  */
135 static struct rb_node *__tree_search(struct rb_root *root, u64 offset,
136 				     struct rb_node **prev_or_next_ret)
137 {
138 	struct rb_node *n = root->rb_node;
139 	struct rb_node *prev = NULL;
140 	struct rb_node *orig_prev = NULL;
141 	struct extent_map *entry;
142 	struct extent_map *prev_entry = NULL;
143 
144 	ASSERT(prev_or_next_ret);
145 
146 	while (n) {
147 		entry = rb_entry(n, struct extent_map, rb_node);
148 		prev = n;
149 		prev_entry = entry;
150 
151 		if (offset < entry->start)
152 			n = n->rb_left;
153 		else if (offset >= extent_map_end(entry))
154 			n = n->rb_right;
155 		else
156 			return n;
157 	}
158 
159 	orig_prev = prev;
160 	while (prev && offset >= extent_map_end(prev_entry)) {
161 		prev = rb_next(prev);
162 		prev_entry = rb_entry(prev, struct extent_map, rb_node);
163 	}
164 
165 	/*
166 	 * Previous extent map found, return as in this case the caller does not
167 	 * care about the next one.
168 	 */
169 	if (prev) {
170 		*prev_or_next_ret = prev;
171 		return NULL;
172 	}
173 
174 	prev = orig_prev;
175 	prev_entry = rb_entry(prev, struct extent_map, rb_node);
176 	while (prev && offset < prev_entry->start) {
177 		prev = rb_prev(prev);
178 		prev_entry = rb_entry(prev, struct extent_map, rb_node);
179 	}
180 	*prev_or_next_ret = prev;
181 
182 	return NULL;
183 }
184 
185 /* Check to see if two extent_map structs are adjacent and safe to merge. */
186 static int mergable_maps(struct extent_map *prev, struct extent_map *next)
187 {
188 	if (test_bit(EXTENT_FLAG_PINNED, &prev->flags))
189 		return 0;
190 
191 	/*
192 	 * don't merge compressed extents, we need to know their
193 	 * actual size
194 	 */
195 	if (test_bit(EXTENT_FLAG_COMPRESSED, &prev->flags))
196 		return 0;
197 
198 	if (test_bit(EXTENT_FLAG_LOGGING, &prev->flags) ||
199 	    test_bit(EXTENT_FLAG_LOGGING, &next->flags))
200 		return 0;
201 
202 	/*
203 	 * We don't want to merge stuff that hasn't been written to the log yet
204 	 * since it may not reflect exactly what is on disk, and that would be
205 	 * bad.
206 	 */
207 	if (!list_empty(&prev->list) || !list_empty(&next->list))
208 		return 0;
209 
210 	ASSERT(next->block_start != EXTENT_MAP_DELALLOC &&
211 	       prev->block_start != EXTENT_MAP_DELALLOC);
212 
213 	if (prev->map_lookup || next->map_lookup)
214 		ASSERT(test_bit(EXTENT_FLAG_FS_MAPPING, &prev->flags) &&
215 		       test_bit(EXTENT_FLAG_FS_MAPPING, &next->flags));
216 
217 	if (extent_map_end(prev) == next->start &&
218 	    prev->flags == next->flags &&
219 	    prev->map_lookup == next->map_lookup &&
220 	    ((next->block_start == EXTENT_MAP_HOLE &&
221 	      prev->block_start == EXTENT_MAP_HOLE) ||
222 	     (next->block_start == EXTENT_MAP_INLINE &&
223 	      prev->block_start == EXTENT_MAP_INLINE) ||
224 	     (next->block_start < EXTENT_MAP_LAST_BYTE - 1 &&
225 	      next->block_start == extent_map_block_end(prev)))) {
226 		return 1;
227 	}
228 	return 0;
229 }
230 
231 static void try_merge_map(struct extent_map_tree *tree, struct extent_map *em)
232 {
233 	struct extent_map *merge = NULL;
234 	struct rb_node *rb;
235 
236 	/*
237 	 * We can't modify an extent map that is in the tree and that is being
238 	 * used by another task, as it can cause that other task to see it in
239 	 * inconsistent state during the merging. We always have 1 reference for
240 	 * the tree and 1 for this task (which is unpinning the extent map or
241 	 * clearing the logging flag), so anything > 2 means it's being used by
242 	 * other tasks too.
243 	 */
244 	if (refcount_read(&em->refs) > 2)
245 		return;
246 
247 	if (em->start != 0) {
248 		rb = rb_prev(&em->rb_node);
249 		if (rb)
250 			merge = rb_entry(rb, struct extent_map, rb_node);
251 		if (rb && mergable_maps(merge, em)) {
252 			em->start = merge->start;
253 			em->orig_start = merge->orig_start;
254 			em->len += merge->len;
255 			em->block_len += merge->block_len;
256 			em->block_start = merge->block_start;
257 			em->mod_len = (em->mod_len + em->mod_start) - merge->mod_start;
258 			em->mod_start = merge->mod_start;
259 			em->generation = max(em->generation, merge->generation);
260 			set_bit(EXTENT_FLAG_MERGED, &em->flags);
261 
262 			rb_erase_cached(&merge->rb_node, &tree->map);
263 			RB_CLEAR_NODE(&merge->rb_node);
264 			free_extent_map(merge);
265 		}
266 	}
267 
268 	rb = rb_next(&em->rb_node);
269 	if (rb)
270 		merge = rb_entry(rb, struct extent_map, rb_node);
271 	if (rb && mergable_maps(em, merge)) {
272 		em->len += merge->len;
273 		em->block_len += merge->block_len;
274 		rb_erase_cached(&merge->rb_node, &tree->map);
275 		RB_CLEAR_NODE(&merge->rb_node);
276 		em->mod_len = (merge->mod_start + merge->mod_len) - em->mod_start;
277 		em->generation = max(em->generation, merge->generation);
278 		set_bit(EXTENT_FLAG_MERGED, &em->flags);
279 		free_extent_map(merge);
280 	}
281 }
282 
283 /*
284  * Unpin an extent from the cache.
285  *
286  * @tree:	tree to unpin the extent in
287  * @start:	logical offset in the file
288  * @len:	length of the extent
289  * @gen:	generation that this extent has been modified in
290  *
291  * Called after an extent has been written to disk properly.  Set the generation
292  * to the generation that actually added the file item to the inode so we know
293  * we need to sync this extent when we call fsync().
294  */
295 int unpin_extent_cache(struct extent_map_tree *tree, u64 start, u64 len,
296 		       u64 gen)
297 {
298 	int ret = 0;
299 	struct extent_map *em;
300 	bool prealloc = false;
301 
302 	write_lock(&tree->lock);
303 	em = lookup_extent_mapping(tree, start, len);
304 
305 	WARN_ON(!em || em->start != start);
306 
307 	if (!em)
308 		goto out;
309 
310 	em->generation = gen;
311 	clear_bit(EXTENT_FLAG_PINNED, &em->flags);
312 	em->mod_start = em->start;
313 	em->mod_len = em->len;
314 
315 	if (test_bit(EXTENT_FLAG_FILLING, &em->flags)) {
316 		prealloc = true;
317 		clear_bit(EXTENT_FLAG_FILLING, &em->flags);
318 	}
319 
320 	try_merge_map(tree, em);
321 
322 	if (prealloc) {
323 		em->mod_start = em->start;
324 		em->mod_len = em->len;
325 	}
326 
327 	free_extent_map(em);
328 out:
329 	write_unlock(&tree->lock);
330 	return ret;
331 
332 }
333 
334 void clear_em_logging(struct extent_map_tree *tree, struct extent_map *em)
335 {
336 	lockdep_assert_held_write(&tree->lock);
337 
338 	clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
339 	if (extent_map_in_tree(em))
340 		try_merge_map(tree, em);
341 }
342 
343 static inline void setup_extent_mapping(struct extent_map_tree *tree,
344 					struct extent_map *em,
345 					int modified)
346 {
347 	refcount_inc(&em->refs);
348 	em->mod_start = em->start;
349 	em->mod_len = em->len;
350 
351 	if (modified)
352 		list_move(&em->list, &tree->modified_extents);
353 	else
354 		try_merge_map(tree, em);
355 }
356 
357 static void extent_map_device_set_bits(struct extent_map *em, unsigned bits)
358 {
359 	struct map_lookup *map = em->map_lookup;
360 	u64 stripe_size = em->orig_block_len;
361 	int i;
362 
363 	for (i = 0; i < map->num_stripes; i++) {
364 		struct btrfs_io_stripe *stripe = &map->stripes[i];
365 		struct btrfs_device *device = stripe->dev;
366 
367 		set_extent_bit(&device->alloc_state, stripe->physical,
368 			       stripe->physical + stripe_size - 1, bits, NULL,
369 			       GFP_NOWAIT);
370 	}
371 }
372 
373 static void extent_map_device_clear_bits(struct extent_map *em, unsigned bits)
374 {
375 	struct map_lookup *map = em->map_lookup;
376 	u64 stripe_size = em->orig_block_len;
377 	int i;
378 
379 	for (i = 0; i < map->num_stripes; i++) {
380 		struct btrfs_io_stripe *stripe = &map->stripes[i];
381 		struct btrfs_device *device = stripe->dev;
382 
383 		__clear_extent_bit(&device->alloc_state, stripe->physical,
384 				   stripe->physical + stripe_size - 1, bits,
385 				   NULL, GFP_NOWAIT, NULL);
386 	}
387 }
388 
389 /*
390  * Add new extent map to the extent tree
391  *
392  * @tree:	tree to insert new map in
393  * @em:		map to insert
394  * @modified:	indicate whether the given @em should be added to the
395  *	        modified list, which indicates the extent needs to be logged
396  *
397  * Insert @em into @tree or perform a simple forward/backward merge with
398  * existing mappings.  The extent_map struct passed in will be inserted
399  * into the tree directly, with an additional reference taken, or a
400  * reference dropped if the merge attempt was successful.
401  */
402 int add_extent_mapping(struct extent_map_tree *tree,
403 		       struct extent_map *em, int modified)
404 {
405 	int ret = 0;
406 
407 	lockdep_assert_held_write(&tree->lock);
408 
409 	ret = tree_insert(&tree->map, em);
410 	if (ret)
411 		goto out;
412 
413 	setup_extent_mapping(tree, em, modified);
414 	if (test_bit(EXTENT_FLAG_FS_MAPPING, &em->flags)) {
415 		extent_map_device_set_bits(em, CHUNK_ALLOCATED);
416 		extent_map_device_clear_bits(em, CHUNK_TRIMMED);
417 	}
418 out:
419 	return ret;
420 }
421 
422 static struct extent_map *
423 __lookup_extent_mapping(struct extent_map_tree *tree,
424 			u64 start, u64 len, int strict)
425 {
426 	struct extent_map *em;
427 	struct rb_node *rb_node;
428 	struct rb_node *prev_or_next = NULL;
429 	u64 end = range_end(start, len);
430 
431 	rb_node = __tree_search(&tree->map.rb_root, start, &prev_or_next);
432 	if (!rb_node) {
433 		if (prev_or_next)
434 			rb_node = prev_or_next;
435 		else
436 			return NULL;
437 	}
438 
439 	em = rb_entry(rb_node, struct extent_map, rb_node);
440 
441 	if (strict && !(end > em->start && start < extent_map_end(em)))
442 		return NULL;
443 
444 	refcount_inc(&em->refs);
445 	return em;
446 }
447 
448 /*
449  * Lookup extent_map that intersects @start + @len range.
450  *
451  * @tree:	tree to lookup in
452  * @start:	byte offset to start the search
453  * @len:	length of the lookup range
454  *
455  * Find and return the first extent_map struct in @tree that intersects the
456  * [start, len] range.  There may be additional objects in the tree that
457  * intersect, so check the object returned carefully to make sure that no
458  * additional lookups are needed.
459  */
460 struct extent_map *lookup_extent_mapping(struct extent_map_tree *tree,
461 					 u64 start, u64 len)
462 {
463 	return __lookup_extent_mapping(tree, start, len, 1);
464 }
465 
466 /*
467  * Find a nearby extent map intersecting @start + @len (not an exact search).
468  *
469  * @tree:	tree to lookup in
470  * @start:	byte offset to start the search
471  * @len:	length of the lookup range
472  *
473  * Find and return the first extent_map struct in @tree that intersects the
474  * [start, len] range.
475  *
476  * If one can't be found, any nearby extent may be returned
477  */
478 struct extent_map *search_extent_mapping(struct extent_map_tree *tree,
479 					 u64 start, u64 len)
480 {
481 	return __lookup_extent_mapping(tree, start, len, 0);
482 }
483 
484 /*
485  * Remove an extent_map from the extent tree.
486  *
487  * @tree:	extent tree to remove from
488  * @em:		extent map being removed
489  *
490  * Remove @em from @tree.  No reference counts are dropped, and no checks
491  * are done to see if the range is in use.
492  */
493 void remove_extent_mapping(struct extent_map_tree *tree, struct extent_map *em)
494 {
495 	lockdep_assert_held_write(&tree->lock);
496 
497 	WARN_ON(test_bit(EXTENT_FLAG_PINNED, &em->flags));
498 	rb_erase_cached(&em->rb_node, &tree->map);
499 	if (!test_bit(EXTENT_FLAG_LOGGING, &em->flags))
500 		list_del_init(&em->list);
501 	if (test_bit(EXTENT_FLAG_FS_MAPPING, &em->flags))
502 		extent_map_device_clear_bits(em, CHUNK_ALLOCATED);
503 	RB_CLEAR_NODE(&em->rb_node);
504 }
505 
506 void replace_extent_mapping(struct extent_map_tree *tree,
507 			    struct extent_map *cur,
508 			    struct extent_map *new,
509 			    int modified)
510 {
511 	lockdep_assert_held_write(&tree->lock);
512 
513 	WARN_ON(test_bit(EXTENT_FLAG_PINNED, &cur->flags));
514 	ASSERT(extent_map_in_tree(cur));
515 	if (!test_bit(EXTENT_FLAG_LOGGING, &cur->flags))
516 		list_del_init(&cur->list);
517 	rb_replace_node_cached(&cur->rb_node, &new->rb_node, &tree->map);
518 	RB_CLEAR_NODE(&cur->rb_node);
519 
520 	setup_extent_mapping(tree, new, modified);
521 }
522 
523 static struct extent_map *next_extent_map(const struct extent_map *em)
524 {
525 	struct rb_node *next;
526 
527 	next = rb_next(&em->rb_node);
528 	if (!next)
529 		return NULL;
530 	return container_of(next, struct extent_map, rb_node);
531 }
532 
533 static struct extent_map *prev_extent_map(struct extent_map *em)
534 {
535 	struct rb_node *prev;
536 
537 	prev = rb_prev(&em->rb_node);
538 	if (!prev)
539 		return NULL;
540 	return container_of(prev, struct extent_map, rb_node);
541 }
542 
543 /*
544  * Helper for btrfs_get_extent.  Given an existing extent in the tree,
545  * the existing extent is the nearest extent to map_start,
546  * and an extent that you want to insert, deal with overlap and insert
547  * the best fitted new extent into the tree.
548  */
549 static noinline int merge_extent_mapping(struct extent_map_tree *em_tree,
550 					 struct extent_map *existing,
551 					 struct extent_map *em,
552 					 u64 map_start)
553 {
554 	struct extent_map *prev;
555 	struct extent_map *next;
556 	u64 start;
557 	u64 end;
558 	u64 start_diff;
559 
560 	BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
561 
562 	if (existing->start > map_start) {
563 		next = existing;
564 		prev = prev_extent_map(next);
565 	} else {
566 		prev = existing;
567 		next = next_extent_map(prev);
568 	}
569 
570 	start = prev ? extent_map_end(prev) : em->start;
571 	start = max_t(u64, start, em->start);
572 	end = next ? next->start : extent_map_end(em);
573 	end = min_t(u64, end, extent_map_end(em));
574 	start_diff = start - em->start;
575 	em->start = start;
576 	em->len = end - start;
577 	if (em->block_start < EXTENT_MAP_LAST_BYTE &&
578 	    !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
579 		em->block_start += start_diff;
580 		em->block_len = em->len;
581 	}
582 	return add_extent_mapping(em_tree, em, 0);
583 }
584 
585 /*
586  * Add extent mapping into em_tree.
587  *
588  * @fs_info:  the filesystem
589  * @em_tree:  extent tree into which we want to insert the extent mapping
590  * @em_in:    extent we are inserting
591  * @start:    start of the logical range btrfs_get_extent() is requesting
592  * @len:      length of the logical range btrfs_get_extent() is requesting
593  *
594  * Note that @em_in's range may be different from [start, start+len),
595  * but they must be overlapped.
596  *
597  * Insert @em_in into @em_tree. In case there is an overlapping range, handle
598  * the -EEXIST by either:
599  * a) Returning the existing extent in @em_in if @start is within the
600  *    existing em.
601  * b) Merge the existing extent with @em_in passed in.
602  *
603  * Return 0 on success, otherwise -EEXIST.
604  *
605  */
606 int btrfs_add_extent_mapping(struct btrfs_fs_info *fs_info,
607 			     struct extent_map_tree *em_tree,
608 			     struct extent_map **em_in, u64 start, u64 len)
609 {
610 	int ret;
611 	struct extent_map *em = *em_in;
612 
613 	/*
614 	 * Tree-checker should have rejected any inline extent with non-zero
615 	 * file offset. Here just do a sanity check.
616 	 */
617 	if (em->block_start == EXTENT_MAP_INLINE)
618 		ASSERT(em->start == 0);
619 
620 	ret = add_extent_mapping(em_tree, em, 0);
621 	/* it is possible that someone inserted the extent into the tree
622 	 * while we had the lock dropped.  It is also possible that
623 	 * an overlapping map exists in the tree
624 	 */
625 	if (ret == -EEXIST) {
626 		struct extent_map *existing;
627 
628 		ret = 0;
629 
630 		existing = search_extent_mapping(em_tree, start, len);
631 
632 		trace_btrfs_handle_em_exist(fs_info, existing, em, start, len);
633 
634 		/*
635 		 * existing will always be non-NULL, since there must be
636 		 * extent causing the -EEXIST.
637 		 */
638 		if (start >= existing->start &&
639 		    start < extent_map_end(existing)) {
640 			free_extent_map(em);
641 			*em_in = existing;
642 			ret = 0;
643 		} else {
644 			u64 orig_start = em->start;
645 			u64 orig_len = em->len;
646 
647 			/*
648 			 * The existing extent map is the one nearest to
649 			 * the [start, start + len) range which overlaps
650 			 */
651 			ret = merge_extent_mapping(em_tree, existing,
652 						   em, start);
653 			if (ret) {
654 				free_extent_map(em);
655 				*em_in = NULL;
656 				WARN_ONCE(ret,
657 "unexpected error %d: merge existing(start %llu len %llu) with em(start %llu len %llu)\n",
658 					  ret, existing->start, existing->len,
659 					  orig_start, orig_len);
660 			}
661 			free_extent_map(existing);
662 		}
663 	}
664 
665 	ASSERT(ret == 0 || ret == -EEXIST);
666 	return ret;
667 }
668 
669 /*
670  * Drop all extent maps from a tree in the fastest possible way, rescheduling
671  * if needed. This avoids searching the tree, from the root down to the first
672  * extent map, before each deletion.
673  */
674 static void drop_all_extent_maps_fast(struct extent_map_tree *tree)
675 {
676 	write_lock(&tree->lock);
677 	while (!RB_EMPTY_ROOT(&tree->map.rb_root)) {
678 		struct extent_map *em;
679 		struct rb_node *node;
680 
681 		node = rb_first_cached(&tree->map);
682 		em = rb_entry(node, struct extent_map, rb_node);
683 		clear_bit(EXTENT_FLAG_PINNED, &em->flags);
684 		clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
685 		remove_extent_mapping(tree, em);
686 		free_extent_map(em);
687 		cond_resched_rwlock_write(&tree->lock);
688 	}
689 	write_unlock(&tree->lock);
690 }
691 
692 /*
693  * Drop all extent maps in a given range.
694  *
695  * @inode:       The target inode.
696  * @start:       Start offset of the range.
697  * @end:         End offset of the range (inclusive value).
698  * @skip_pinned: Indicate if pinned extent maps should be ignored or not.
699  *
700  * This drops all the extent maps that intersect the given range [@start, @end].
701  * Extent maps that partially overlap the range and extend behind or beyond it,
702  * are split.
703  * The caller should have locked an appropriate file range in the inode's io
704  * tree before calling this function.
705  */
706 void btrfs_drop_extent_map_range(struct btrfs_inode *inode, u64 start, u64 end,
707 				 bool skip_pinned)
708 {
709 	struct extent_map *split;
710 	struct extent_map *split2;
711 	struct extent_map *em;
712 	struct extent_map_tree *em_tree = &inode->extent_tree;
713 	u64 len = end - start + 1;
714 
715 	WARN_ON(end < start);
716 	if (end == (u64)-1) {
717 		if (start == 0 && !skip_pinned) {
718 			drop_all_extent_maps_fast(em_tree);
719 			return;
720 		}
721 		len = (u64)-1;
722 	} else {
723 		/* Make end offset exclusive for use in the loop below. */
724 		end++;
725 	}
726 
727 	/*
728 	 * It's ok if we fail to allocate the extent maps, see the comment near
729 	 * the bottom of the loop below. We only need two spare extent maps in
730 	 * the worst case, where the first extent map that intersects our range
731 	 * starts before the range and the last extent map that intersects our
732 	 * range ends after our range (and they might be the same extent map),
733 	 * because we need to split those two extent maps at the boundaries.
734 	 */
735 	split = alloc_extent_map();
736 	split2 = alloc_extent_map();
737 
738 	write_lock(&em_tree->lock);
739 	em = lookup_extent_mapping(em_tree, start, len);
740 
741 	while (em) {
742 		/* extent_map_end() returns exclusive value (last byte + 1). */
743 		const u64 em_end = extent_map_end(em);
744 		struct extent_map *next_em = NULL;
745 		u64 gen;
746 		unsigned long flags;
747 		bool modified;
748 		bool compressed;
749 
750 		if (em_end < end) {
751 			next_em = next_extent_map(em);
752 			if (next_em) {
753 				if (next_em->start < end)
754 					refcount_inc(&next_em->refs);
755 				else
756 					next_em = NULL;
757 			}
758 		}
759 
760 		if (skip_pinned && test_bit(EXTENT_FLAG_PINNED, &em->flags)) {
761 			start = em_end;
762 			if (end != (u64)-1)
763 				len = start + len - em_end;
764 			goto next;
765 		}
766 
767 		flags = em->flags;
768 		clear_bit(EXTENT_FLAG_PINNED, &em->flags);
769 		/*
770 		 * In case we split the extent map, we want to preserve the
771 		 * EXTENT_FLAG_LOGGING flag on our extent map, but we don't want
772 		 * it on the new extent maps.
773 		 */
774 		clear_bit(EXTENT_FLAG_LOGGING, &flags);
775 		modified = !list_empty(&em->list);
776 
777 		/*
778 		 * The extent map does not cross our target range, so no need to
779 		 * split it, we can remove it directly.
780 		 */
781 		if (em->start >= start && em_end <= end)
782 			goto remove_em;
783 
784 		gen = em->generation;
785 		compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
786 
787 		if (em->start < start) {
788 			if (!split) {
789 				split = split2;
790 				split2 = NULL;
791 				if (!split)
792 					goto remove_em;
793 			}
794 			split->start = em->start;
795 			split->len = start - em->start;
796 
797 			if (em->block_start < EXTENT_MAP_LAST_BYTE) {
798 				split->orig_start = em->orig_start;
799 				split->block_start = em->block_start;
800 
801 				if (compressed)
802 					split->block_len = em->block_len;
803 				else
804 					split->block_len = split->len;
805 				split->orig_block_len = max(split->block_len,
806 						em->orig_block_len);
807 				split->ram_bytes = em->ram_bytes;
808 			} else {
809 				split->orig_start = split->start;
810 				split->block_len = 0;
811 				split->block_start = em->block_start;
812 				split->orig_block_len = 0;
813 				split->ram_bytes = split->len;
814 			}
815 
816 			split->generation = gen;
817 			split->flags = flags;
818 			split->compress_type = em->compress_type;
819 			replace_extent_mapping(em_tree, em, split, modified);
820 			free_extent_map(split);
821 			split = split2;
822 			split2 = NULL;
823 		}
824 		if (em_end > end) {
825 			if (!split) {
826 				split = split2;
827 				split2 = NULL;
828 				if (!split)
829 					goto remove_em;
830 			}
831 			split->start = start + len;
832 			split->len = em_end - (start + len);
833 			split->block_start = em->block_start;
834 			split->flags = flags;
835 			split->compress_type = em->compress_type;
836 			split->generation = gen;
837 
838 			if (em->block_start < EXTENT_MAP_LAST_BYTE) {
839 				split->orig_block_len = max(em->block_len,
840 						    em->orig_block_len);
841 
842 				split->ram_bytes = em->ram_bytes;
843 				if (compressed) {
844 					split->block_len = em->block_len;
845 					split->orig_start = em->orig_start;
846 				} else {
847 					const u64 diff = start + len - em->start;
848 
849 					split->block_len = split->len;
850 					split->block_start += diff;
851 					split->orig_start = em->orig_start;
852 				}
853 			} else {
854 				split->ram_bytes = split->len;
855 				split->orig_start = split->start;
856 				split->block_len = 0;
857 				split->orig_block_len = 0;
858 			}
859 
860 			if (extent_map_in_tree(em)) {
861 				replace_extent_mapping(em_tree, em, split,
862 						       modified);
863 			} else {
864 				int ret;
865 
866 				ret = add_extent_mapping(em_tree, split,
867 							 modified);
868 				/* Logic error, shouldn't happen. */
869 				ASSERT(ret == 0);
870 				if (WARN_ON(ret != 0) && modified)
871 					btrfs_set_inode_full_sync(inode);
872 			}
873 			free_extent_map(split);
874 			split = NULL;
875 		}
876 remove_em:
877 		if (extent_map_in_tree(em)) {
878 			/*
879 			 * If the extent map is still in the tree it means that
880 			 * either of the following is true:
881 			 *
882 			 * 1) It fits entirely in our range (doesn't end beyond
883 			 *    it or starts before it);
884 			 *
885 			 * 2) It starts before our range and/or ends after our
886 			 *    range, and we were not able to allocate the extent
887 			 *    maps for split operations, @split and @split2.
888 			 *
889 			 * If we are at case 2) then we just remove the entire
890 			 * extent map - this is fine since if anyone needs it to
891 			 * access the subranges outside our range, will just
892 			 * load it again from the subvolume tree's file extent
893 			 * item. However if the extent map was in the list of
894 			 * modified extents, then we must mark the inode for a
895 			 * full fsync, otherwise a fast fsync will miss this
896 			 * extent if it's new and needs to be logged.
897 			 */
898 			if ((em->start < start || em_end > end) && modified) {
899 				ASSERT(!split);
900 				btrfs_set_inode_full_sync(inode);
901 			}
902 			remove_extent_mapping(em_tree, em);
903 		}
904 
905 		/*
906 		 * Once for the tree reference (we replaced or removed the
907 		 * extent map from the tree).
908 		 */
909 		free_extent_map(em);
910 next:
911 		/* Once for us (for our lookup reference). */
912 		free_extent_map(em);
913 
914 		em = next_em;
915 	}
916 
917 	write_unlock(&em_tree->lock);
918 
919 	free_extent_map(split);
920 	free_extent_map(split2);
921 }
922 
923 /*
924  * Replace a range in the inode's extent map tree with a new extent map.
925  *
926  * @inode:      The target inode.
927  * @new_em:     The new extent map to add to the inode's extent map tree.
928  * @modified:   Indicate if the new extent map should be added to the list of
929  *              modified extents (for fast fsync tracking).
930  *
931  * Drops all the extent maps in the inode's extent map tree that intersect the
932  * range of the new extent map and adds the new extent map to the tree.
933  * The caller should have locked an appropriate file range in the inode's io
934  * tree before calling this function.
935  */
936 int btrfs_replace_extent_map_range(struct btrfs_inode *inode,
937 				   struct extent_map *new_em,
938 				   bool modified)
939 {
940 	const u64 end = new_em->start + new_em->len - 1;
941 	struct extent_map_tree *tree = &inode->extent_tree;
942 	int ret;
943 
944 	ASSERT(!extent_map_in_tree(new_em));
945 
946 	/*
947 	 * The caller has locked an appropriate file range in the inode's io
948 	 * tree, but getting -EEXIST when adding the new extent map can still
949 	 * happen in case there are extents that partially cover the range, and
950 	 * this is due to two tasks operating on different parts of the extent.
951 	 * See commit 18e83ac75bfe67 ("Btrfs: fix unexpected EEXIST from
952 	 * btrfs_get_extent") for an example and details.
953 	 */
954 	do {
955 		btrfs_drop_extent_map_range(inode, new_em->start, end, false);
956 		write_lock(&tree->lock);
957 		ret = add_extent_mapping(tree, new_em, modified);
958 		write_unlock(&tree->lock);
959 	} while (ret == -EEXIST);
960 
961 	return ret;
962 }
963