xref: /linux/fs/btrfs/extent-io-tree.c (revision 50c44fea13ec339d0d457079b254e8c8420d6511)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include <linux/slab.h>
4 #include <trace/events/btrfs.h>
5 #include "messages.h"
6 #include "ctree.h"
7 #include "extent_io.h"
8 #include "extent-io-tree.h"
9 #include "btrfs_inode.h"
10 
11 static struct kmem_cache *extent_state_cache;
12 
extent_state_in_tree(const struct extent_state * state)13 static inline bool extent_state_in_tree(const struct extent_state *state)
14 {
15 	return !RB_EMPTY_NODE(&state->rb_node);
16 }
17 
18 #ifdef CONFIG_BTRFS_DEBUG
19 static LIST_HEAD(states);
20 static DEFINE_SPINLOCK(leak_lock);
21 
btrfs_leak_debug_add_state(struct extent_state * state)22 static inline void btrfs_leak_debug_add_state(struct extent_state *state)
23 {
24 	unsigned long flags;
25 
26 	spin_lock_irqsave(&leak_lock, flags);
27 	list_add(&state->leak_list, &states);
28 	spin_unlock_irqrestore(&leak_lock, flags);
29 }
30 
btrfs_leak_debug_del_state(struct extent_state * state)31 static inline void btrfs_leak_debug_del_state(struct extent_state *state)
32 {
33 	unsigned long flags;
34 
35 	spin_lock_irqsave(&leak_lock, flags);
36 	list_del(&state->leak_list);
37 	spin_unlock_irqrestore(&leak_lock, flags);
38 }
39 
btrfs_extent_state_leak_debug_check(void)40 static inline void btrfs_extent_state_leak_debug_check(void)
41 {
42 	struct extent_state *state;
43 
44 	while (!list_empty(&states)) {
45 		state = list_first_entry(&states, struct extent_state, leak_list);
46 		btrfs_err(NULL,
47 		       "state leak: start %llu end %llu state %u in tree %d refs %d",
48 		       state->start, state->end, state->state,
49 		       extent_state_in_tree(state),
50 		       refcount_read(&state->refs));
51 		list_del(&state->leak_list);
52 		WARN_ON_ONCE(1);
53 		kmem_cache_free(extent_state_cache, state);
54 	}
55 }
56 
57 #define btrfs_debug_check_extent_io_range(tree, start, end)		\
58 	__btrfs_debug_check_extent_io_range(__func__, (tree), (start), (end))
__btrfs_debug_check_extent_io_range(const char * caller,struct extent_io_tree * tree,u64 start,u64 end)59 static inline void __btrfs_debug_check_extent_io_range(const char *caller,
60 						       struct extent_io_tree *tree,
61 						       u64 start, u64 end)
62 {
63 	const struct btrfs_inode *inode = tree->inode;
64 	u64 isize;
65 
66 	if (tree->owner != IO_TREE_INODE_IO)
67 		return;
68 
69 	isize = i_size_read(&inode->vfs_inode);
70 	if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
71 		btrfs_debug_rl(inode->root->fs_info,
72 		    "%s: ino %llu isize %llu odd range [%llu,%llu]",
73 			caller, btrfs_ino(inode), isize, start, end);
74 	}
75 }
76 #else
77 #define btrfs_leak_debug_add_state(state)		do {} while (0)
78 #define btrfs_leak_debug_del_state(state)		do {} while (0)
79 #define btrfs_extent_state_leak_debug_check()		do {} while (0)
80 #define btrfs_debug_check_extent_io_range(c, s, e)	do {} while (0)
81 #endif
82 
83 /* Read-only access to the inode. */
btrfs_extent_io_tree_to_inode(const struct extent_io_tree * tree)84 const struct btrfs_inode *btrfs_extent_io_tree_to_inode(const struct extent_io_tree *tree)
85 {
86 	if (tree->owner == IO_TREE_INODE_IO)
87 		return tree->inode;
88 	return NULL;
89 }
90 
91 /* For read-only access to fs_info. */
btrfs_extent_io_tree_to_fs_info(const struct extent_io_tree * tree)92 const struct btrfs_fs_info *btrfs_extent_io_tree_to_fs_info(const struct extent_io_tree *tree)
93 {
94 	if (tree->owner == IO_TREE_INODE_IO)
95 		return tree->inode->root->fs_info;
96 	return tree->fs_info;
97 }
98 
btrfs_extent_io_tree_init(struct btrfs_fs_info * fs_info,struct extent_io_tree * tree,unsigned int owner)99 void btrfs_extent_io_tree_init(struct btrfs_fs_info *fs_info,
100 			       struct extent_io_tree *tree, unsigned int owner)
101 {
102 	tree->state = RB_ROOT;
103 	spin_lock_init(&tree->lock);
104 	tree->fs_info = fs_info;
105 	tree->owner = owner;
106 }
107 
108 /*
109  * Empty an io tree, removing and freeing every extent state record from the
110  * tree. This should be called once we are sure no other task can access the
111  * tree anymore, so no tree updates happen after we empty the tree and there
112  * aren't any waiters on any extent state record (EXTENT_LOCK_BITS are never
113  * set on any extent state when calling this function).
114  */
btrfs_extent_io_tree_release(struct extent_io_tree * tree)115 void btrfs_extent_io_tree_release(struct extent_io_tree *tree)
116 {
117 	struct rb_root root;
118 	struct extent_state *state;
119 	struct extent_state *tmp;
120 
121 	spin_lock(&tree->lock);
122 	root = tree->state;
123 	tree->state = RB_ROOT;
124 	rbtree_postorder_for_each_entry_safe(state, tmp, &root, rb_node) {
125 		/* Clear node to keep free_extent_state() happy. */
126 		RB_CLEAR_NODE(&state->rb_node);
127 		ASSERT(!(state->state & EXTENT_LOCK_BITS));
128 		/*
129 		 * No need for a memory barrier here, as we are holding the tree
130 		 * lock and we only change the waitqueue while holding that lock
131 		 * (see wait_extent_bit()).
132 		 */
133 		ASSERT(!waitqueue_active(&state->wq));
134 		btrfs_free_extent_state(state);
135 		cond_resched_lock(&tree->lock);
136 	}
137 	/*
138 	 * Should still be empty even after a reschedule, no other task should
139 	 * be accessing the tree anymore.
140 	 */
141 	ASSERT(RB_EMPTY_ROOT(&tree->state));
142 	spin_unlock(&tree->lock);
143 }
144 
alloc_extent_state(gfp_t mask)145 static struct extent_state *alloc_extent_state(gfp_t mask)
146 {
147 	struct extent_state *state;
148 
149 	/*
150 	 * The given mask might be not appropriate for the slab allocator,
151 	 * drop the unsupported bits
152 	 */
153 	mask &= ~(__GFP_DMA32|__GFP_HIGHMEM);
154 	state = kmem_cache_alloc(extent_state_cache, mask);
155 	if (!state)
156 		return state;
157 	state->state = 0;
158 	RB_CLEAR_NODE(&state->rb_node);
159 	btrfs_leak_debug_add_state(state);
160 	refcount_set(&state->refs, 1);
161 	init_waitqueue_head(&state->wq);
162 	trace_btrfs_alloc_extent_state(state, mask, _RET_IP_);
163 	return state;
164 }
165 
alloc_extent_state_atomic(struct extent_state * prealloc)166 static struct extent_state *alloc_extent_state_atomic(struct extent_state *prealloc)
167 {
168 	if (!prealloc)
169 		prealloc = alloc_extent_state(GFP_ATOMIC);
170 
171 	return prealloc;
172 }
173 
btrfs_free_extent_state(struct extent_state * state)174 void btrfs_free_extent_state(struct extent_state *state)
175 {
176 	if (!state)
177 		return;
178 	if (refcount_dec_and_test(&state->refs)) {
179 		WARN_ON(extent_state_in_tree(state));
180 		btrfs_leak_debug_del_state(state);
181 		trace_btrfs_free_extent_state(state, _RET_IP_);
182 		kmem_cache_free(extent_state_cache, state);
183 	}
184 }
185 
add_extent_changeset(struct extent_state * state,u32 bits,struct extent_changeset * changeset,bool set)186 static int add_extent_changeset(struct extent_state *state, u32 bits,
187 				 struct extent_changeset *changeset,
188 				 bool set)
189 {
190 	int ret;
191 
192 	if (!changeset)
193 		return 0;
194 	if (set && (state->state & bits) == bits)
195 		return 0;
196 	if (!set && (state->state & bits) == 0)
197 		return 0;
198 
199 	changeset->bytes_changed += state->end - state->start + 1;
200 	if (!extent_changeset_tracks_ranges(changeset))
201 		return 0;
202 
203 	ret = ulist_add(&changeset->range_changed, state->start, state->end, GFP_ATOMIC);
204 	if (ret < 0)
205 		return ret;
206 	return 0;
207 }
208 
next_state(struct extent_state * state)209 static inline struct extent_state *next_state(struct extent_state *state)
210 {
211 	struct rb_node *next = rb_next(&state->rb_node);
212 
213 	return rb_entry_safe(next, struct extent_state, rb_node);
214 }
215 
prev_state(struct extent_state * state)216 static inline struct extent_state *prev_state(struct extent_state *state)
217 {
218 	struct rb_node *next = rb_prev(&state->rb_node);
219 
220 	return rb_entry_safe(next, struct extent_state, rb_node);
221 }
222 
223 /*
224  * Search @tree for an entry that contains @offset or if none exists for the
225  * first entry that starts and ends after that offset.
226  *
227  * @tree:       the tree to search
228  * @offset:     search offset
229  * @node_ret:   pointer where new node should be anchored (used when inserting an
230  *	        entry in the tree)
231  * @parent_ret: points to entry which would have been the parent of the entry,
232  *               containing @offset
233  *
234  * Return a pointer to the entry that contains @offset byte address.
235  *
236  * If no such entry exists, return the first entry that starts and ends after
237  * @offset if one exists, otherwise NULL.
238  *
239  * If the returned entry starts at @offset, then @node_ret and @parent_ret
240  * aren't changed.
241  */
tree_search_for_insert(struct extent_io_tree * tree,u64 offset,struct rb_node *** node_ret,struct rb_node ** parent_ret)242 static inline struct extent_state *tree_search_for_insert(struct extent_io_tree *tree,
243 							  u64 offset,
244 							  struct rb_node ***node_ret,
245 							  struct rb_node **parent_ret)
246 {
247 	struct rb_root *root = &tree->state;
248 	struct rb_node **node = &root->rb_node;
249 	struct rb_node *prev = NULL;
250 	struct extent_state *entry = NULL;
251 
252 	while (*node) {
253 		prev = *node;
254 		entry = rb_entry(prev, struct extent_state, rb_node);
255 
256 		if (offset < entry->start)
257 			node = &(*node)->rb_left;
258 		else if (offset > entry->end)
259 			node = &(*node)->rb_right;
260 		else
261 			return entry;
262 	}
263 
264 	if (node_ret)
265 		*node_ret = node;
266 	if (parent_ret)
267 		*parent_ret = prev;
268 
269 	/*
270 	 * Return either the current entry if it contains offset (it ends after
271 	 * or at offset) or the first entry that starts and ends after offset if
272 	 * one exists, or NULL.
273 	 */
274 	while (entry && offset > entry->end)
275 		entry = next_state(entry);
276 
277 	return entry;
278 }
279 
280 /*
281  * Search offset in the tree or fill neighbor rbtree node pointers.
282  *
283  * @tree:      the tree to search
284  * @offset:    offset that should fall within an entry in @tree
285  * @next_ret:  pointer to the first entry whose range ends after @offset
286  * @prev_ret:  pointer to the first entry whose range begins before @offset
287  *
288  * Return a pointer to the entry that contains @offset byte address. If no
289  * such entry exists, then return NULL and fill @prev_ret and @next_ret.
290  * Otherwise return the found entry and other pointers are left untouched.
291  */
tree_search_prev_next(struct extent_io_tree * tree,u64 offset,struct extent_state ** prev_ret,struct extent_state ** next_ret)292 static struct extent_state *tree_search_prev_next(struct extent_io_tree *tree,
293 						  u64 offset,
294 						  struct extent_state **prev_ret,
295 						  struct extent_state **next_ret)
296 {
297 	struct rb_root *root = &tree->state;
298 	struct rb_node **node = &root->rb_node;
299 	struct extent_state *orig_prev;
300 	struct extent_state *entry = NULL;
301 
302 	ASSERT(prev_ret);
303 	ASSERT(next_ret);
304 
305 	while (*node) {
306 		entry = rb_entry(*node, struct extent_state, rb_node);
307 
308 		if (offset < entry->start)
309 			node = &(*node)->rb_left;
310 		else if (offset > entry->end)
311 			node = &(*node)->rb_right;
312 		else
313 			return entry;
314 	}
315 
316 	orig_prev = entry;
317 	while (entry && offset > entry->end)
318 		entry = next_state(entry);
319 	*next_ret = entry;
320 	entry = orig_prev;
321 
322 	while (entry && offset < entry->start)
323 		entry = prev_state(entry);
324 	*prev_ret = entry;
325 
326 	return NULL;
327 }
328 
329 /*
330  * Inexact rb-tree search, return the next entry if @offset is not found
331  */
tree_search(struct extent_io_tree * tree,u64 offset)332 static inline struct extent_state *tree_search(struct extent_io_tree *tree, u64 offset)
333 {
334 	return tree_search_for_insert(tree, offset, NULL, NULL);
335 }
336 
validate_extent_state(const struct extent_io_tree * tree,const struct extent_state * state)337 static void validate_extent_state(const struct extent_io_tree *tree,
338 				  const struct extent_state *state)
339 {
340 	u32 blocksize;
341 
342 	if (tree->owner != IO_TREE_INODE_IO)
343 		return;
344 
345 	blocksize = btrfs_extent_io_tree_to_fs_info(tree)->sectorsize;
346 	ASSERT(IS_ALIGNED(state->start, blocksize) &&
347 	       IS_ALIGNED(state->end + 1, blocksize),
348 	       "unaligned extent state, blocksize=%u start=%llu end=%llu state=0x%x",
349 	       blocksize, state->start, state->end, state->state);
350 }
351 
352 #define extent_io_tree_panic(tree, state, opname, err)                      \
353 	btrfs_panic(btrfs_extent_io_tree_to_fs_info((tree)), (err),         \
354 		    "extent io tree error on %s state start %llu end %llu", \
355 		    (opname), (state)->start, (state)->end)
356 
merge_prev_state(struct extent_io_tree * tree,struct extent_state * state)357 static void merge_prev_state(struct extent_io_tree *tree, struct extent_state *state)
358 {
359 	struct extent_state *prev;
360 
361 	prev = prev_state(state);
362 	if (prev && prev->end == state->start - 1 && prev->state == state->state) {
363 		if (tree->owner == IO_TREE_INODE_IO)
364 			btrfs_merge_delalloc_extent(tree->inode, state, prev);
365 		state->start = prev->start;
366 		rb_erase(&prev->rb_node, &tree->state);
367 		RB_CLEAR_NODE(&prev->rb_node);
368 		btrfs_free_extent_state(prev);
369 	}
370 }
371 
merge_next_state(struct extent_io_tree * tree,struct extent_state * state)372 static void merge_next_state(struct extent_io_tree *tree, struct extent_state *state)
373 {
374 	struct extent_state *next;
375 
376 	next = next_state(state);
377 	if (next && next->start == state->end + 1 && next->state == state->state) {
378 		if (tree->owner == IO_TREE_INODE_IO)
379 			btrfs_merge_delalloc_extent(tree->inode, state, next);
380 		state->end = next->end;
381 		rb_erase(&next->rb_node, &tree->state);
382 		RB_CLEAR_NODE(&next->rb_node);
383 		btrfs_free_extent_state(next);
384 	}
385 }
386 
387 /*
388  * Utility function to look for merge candidates inside a given range.  Any
389  * extents with matching state are merged together into a single extent in the
390  * tree.  Extents with EXTENT_IO in their state field are not merged because
391  * the end_io handlers need to be able to do operations on them without
392  * sleeping (or doing allocations/splits).
393  *
394  * This should be called with the tree lock held.
395  */
merge_state(struct extent_io_tree * tree,struct extent_state * state)396 static void merge_state(struct extent_io_tree *tree, struct extent_state *state)
397 {
398 	if (state->state & (EXTENT_LOCK_BITS | EXTENT_BOUNDARY))
399 		return;
400 
401 	merge_prev_state(tree, state);
402 	merge_next_state(tree, state);
403 }
404 
set_state_bits(struct extent_io_tree * tree,struct extent_state * state,u32 bits,struct extent_changeset * changeset)405 static void set_state_bits(struct extent_io_tree *tree,
406 			   struct extent_state *state,
407 			   u32 bits, struct extent_changeset *changeset)
408 {
409 	u32 bits_to_set = bits & ~EXTENT_CTLBITS;
410 	int ret;
411 
412 	if (tree->owner == IO_TREE_INODE_IO)
413 		btrfs_set_delalloc_extent(tree->inode, state, bits);
414 
415 	ret = add_extent_changeset(state, bits_to_set, changeset, true);
416 	if (unlikely(ret))
417 		extent_io_tree_panic(tree, state, "add_extent_changeset", ret);
418 	state->state |= bits_to_set;
419 }
420 
421 /*
422  * Insert an extent_state struct into the tree.  'bits' are set on the
423  * struct before it is inserted.
424  *
425  * Returns a pointer to the struct extent_state record containing the range
426  * requested for insertion, which may be the same as the given struct or it
427  * may be an existing record in the tree that was expanded to accommodate the
428  * requested range. In case of an extent_state different from the one that was
429  * given, the later can be freed or reused by the caller.
430  *
431  * On error it returns an error pointer.
432  *
433  * The tree lock is not taken internally.  This is a utility function and
434  * probably isn't what you want to call (see set/clear_extent_bit).
435  */
insert_state(struct extent_io_tree * tree,struct extent_state * state,u32 bits,struct extent_changeset * changeset)436 static struct extent_state *insert_state(struct extent_io_tree *tree,
437 					 struct extent_state *state,
438 					 u32 bits,
439 					 struct extent_changeset *changeset)
440 {
441 	struct rb_node **node;
442 	struct rb_node *parent = NULL;
443 	const u64 start = state->start - 1;
444 	const u64 end = state->end + 1;
445 	const bool try_merge = !(bits & (EXTENT_LOCK_BITS | EXTENT_BOUNDARY));
446 
447 	validate_extent_state(tree, state);
448 
449 	set_state_bits(tree, state, bits, changeset);
450 
451 	node = &tree->state.rb_node;
452 	while (*node) {
453 		struct extent_state *entry;
454 
455 		parent = *node;
456 		entry = rb_entry(parent, struct extent_state, rb_node);
457 
458 		if (state->end < entry->start) {
459 			if (try_merge && end == entry->start &&
460 			    state->state == entry->state) {
461 				if (tree->owner == IO_TREE_INODE_IO)
462 					btrfs_merge_delalloc_extent(tree->inode,
463 								    state, entry);
464 				entry->start = state->start;
465 				merge_prev_state(tree, entry);
466 				state->state = 0;
467 				return entry;
468 			}
469 			node = &(*node)->rb_left;
470 		} else if (state->end > entry->end) {
471 			if (try_merge && entry->end == start &&
472 			    state->state == entry->state) {
473 				if (tree->owner == IO_TREE_INODE_IO)
474 					btrfs_merge_delalloc_extent(tree->inode,
475 								    state, entry);
476 				entry->end = state->end;
477 				merge_next_state(tree, entry);
478 				state->state = 0;
479 				return entry;
480 			}
481 			node = &(*node)->rb_right;
482 		} else {
483 			return ERR_PTR(-EEXIST);
484 		}
485 	}
486 
487 	rb_link_node(&state->rb_node, parent, node);
488 	rb_insert_color(&state->rb_node, &tree->state);
489 
490 	return state;
491 }
492 
493 /*
494  * Insert state to @tree to the location given by @node and @parent.
495  */
insert_state_fast(struct extent_io_tree * tree,struct extent_state * state,struct rb_node ** node,struct rb_node * parent,unsigned bits,struct extent_changeset * changeset)496 static void insert_state_fast(struct extent_io_tree *tree,
497 			      struct extent_state *state, struct rb_node **node,
498 			      struct rb_node *parent, unsigned bits,
499 			      struct extent_changeset *changeset)
500 {
501 	validate_extent_state(tree, state);
502 
503 	set_state_bits(tree, state, bits, changeset);
504 	rb_link_node(&state->rb_node, parent, node);
505 	rb_insert_color(&state->rb_node, &tree->state);
506 	merge_state(tree, state);
507 }
508 
509 /*
510  * Split a given extent state struct in two, inserting the preallocated
511  * struct 'prealloc' as the newly created second half.  'split' indicates an
512  * offset inside 'orig' where it should be split.
513  *
514  * Before calling,
515  * the tree has 'orig' at [orig->start, orig->end].  After calling, there
516  * are two extent state structs in the tree:
517  * prealloc: [orig->start, split - 1]
518  * orig: [ split, orig->end ]
519  *
520  * The tree locks are not taken by this function. They need to be held
521  * by the caller.
522  */
split_state(struct extent_io_tree * tree,struct extent_state * orig,struct extent_state * prealloc,u64 split)523 static int split_state(struct extent_io_tree *tree, struct extent_state *orig,
524 		       struct extent_state *prealloc, u64 split)
525 {
526 	struct rb_node *parent = NULL;
527 	struct rb_node **node;
528 
529 	if (tree->owner == IO_TREE_INODE_IO)
530 		btrfs_split_delalloc_extent(tree->inode, orig, split);
531 
532 	prealloc->start = orig->start;
533 	prealloc->end = split - 1;
534 	prealloc->state = orig->state;
535 	orig->start = split;
536 
537 	parent = &orig->rb_node;
538 	node = &parent;
539 	while (*node) {
540 		struct extent_state *entry;
541 
542 		parent = *node;
543 		entry = rb_entry(parent, struct extent_state, rb_node);
544 
545 		if (prealloc->end < entry->start) {
546 			node = &(*node)->rb_left;
547 		} else if (prealloc->end > entry->end) {
548 			node = &(*node)->rb_right;
549 		} else {
550 			btrfs_free_extent_state(prealloc);
551 			return -EEXIST;
552 		}
553 	}
554 
555 	validate_extent_state(tree, orig);
556 	validate_extent_state(tree, prealloc);
557 	rb_link_node(&prealloc->rb_node, parent, node);
558 	rb_insert_color(&prealloc->rb_node, &tree->state);
559 
560 	return 0;
561 }
562 
state_wake_up(struct extent_io_tree * tree,struct extent_state * state,u32 bits)563 static inline void state_wake_up(struct extent_io_tree *tree,
564 				 struct extent_state *state, u32 bits)
565 {
566 	lockdep_assert_held(&tree->lock);
567 
568 	if (!(bits & EXTENT_LOCK_BITS))
569 		return;
570 
571 	/*
572 	 * No memory barriers because the tree's lock is held while:
573 	 *
574 	 * 1) Adding waiters to the queue.
575 	 * 2) Waking up waiters.
576 	 * 3) Removing waiters from queue.
577 	 */
578 	cond_wake_up_nomb(&state->wq);
579 }
580 
581 /*
582  * Use this during tree iteration to avoid doing next node searches when it's
583  * not needed (the current record ends at or after the target range's end).
584  */
next_search_state(struct extent_state * state,u64 end)585 static inline struct extent_state *next_search_state(struct extent_state *state, u64 end)
586 {
587 	if (state->end < end)
588 		return next_state(state);
589 
590 	return NULL;
591 }
592 
593 /*
594  * Utility function to clear some bits in an extent state struct.  It will
595  * optionally wake up anyone waiting on this state.
596  *
597  * If no bits are set on the state struct after clearing things, the
598  * struct is freed and removed from the tree
599  */
clear_state_bit(struct extent_io_tree * tree,struct extent_state * state,u32 bits,u64 end,struct extent_changeset * changeset)600 static struct extent_state *clear_state_bit(struct extent_io_tree *tree,
601 					    struct extent_state *state,
602 					    u32 bits, u64 end,
603 					    struct extent_changeset *changeset)
604 {
605 	struct extent_state *next;
606 	u32 bits_to_clear = bits & ~EXTENT_CTLBITS;
607 	int ret;
608 
609 	if (tree->owner == IO_TREE_INODE_IO)
610 		btrfs_clear_delalloc_extent(tree->inode, state, bits);
611 
612 	ret = add_extent_changeset(state, bits_to_clear, changeset, false);
613 	if (unlikely(ret))
614 		extent_io_tree_panic(tree, state, "add_extent_changeset", ret);
615 	state->state &= ~bits_to_clear;
616 	state_wake_up(tree, state, bits);
617 	if (state->state == 0) {
618 		if (unlikely(!extent_state_in_tree(state)))
619 			extent_io_tree_panic(tree, state, "extent_state_in_tree", -EUCLEAN);
620 
621 		next = next_search_state(state, end);
622 		rb_erase(&state->rb_node, &tree->state);
623 		RB_CLEAR_NODE(&state->rb_node);
624 		btrfs_free_extent_state(state);
625 	} else {
626 		merge_state(tree, state);
627 		next = next_search_state(state, end);
628 	}
629 	return next;
630 }
631 
632 /*
633  * Detect if extent bits request NOWAIT semantics and set the gfp mask accordingly,
634  * unset the EXTENT_NOWAIT bit.
635  */
set_gfp_mask_from_bits(u32 * bits,gfp_t * mask)636 static void set_gfp_mask_from_bits(u32 *bits, gfp_t *mask)
637 {
638 	*mask = (*bits & EXTENT_NOWAIT ? GFP_NOWAIT : GFP_NOFS);
639 	*bits &= EXTENT_NOWAIT - 1;
640 }
641 
642 /*
643  * Clear some bits on a range in the tree.  This may require splitting or
644  * inserting elements in the tree, so the gfp mask is used to indicate which
645  * allocations or sleeping are allowed.
646  *
647  * The range [start, end] is inclusive.
648  *
649  * This takes the tree lock, and returns 0 on success and < 0 on error.
650  */
btrfs_clear_extent_bit_changeset(struct extent_io_tree * tree,u64 start,u64 end,u32 bits,struct extent_state ** cached_state,struct extent_changeset * changeset)651 int btrfs_clear_extent_bit_changeset(struct extent_io_tree *tree, u64 start, u64 end,
652 				     u32 bits, struct extent_state **cached_state,
653 				     struct extent_changeset *changeset)
654 {
655 	struct extent_state *state;
656 	struct extent_state *cached;
657 	struct extent_state *prealloc = NULL;
658 	u64 last_end;
659 	int ret = 0;
660 	bool clear;
661 	const bool delete = (bits & EXTENT_CLEAR_ALL_BITS);
662 	const u32 bits_to_clear = (bits & ~EXTENT_CTLBITS);
663 	gfp_t mask;
664 
665 	set_gfp_mask_from_bits(&bits, &mask);
666 	btrfs_debug_check_extent_io_range(tree, start, end);
667 	trace_btrfs_clear_extent_bit(tree, start, end - start + 1, bits);
668 
669 	if (delete)
670 		bits |= ~EXTENT_CTLBITS;
671 
672 	if (bits & EXTENT_DELALLOC)
673 		bits |= EXTENT_NORESERVE;
674 
675 	clear = (bits & (EXTENT_LOCK_BITS | EXTENT_BOUNDARY));
676 again:
677 	if (!prealloc) {
678 		/*
679 		 * Don't care for allocation failure here because we might end
680 		 * up not needing the pre-allocated extent state at all, which
681 		 * is the case if we only have in the tree extent states that
682 		 * cover our input range and don't cover too any other range.
683 		 * If we end up needing a new extent state we allocate it later.
684 		 */
685 		prealloc = alloc_extent_state(mask);
686 	}
687 
688 	spin_lock(&tree->lock);
689 	if (cached_state) {
690 		cached = *cached_state;
691 
692 		if (clear) {
693 			*cached_state = NULL;
694 			cached_state = NULL;
695 		}
696 
697 		if (cached && extent_state_in_tree(cached) &&
698 		    cached->start <= start && cached->end > start) {
699 			if (clear)
700 				refcount_dec(&cached->refs);
701 			state = cached;
702 			goto hit_next;
703 		}
704 		if (clear)
705 			btrfs_free_extent_state(cached);
706 	}
707 
708 	/* This search will find the extents that end after our range starts. */
709 	state = tree_search(tree, start);
710 	if (!state)
711 		goto out;
712 hit_next:
713 	if (state->start > end)
714 		goto out;
715 	WARN_ON(state->end < start);
716 	last_end = state->end;
717 
718 	/* The state doesn't have the wanted bits, go ahead. */
719 	if (!(state->state & bits)) {
720 		state = next_search_state(state, end);
721 		goto next;
722 	}
723 
724 	/*
725 	 *     | ---- desired range ---- |
726 	 *  | state | or
727 	 *  | ------------- state -------------- |
728 	 *
729 	 * We need to split the extent we found, and may flip bits on second
730 	 * half.
731 	 *
732 	 * If the extent we found extends past our range, we just split and
733 	 * search again.  It'll get split again the next time though.
734 	 *
735 	 * If the extent we found is inside our range, we clear the desired bit
736 	 * on it.
737 	 */
738 
739 	if (state->start < start) {
740 		/*
741 		 * If all bits are cleared, there's no point in allocating or
742 		 * using the prealloc extent, split the state record, insert the
743 		 * prealloc record and then remove this record. We can just
744 		 * adjust this record and move on to the next without adding or
745 		 * removing anything to the tree.
746 		 */
747 		if (state->end <= end && (state->state & ~bits_to_clear) == 0) {
748 			const u64 orig_start = state->start;
749 
750 			if (tree->owner == IO_TREE_INODE_IO)
751 				btrfs_split_delalloc_extent(tree->inode, state, start);
752 
753 			/*
754 			 * Temporarilly ajdust this state's range to match the
755 			 * range for which we are clearing bits.
756 			 */
757 			state->start = start;
758 
759 			ret = add_extent_changeset(state, bits_to_clear, changeset, false);
760 			if (unlikely(ret < 0)) {
761 				extent_io_tree_panic(tree, state,
762 						     "add_extent_changeset", ret);
763 				goto out;
764 			}
765 
766 			if (tree->owner == IO_TREE_INODE_IO)
767 				btrfs_clear_delalloc_extent(tree->inode, state, bits);
768 
769 			/*
770 			 * Now adjust the range to the section for which no bits
771 			 * are cleared.
772 			 */
773 			state->start = orig_start;
774 			state->end = start - 1;
775 
776 			state_wake_up(tree, state, bits);
777 			state = next_search_state(state, end);
778 			goto next;
779 		}
780 
781 		prealloc = alloc_extent_state_atomic(prealloc);
782 		if (!prealloc)
783 			goto search_again;
784 		ret = split_state(tree, state, prealloc, start);
785 		prealloc = NULL;
786 		if (unlikely(ret)) {
787 			extent_io_tree_panic(tree, state, "split", ret);
788 			goto out;
789 		}
790 		if (state->end <= end) {
791 			state = clear_state_bit(tree, state, bits, end, changeset);
792 			goto next;
793 		}
794 		if (need_resched())
795 			goto search_again;
796 		/*
797 		 * Fallthrough and try atomic extent state allocation if needed.
798 		 * If it fails we'll jump to 'search_again' retry the allocation
799 		 * in non-atomic mode and start the search again.
800 		 */
801 	}
802 	/*
803 	 * | ---- desired range ---- |
804 	 *                        | state |
805 	 * We need to split the extent, and clear the bit on the first half.
806 	 */
807 	if (state->start <= end && state->end > end) {
808 		/*
809 		 * If all bits are cleared, there's no point in allocating or
810 		 * using the prealloc extent, split the state record, insert the
811 		 * prealloc record and then remove it. We can just adjust the
812 		 * start offset of the current state and avoid all that.
813 		 */
814 		if ((state->state & ~bits_to_clear) == 0) {
815 			const u64 orig_end = state->end;
816 
817 			if (tree->owner == IO_TREE_INODE_IO)
818 				btrfs_split_delalloc_extent(tree->inode, state, end + 1);
819 
820 			/*
821 			 * Temporarily adjust the end offset to match the
822 			 * removed subrange to update the changeset.
823 			 */
824 			state->end = end;
825 
826 			ret = add_extent_changeset(state, bits_to_clear, changeset, false);
827 			if (unlikely(ret < 0)) {
828 				extent_io_tree_panic(tree, state,
829 						     "add_extent_changeset", ret);
830 				goto out;
831 			}
832 
833 			if (tree->owner == IO_TREE_INODE_IO)
834 				btrfs_clear_delalloc_extent(tree->inode, state, bits);
835 
836 			state->start = end + 1;
837 			state->end = orig_end;
838 
839 			state_wake_up(tree, state, bits);
840 			goto out;
841 		}
842 
843 		prealloc = alloc_extent_state_atomic(prealloc);
844 		if (!prealloc)
845 			goto search_again;
846 		ret = split_state(tree, state, prealloc, end + 1);
847 		if (unlikely(ret)) {
848 			extent_io_tree_panic(tree, state, "split", ret);
849 			prealloc = NULL;
850 			goto out;
851 		}
852 
853 		state_wake_up(tree, state, bits);
854 
855 		clear_state_bit(tree, prealloc, bits, end, changeset);
856 
857 		prealloc = NULL;
858 		goto out;
859 	}
860 
861 	state = clear_state_bit(tree, state, bits, end, changeset);
862 next:
863 	if (last_end >= end)
864 		goto out;
865 	start = last_end + 1;
866 	if (state && !need_resched())
867 		goto hit_next;
868 
869 search_again:
870 	spin_unlock(&tree->lock);
871 	if (gfpflags_allow_blocking(mask))
872 		cond_resched();
873 	goto again;
874 
875 out:
876 	spin_unlock(&tree->lock);
877 	btrfs_free_extent_state(prealloc);
878 
879 	return ret;
880 
881 }
882 
883 /*
884  * Wait for one or more bits to clear on a range in the state tree.
885  * The range [start, end] is inclusive.
886  * The tree lock is taken by this function
887  */
wait_extent_bit(struct extent_io_tree * tree,u64 start,u64 end,u32 bits,struct extent_state ** cached_state)888 static void wait_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
889 			    u32 bits, struct extent_state **cached_state)
890 {
891 	struct extent_state *state;
892 
893 	btrfs_debug_check_extent_io_range(tree, start, end);
894 
895 	spin_lock(&tree->lock);
896 again:
897 	/*
898 	 * Maintain cached_state, as we may not remove it from the tree if there
899 	 * are more bits than the bits we're waiting on set on this state.
900 	 */
901 	if (cached_state && *cached_state) {
902 		state = *cached_state;
903 		if (extent_state_in_tree(state) &&
904 		    state->start <= start && start < state->end)
905 			goto process_node;
906 	}
907 	while (1) {
908 		/*
909 		 * This search will find all the extents that end after our
910 		 * range starts.
911 		 */
912 		state = tree_search(tree, start);
913 process_node:
914 		if (!state)
915 			break;
916 		if (state->start > end)
917 			goto out;
918 
919 		if (state->state & bits) {
920 			DEFINE_WAIT(wait);
921 
922 			start = state->start;
923 			refcount_inc(&state->refs);
924 			prepare_to_wait(&state->wq, &wait, TASK_UNINTERRUPTIBLE);
925 			spin_unlock(&tree->lock);
926 			schedule();
927 			spin_lock(&tree->lock);
928 			finish_wait(&state->wq, &wait);
929 			btrfs_free_extent_state(state);
930 			goto again;
931 		}
932 		start = state->end + 1;
933 
934 		if (start > end)
935 			break;
936 
937 		if (!cond_resched_lock(&tree->lock)) {
938 			state = next_state(state);
939 			goto process_node;
940 		}
941 	}
942 out:
943 	spin_unlock(&tree->lock);
944 	/* This state is no longer useful, clear it and free it up. */
945 	if (cached_state && *cached_state) {
946 		state = *cached_state;
947 		*cached_state = NULL;
948 		btrfs_free_extent_state(state);
949 	}
950 }
951 
cache_state_if_flags(struct extent_state * state,struct extent_state ** cached_ptr,unsigned flags)952 static void cache_state_if_flags(struct extent_state *state,
953 				 struct extent_state **cached_ptr,
954 				 unsigned flags)
955 {
956 	if (cached_ptr && !(*cached_ptr)) {
957 		if (!flags || (state->state & flags)) {
958 			*cached_ptr = state;
959 			refcount_inc(&state->refs);
960 		}
961 	}
962 }
963 
cache_state(struct extent_state * state,struct extent_state ** cached_ptr)964 static void cache_state(struct extent_state *state,
965 			struct extent_state **cached_ptr)
966 {
967 	return cache_state_if_flags(state, cached_ptr, EXTENT_LOCK_BITS | EXTENT_BOUNDARY);
968 }
969 
970 /*
971  * Find the first state struct with 'bits' set after 'start', and return it.
972  * tree->lock must be held.  NULL will returned if nothing was found after
973  * 'start'.
974  */
find_first_extent_bit_state(struct extent_io_tree * tree,u64 start,u32 bits)975 static struct extent_state *find_first_extent_bit_state(struct extent_io_tree *tree,
976 							u64 start, u32 bits)
977 {
978 	struct extent_state *state;
979 
980 	/*
981 	 * This search will find all the extents that end after our range
982 	 * starts.
983 	 */
984 	state = tree_search(tree, start);
985 	while (state) {
986 		if (state->state & bits)
987 			return state;
988 		state = next_state(state);
989 	}
990 	return NULL;
991 }
992 
993 /*
994  * Find the first offset in the io tree with one or more @bits set.
995  *
996  * Note: If there are multiple bits set in @bits, any of them will match.
997  *
998  * Return true if we find something, and update @start_ret and @end_ret.
999  * Return false if we found nothing.
1000  */
btrfs_find_first_extent_bit(struct extent_io_tree * tree,u64 start,u64 * start_ret,u64 * end_ret,u32 bits,struct extent_state ** cached_state)1001 bool btrfs_find_first_extent_bit(struct extent_io_tree *tree, u64 start,
1002 				 u64 *start_ret, u64 *end_ret, u32 bits,
1003 				 struct extent_state **cached_state)
1004 {
1005 	struct extent_state *state;
1006 	bool ret = false;
1007 
1008 	spin_lock(&tree->lock);
1009 	if (cached_state && *cached_state) {
1010 		state = *cached_state;
1011 		if (state->end == start - 1 && extent_state_in_tree(state)) {
1012 			while ((state = next_state(state)) != NULL) {
1013 				if (state->state & bits)
1014 					break;
1015 			}
1016 			/*
1017 			 * If we found the next extent state, clear cached_state
1018 			 * so that we can cache the next extent state below and
1019 			 * avoid future calls going over the same extent state
1020 			 * again. If we haven't found any, clear as well since
1021 			 * it's now useless.
1022 			 */
1023 			btrfs_free_extent_state(*cached_state);
1024 			*cached_state = NULL;
1025 			if (state)
1026 				goto got_it;
1027 			goto out;
1028 		}
1029 		btrfs_free_extent_state(*cached_state);
1030 		*cached_state = NULL;
1031 	}
1032 
1033 	state = find_first_extent_bit_state(tree, start, bits);
1034 got_it:
1035 	if (state) {
1036 		cache_state_if_flags(state, cached_state, 0);
1037 		*start_ret = state->start;
1038 		*end_ret = state->end;
1039 		ret = true;
1040 	}
1041 out:
1042 	spin_unlock(&tree->lock);
1043 	return ret;
1044 }
1045 
1046 /*
1047  * Find a contiguous area of bits
1048  *
1049  * @tree:      io tree to check
1050  * @start:     offset to start the search from
1051  * @start_ret: the first offset we found with the bits set
1052  * @end_ret:   the final contiguous range of the bits that were set
1053  * @bits:      bits to look for
1054  *
1055  * set_extent_bit and clear_extent_bit can temporarily split contiguous ranges
1056  * to set bits appropriately, and then merge them again.  During this time it
1057  * will drop the tree->lock, so use this helper if you want to find the actual
1058  * contiguous area for given bits.  We will search to the first bit we find, and
1059  * then walk down the tree until we find a non-contiguous area.  The area
1060  * returned will be the full contiguous area with the bits set.
1061  *
1062  * Returns true if we found a range with the given bits set, in which case
1063  * @start_ret and @end_ret are updated, or false if no range was found.
1064  */
btrfs_find_contiguous_extent_bit(struct extent_io_tree * tree,u64 start,u64 * start_ret,u64 * end_ret,u32 bits)1065 bool btrfs_find_contiguous_extent_bit(struct extent_io_tree *tree, u64 start,
1066 				      u64 *start_ret, u64 *end_ret, u32 bits)
1067 {
1068 	struct extent_state *state;
1069 	bool ret = false;
1070 
1071 	ASSERT(!btrfs_fs_incompat(btrfs_extent_io_tree_to_fs_info(tree), NO_HOLES));
1072 
1073 	spin_lock(&tree->lock);
1074 	state = find_first_extent_bit_state(tree, start, bits);
1075 	if (state) {
1076 		*start_ret = state->start;
1077 		*end_ret = state->end;
1078 		while ((state = next_state(state)) != NULL) {
1079 			if (state->start > (*end_ret + 1))
1080 				break;
1081 			*end_ret = state->end;
1082 		}
1083 		ret = true;
1084 	}
1085 	spin_unlock(&tree->lock);
1086 	return ret;
1087 }
1088 
1089 /*
1090  * Find a contiguous range of bytes in the file marked as delalloc, not more
1091  * than 'max_bytes'.  start and end are used to return the range,
1092  *
1093  * True is returned if we find something, false if nothing was in the tree.
1094  */
btrfs_find_delalloc_range(struct extent_io_tree * tree,u64 * start,u64 * end,u64 max_bytes,struct extent_state ** cached_state)1095 bool btrfs_find_delalloc_range(struct extent_io_tree *tree, u64 *start,
1096 			       u64 *end, u64 max_bytes,
1097 			       struct extent_state **cached_state)
1098 {
1099 	struct extent_state *state;
1100 	u64 cur_start = *start;
1101 	bool found = false;
1102 	u64 total_bytes = 0;
1103 
1104 	spin_lock(&tree->lock);
1105 
1106 	/*
1107 	 * This search will find all the extents that end after our range
1108 	 * starts.
1109 	 */
1110 	state = tree_search(tree, cur_start);
1111 	if (!state) {
1112 		*end = (u64)-1;
1113 		goto out;
1114 	}
1115 
1116 	while (state) {
1117 		if (found && (state->start != cur_start ||
1118 			      (state->state & EXTENT_BOUNDARY))) {
1119 			goto out;
1120 		}
1121 		if (!(state->state & EXTENT_DELALLOC)) {
1122 			if (!found)
1123 				*end = state->end;
1124 			goto out;
1125 		}
1126 		if (!found) {
1127 			*start = state->start;
1128 			*cached_state = state;
1129 			refcount_inc(&state->refs);
1130 		}
1131 		found = true;
1132 		*end = state->end;
1133 		cur_start = state->end + 1;
1134 		total_bytes += state->end - state->start + 1;
1135 		if (total_bytes >= max_bytes)
1136 			break;
1137 		state = next_state(state);
1138 	}
1139 out:
1140 	spin_unlock(&tree->lock);
1141 	return found;
1142 }
1143 
1144 /*
1145  * Set some bits on a range in the tree.  This may require allocations or
1146  * sleeping. By default all allocations use GFP_NOFS, use EXTENT_NOWAIT for
1147  * GFP_NOWAIT.
1148  *
1149  * If any of the exclusive bits are set, this will fail with -EEXIST if some
1150  * part of the range already has the desired bits set.  The extent_state of the
1151  * existing range is returned in failed_state in this case, and the start of the
1152  * existing range is returned in failed_start.  failed_state is used as an
1153  * optimization for wait_extent_bit, failed_start must be used as the source of
1154  * truth as failed_state may have changed since we returned.
1155  *
1156  * [start, end] is inclusive This takes the tree lock.
1157  */
set_extent_bit(struct extent_io_tree * tree,u64 start,u64 end,u32 bits,u64 * failed_start,struct extent_state ** failed_state,struct extent_state ** cached_state,struct extent_changeset * changeset)1158 static int set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1159 			  u32 bits, u64 *failed_start,
1160 			  struct extent_state **failed_state,
1161 			  struct extent_state **cached_state,
1162 			  struct extent_changeset *changeset)
1163 {
1164 	struct extent_state *state;
1165 	struct extent_state *prealloc = NULL;
1166 	struct rb_node **p = NULL;
1167 	struct rb_node *parent = NULL;
1168 	int ret = 0;
1169 	u64 last_start;
1170 	u64 last_end;
1171 	u32 exclusive_bits = (bits & EXTENT_LOCK_BITS);
1172 	gfp_t mask;
1173 
1174 	set_gfp_mask_from_bits(&bits, &mask);
1175 	btrfs_debug_check_extent_io_range(tree, start, end);
1176 	trace_btrfs_set_extent_bit(tree, start, end - start + 1, bits);
1177 
1178 	if (exclusive_bits)
1179 		ASSERT(failed_start);
1180 	else
1181 		ASSERT(failed_start == NULL && failed_state == NULL);
1182 again:
1183 	if (!prealloc) {
1184 		/*
1185 		 * Don't care for allocation failure here because we might end
1186 		 * up not needing the pre-allocated extent state at all, which
1187 		 * is the case if we only have in the tree extent states that
1188 		 * cover our input range and don't cover too any other range.
1189 		 * If we end up needing a new extent state we allocate it later.
1190 		 */
1191 		prealloc = alloc_extent_state(mask);
1192 	}
1193 	/* Optimistically preallocate the extent changeset ulist node. */
1194 	if (changeset)
1195 		extent_changeset_prealloc(changeset, mask);
1196 
1197 	spin_lock(&tree->lock);
1198 	if (cached_state && *cached_state) {
1199 		state = *cached_state;
1200 		if (state->start <= start && state->end > start &&
1201 		    extent_state_in_tree(state))
1202 			goto hit_next;
1203 	}
1204 	/*
1205 	 * This search will find all the extents that end after our range
1206 	 * starts.
1207 	 */
1208 	state = tree_search_for_insert(tree, start, &p, &parent);
1209 	if (!state) {
1210 		prealloc = alloc_extent_state_atomic(prealloc);
1211 		if (!prealloc)
1212 			goto search_again;
1213 		prealloc->start = start;
1214 		prealloc->end = end;
1215 		insert_state_fast(tree, prealloc, p, parent, bits, changeset);
1216 		cache_state(prealloc, cached_state);
1217 		prealloc = NULL;
1218 		goto out;
1219 	}
1220 hit_next:
1221 	last_start = state->start;
1222 	last_end = state->end;
1223 
1224 	/*
1225 	 * | ---- desired range ---- |
1226 	 * | state |
1227 	 *
1228 	 * Just lock what we found and keep going
1229 	 */
1230 	if (state->start == start && state->end <= end) {
1231 		if (state->state & exclusive_bits) {
1232 			*failed_start = state->start;
1233 			cache_state(state, failed_state);
1234 			ret = -EEXIST;
1235 			goto out;
1236 		}
1237 
1238 		set_state_bits(tree, state, bits, changeset);
1239 		cache_state(state, cached_state);
1240 		merge_state(tree, state);
1241 		if (last_end >= end)
1242 			goto out;
1243 		start = last_end + 1;
1244 		state = next_state(state);
1245 		if (state && state->start == start && !need_resched())
1246 			goto hit_next;
1247 		goto search_again;
1248 	}
1249 
1250 	/*
1251 	 *     | ---- desired range ---- |
1252 	 * | state |
1253 	 *   or
1254 	 * | ------------- state -------------- |
1255 	 *
1256 	 * We need to split the extent we found, and may flip bits on second
1257 	 * half.
1258 	 *
1259 	 * If the extent we found extends past our range, we just split and
1260 	 * search again.  It'll get split again the next time though.
1261 	 *
1262 	 * If the extent we found is inside our range, we set the desired bit
1263 	 * on it.
1264 	 */
1265 	if (state->start < start) {
1266 		if (state->state & exclusive_bits) {
1267 			*failed_start = start;
1268 			cache_state(state, failed_state);
1269 			ret = -EEXIST;
1270 			goto out;
1271 		}
1272 
1273 		/*
1274 		 * If this extent already has all the bits we want set, then
1275 		 * skip it, not necessary to split it or do anything with it.
1276 		 */
1277 		if ((state->state & bits) == bits) {
1278 			start = state->end + 1;
1279 			cache_state(state, cached_state);
1280 			goto search_again;
1281 		}
1282 
1283 		prealloc = alloc_extent_state_atomic(prealloc);
1284 		if (!prealloc)
1285 			goto search_again;
1286 		ret = split_state(tree, state, prealloc, start);
1287 		if (unlikely(ret))
1288 			extent_io_tree_panic(tree, state, "split", ret);
1289 
1290 		prealloc = NULL;
1291 		if (ret)
1292 			goto out;
1293 		if (state->end <= end) {
1294 			set_state_bits(tree, state, bits, changeset);
1295 			cache_state(state, cached_state);
1296 			merge_state(tree, state);
1297 			if (last_end >= end)
1298 				goto out;
1299 			start = last_end + 1;
1300 			state = next_state(state);
1301 			if (state && state->start == start && !need_resched())
1302 				goto hit_next;
1303 		}
1304 		goto search_again;
1305 	}
1306 	/*
1307 	 * | ---- desired range ---- |
1308 	 *     | state | or               | state |
1309 	 *
1310 	 * There's a hole, we need to insert something in it and ignore the
1311 	 * extent we found.
1312 	 */
1313 	if (state->start > start) {
1314 		struct extent_state *inserted_state;
1315 
1316 		prealloc = alloc_extent_state_atomic(prealloc);
1317 		if (!prealloc)
1318 			goto search_again;
1319 
1320 		/*
1321 		 * Avoid to free 'prealloc' if it can be merged with the later
1322 		 * extent.
1323 		 */
1324 		prealloc->start = start;
1325 		if (end < last_start)
1326 			prealloc->end = end;
1327 		else
1328 			prealloc->end = last_start - 1;
1329 
1330 		inserted_state = insert_state(tree, prealloc, bits, changeset);
1331 		if (IS_ERR(inserted_state)) {
1332 			ret = PTR_ERR(inserted_state);
1333 			extent_io_tree_panic(tree, prealloc, "insert", ret);
1334 			goto out;
1335 		}
1336 
1337 		cache_state(inserted_state, cached_state);
1338 		if (inserted_state == prealloc)
1339 			prealloc = NULL;
1340 		start = inserted_state->end + 1;
1341 
1342 		/* Beyond target range, stop. */
1343 		if (start > end)
1344 			goto out;
1345 
1346 		if (need_resched())
1347 			goto search_again;
1348 
1349 		state = next_search_state(inserted_state, end);
1350 		/*
1351 		 * If there's a next state, whether contiguous or not, we don't
1352 		 * need to unlock and start search again. If it's not contiguous
1353 		 * we will end up here and try to allocate a prealloc state and insert.
1354 		 */
1355 		if (state)
1356 			goto hit_next;
1357 		goto search_again;
1358 	}
1359 	/*
1360 	 * | ---- desired range ---- |
1361 	 *                        | state |
1362 	 *
1363 	 * We need to split the extent, and set the bit on the first half
1364 	 */
1365 	if (state->start <= end && state->end > end) {
1366 		if (state->state & exclusive_bits) {
1367 			*failed_start = start;
1368 			cache_state(state, failed_state);
1369 			ret = -EEXIST;
1370 			goto out;
1371 		}
1372 
1373 		prealloc = alloc_extent_state_atomic(prealloc);
1374 		if (!prealloc)
1375 			goto search_again;
1376 		ret = split_state(tree, state, prealloc, end + 1);
1377 		if (unlikely(ret)) {
1378 			extent_io_tree_panic(tree, state, "split", ret);
1379 			prealloc = NULL;
1380 			goto out;
1381 		}
1382 
1383 		set_state_bits(tree, prealloc, bits, changeset);
1384 		cache_state(prealloc, cached_state);
1385 		merge_state(tree, prealloc);
1386 		prealloc = NULL;
1387 		goto out;
1388 	}
1389 
1390 search_again:
1391 	if (start > end)
1392 		goto out;
1393 	spin_unlock(&tree->lock);
1394 	if (gfpflags_allow_blocking(mask))
1395 		cond_resched();
1396 	goto again;
1397 
1398 out:
1399 	spin_unlock(&tree->lock);
1400 	btrfs_free_extent_state(prealloc);
1401 
1402 	return ret;
1403 
1404 }
1405 
btrfs_set_extent_bit(struct extent_io_tree * tree,u64 start,u64 end,u32 bits,struct extent_state ** cached_state)1406 int btrfs_set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1407 			 u32 bits, struct extent_state **cached_state)
1408 {
1409 	return set_extent_bit(tree, start, end, bits, NULL, NULL, cached_state, NULL);
1410 }
1411 
1412 /*
1413  * Convert all bits in a given range from one bit to another
1414  *
1415  * @tree:	the io tree to search
1416  * @start:	the start offset in bytes
1417  * @end:	the end offset in bytes (inclusive)
1418  * @bits:	the bits to set in this range
1419  * @clear_bits:	the bits to clear in this range
1420  * @cached_state:	state that we're going to cache
1421  *
1422  * This will go through and set bits for the given range.  If any states exist
1423  * already in this range they are set with the given bit and cleared of the
1424  * clear_bits.  This is only meant to be used by things that are mergeable, ie.
1425  * converting from say DELALLOC to DIRTY.  This is not meant to be used with
1426  * boundary bits like LOCK.
1427  *
1428  * All allocations are done with GFP_NOFS.
1429  */
btrfs_convert_extent_bit(struct extent_io_tree * tree,u64 start,u64 end,u32 bits,u32 clear_bits,struct extent_state ** cached_state)1430 int btrfs_convert_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
1431 			     u32 bits, u32 clear_bits,
1432 			     struct extent_state **cached_state)
1433 {
1434 	struct extent_state *state;
1435 	struct extent_state *prealloc = NULL;
1436 	struct rb_node **p = NULL;
1437 	struct rb_node *parent = NULL;
1438 	int ret = 0;
1439 	u64 last_start;
1440 	u64 last_end;
1441 	bool first_iteration = true;
1442 
1443 	btrfs_debug_check_extent_io_range(tree, start, end);
1444 	trace_btrfs_convert_extent_bit(tree, start, end - start + 1, bits,
1445 				       clear_bits);
1446 
1447 again:
1448 	if (!prealloc) {
1449 		/*
1450 		 * Best effort, don't worry if extent state allocation fails
1451 		 * here for the first iteration. We might have a cached state
1452 		 * that matches exactly the target range, in which case no
1453 		 * extent state allocations are needed. We'll only know this
1454 		 * after locking the tree.
1455 		 */
1456 		prealloc = alloc_extent_state(GFP_NOFS);
1457 		if (!prealloc && !first_iteration)
1458 			return -ENOMEM;
1459 	}
1460 
1461 	spin_lock(&tree->lock);
1462 	if (cached_state && *cached_state) {
1463 		state = *cached_state;
1464 		if (state->start <= start && state->end > start &&
1465 		    extent_state_in_tree(state))
1466 			goto hit_next;
1467 	}
1468 
1469 	/*
1470 	 * This search will find all the extents that end after our range
1471 	 * starts.
1472 	 */
1473 	state = tree_search_for_insert(tree, start, &p, &parent);
1474 	if (!state) {
1475 		prealloc = alloc_extent_state_atomic(prealloc);
1476 		if (!prealloc) {
1477 			ret = -ENOMEM;
1478 			goto out;
1479 		}
1480 		prealloc->start = start;
1481 		prealloc->end = end;
1482 		insert_state_fast(tree, prealloc, p, parent, bits, NULL);
1483 		cache_state(prealloc, cached_state);
1484 		prealloc = NULL;
1485 		goto out;
1486 	}
1487 hit_next:
1488 	last_start = state->start;
1489 	last_end = state->end;
1490 
1491 	/*
1492 	 * | ---- desired range ---- |
1493 	 * | state |
1494 	 *
1495 	 * Just lock what we found and keep going.
1496 	 */
1497 	if (state->start == start && state->end <= end) {
1498 		set_state_bits(tree, state, bits, NULL);
1499 		cache_state(state, cached_state);
1500 		state = clear_state_bit(tree, state, clear_bits, end, NULL);
1501 		if (last_end >= end)
1502 			goto out;
1503 		start = last_end + 1;
1504 		if (state && state->start == start && !need_resched())
1505 			goto hit_next;
1506 		goto search_again;
1507 	}
1508 
1509 	/*
1510 	 *     | ---- desired range ---- |
1511 	 * | state |
1512 	 *   or
1513 	 * | ------------- state -------------- |
1514 	 *
1515 	 * We need to split the extent we found, and may flip bits on second
1516 	 * half.
1517 	 *
1518 	 * If the extent we found extends past our range, we just split and
1519 	 * search again.  It'll get split again the next time though.
1520 	 *
1521 	 * If the extent we found is inside our range, we set the desired bit
1522 	 * on it.
1523 	 */
1524 	if (state->start < start) {
1525 		prealloc = alloc_extent_state_atomic(prealloc);
1526 		if (!prealloc) {
1527 			ret = -ENOMEM;
1528 			goto out;
1529 		}
1530 		ret = split_state(tree, state, prealloc, start);
1531 		prealloc = NULL;
1532 		if (unlikely(ret)) {
1533 			extent_io_tree_panic(tree, state, "split", ret);
1534 			goto out;
1535 		}
1536 		if (state->end <= end) {
1537 			set_state_bits(tree, state, bits, NULL);
1538 			cache_state(state, cached_state);
1539 			state = clear_state_bit(tree, state, clear_bits, end, NULL);
1540 			if (last_end >= end)
1541 				goto out;
1542 			start = last_end + 1;
1543 			if (state && state->start == start && !need_resched())
1544 				goto hit_next;
1545 		}
1546 		goto search_again;
1547 	}
1548 	/*
1549 	 * | ---- desired range ---- |
1550 	 *     | state | or               | state |
1551 	 *
1552 	 * There's a hole, we need to insert something in it and ignore the
1553 	 * extent we found.
1554 	 */
1555 	if (state->start > start) {
1556 		struct extent_state *inserted_state;
1557 
1558 		prealloc = alloc_extent_state_atomic(prealloc);
1559 		if (!prealloc) {
1560 			ret = -ENOMEM;
1561 			goto out;
1562 		}
1563 
1564 		/*
1565 		 * Avoid to free 'prealloc' if it can be merged with the later
1566 		 * extent.
1567 		 */
1568 		prealloc->start = start;
1569 		if (end < last_start)
1570 			prealloc->end = end;
1571 		else
1572 			prealloc->end = last_start - 1;
1573 
1574 		inserted_state = insert_state(tree, prealloc, bits, NULL);
1575 		if (IS_ERR(inserted_state)) {
1576 			ret = PTR_ERR(inserted_state);
1577 			extent_io_tree_panic(tree, prealloc, "insert", ret);
1578 			goto out;
1579 		}
1580 		cache_state(inserted_state, cached_state);
1581 		if (inserted_state == prealloc)
1582 			prealloc = NULL;
1583 		start = inserted_state->end + 1;
1584 
1585 		/* Beyond target range, stop. */
1586 		if (start > end)
1587 			goto out;
1588 
1589 		if (need_resched())
1590 			goto search_again;
1591 
1592 		state = next_search_state(inserted_state, end);
1593 		/*
1594 		 * If there's a next state, whether contiguous or not, we don't
1595 		 * need to unlock and start search again. If it's not contiguous
1596 		 * we will end up here and try to allocate a prealloc state and insert.
1597 		 */
1598 		if (state)
1599 			goto hit_next;
1600 		goto search_again;
1601 	}
1602 	/*
1603 	 * | ---- desired range ---- |
1604 	 *                        | state |
1605 	 *
1606 	 * We need to split the extent, and set the bit on the first half.
1607 	 */
1608 	if (state->start <= end && state->end > end) {
1609 		prealloc = alloc_extent_state_atomic(prealloc);
1610 		if (!prealloc) {
1611 			ret = -ENOMEM;
1612 			goto out;
1613 		}
1614 
1615 		ret = split_state(tree, state, prealloc, end + 1);
1616 		if (unlikely(ret)) {
1617 			extent_io_tree_panic(tree, state, "split", ret);
1618 			prealloc = NULL;
1619 			goto out;
1620 		}
1621 
1622 		set_state_bits(tree, prealloc, bits, NULL);
1623 		cache_state(prealloc, cached_state);
1624 		clear_state_bit(tree, prealloc, clear_bits, end, NULL);
1625 		prealloc = NULL;
1626 		goto out;
1627 	}
1628 
1629 search_again:
1630 	if (start > end)
1631 		goto out;
1632 	spin_unlock(&tree->lock);
1633 	cond_resched();
1634 	first_iteration = false;
1635 	goto again;
1636 
1637 out:
1638 	spin_unlock(&tree->lock);
1639 	btrfs_free_extent_state(prealloc);
1640 
1641 	return ret;
1642 }
1643 
1644 /*
1645  * Find the first range that has @bits not set. This range could start before
1646  * @start.
1647  *
1648  * @tree:      the tree to search
1649  * @start:     offset at/after which the found extent should start
1650  * @start_ret: records the beginning of the range
1651  * @end_ret:   records the end of the range (inclusive)
1652  * @bits:      the set of bits which must be unset
1653  *
1654  * Since unallocated range is also considered one which doesn't have the bits
1655  * set it's possible that @end_ret contains -1, this happens in case the range
1656  * spans (last_range_end, end of device]. In this case it's up to the caller to
1657  * trim @end_ret to the appropriate size.
1658  */
btrfs_find_first_clear_extent_bit(struct extent_io_tree * tree,u64 start,u64 * start_ret,u64 * end_ret,u32 bits)1659 void btrfs_find_first_clear_extent_bit(struct extent_io_tree *tree, u64 start,
1660 				       u64 *start_ret, u64 *end_ret, u32 bits)
1661 {
1662 	struct extent_state *state;
1663 	struct extent_state *prev = NULL, *next = NULL;
1664 
1665 	spin_lock(&tree->lock);
1666 
1667 	/* Find first extent with bits cleared */
1668 	while (1) {
1669 		state = tree_search_prev_next(tree, start, &prev, &next);
1670 		if (!state && !next && !prev) {
1671 			/*
1672 			 * Tree is completely empty, send full range and let
1673 			 * caller deal with it
1674 			 */
1675 			*start_ret = 0;
1676 			*end_ret = -1;
1677 			goto out;
1678 		} else if (!state && !next) {
1679 			/*
1680 			 * We are past the last allocated chunk, set start at
1681 			 * the end of the last extent.
1682 			 */
1683 			*start_ret = prev->end + 1;
1684 			*end_ret = -1;
1685 			goto out;
1686 		} else if (!state) {
1687 			state = next;
1688 		}
1689 
1690 		/*
1691 		 * At this point 'state' either contains 'start' or start is
1692 		 * before 'state'
1693 		 */
1694 		if (in_range(start, state->start, state->end - state->start + 1)) {
1695 			if (state->state & bits) {
1696 				/*
1697 				 * |--range with bits sets--|
1698 				 *    |
1699 				 *    start
1700 				 */
1701 				start = state->end + 1;
1702 			} else {
1703 				/*
1704 				 * 'start' falls within a range that doesn't
1705 				 * have the bits set, so take its start as the
1706 				 * beginning of the desired range
1707 				 *
1708 				 * |--range with bits cleared----|
1709 				 *      |
1710 				 *      start
1711 				 */
1712 				*start_ret = state->start;
1713 				break;
1714 			}
1715 		} else {
1716 			/*
1717 			 * |---prev range---|---hole/unset---|---node range---|
1718 			 *                          |
1719 			 *                        start
1720 			 *
1721 			 *                        or
1722 			 *
1723 			 * |---hole/unset--||--first node--|
1724 			 * 0   |
1725 			 *    start
1726 			 */
1727 			if (prev)
1728 				*start_ret = prev->end + 1;
1729 			else
1730 				*start_ret = 0;
1731 			break;
1732 		}
1733 	}
1734 
1735 	/*
1736 	 * Find the longest stretch from start until an entry which has the
1737 	 * bits set
1738 	 */
1739 	while (state) {
1740 		if (state->end >= start && !(state->state & bits)) {
1741 			*end_ret = state->end;
1742 		} else {
1743 			*end_ret = state->start - 1;
1744 			break;
1745 		}
1746 		state = next_state(state);
1747 	}
1748 out:
1749 	spin_unlock(&tree->lock);
1750 }
1751 
1752 /*
1753  * Count the number of bytes in the tree that have a given bit(s) set for a
1754  * given range.
1755  *
1756  * @tree:         The io tree to search.
1757  * @start:        The start offset of the range. This value is updated to the
1758  *                offset of the first byte found with the given bit(s), so it
1759  *                can end up being bigger than the initial value.
1760  * @search_end:   The end offset (inclusive value) of the search range.
1761  * @max_bytes:    The maximum byte count we are interested. The search stops
1762  *                once it reaches this count.
1763  * @bits:         The bits the range must have in order to be accounted for.
1764  *                If multiple bits are set, then only subranges that have all
1765  *                the bits set are accounted for.
1766  * @contig:       Indicate if we should ignore holes in the range or not. If
1767  *                this is true, then stop once we find a hole.
1768  * @cached_state: A cached state to be used across multiple calls to this
1769  *                function in order to speedup searches. Use NULL if this is
1770  *                called only once or if each call does not start where the
1771  *                previous one ended.
1772  *
1773  * Returns the total number of bytes found within the given range that have
1774  * all given bits set. If the returned number of bytes is greater than zero
1775  * then @start is updated with the offset of the first byte with the bits set.
1776  */
btrfs_count_range_bits(struct extent_io_tree * tree,u64 * start,u64 search_end,u64 max_bytes,u32 bits,bool contig,struct extent_state ** cached_state)1777 u64 btrfs_count_range_bits(struct extent_io_tree *tree,
1778 			   u64 *start, u64 search_end, u64 max_bytes,
1779 			   u32 bits, bool contig,
1780 			   struct extent_state **cached_state)
1781 {
1782 	struct extent_state *state = NULL;
1783 	struct extent_state *cached;
1784 	u64 cur_start = *start;
1785 	u64 total_bytes = 0;
1786 	u64 last = 0;
1787 	bool found = false;
1788 
1789 	if (WARN_ON(search_end < cur_start))
1790 		return 0;
1791 
1792 	spin_lock(&tree->lock);
1793 
1794 	if (!cached_state || !*cached_state)
1795 		goto search;
1796 
1797 	cached = *cached_state;
1798 
1799 	if (!extent_state_in_tree(cached))
1800 		goto search;
1801 
1802 	if (cached->start <= cur_start && cur_start <= cached->end) {
1803 		state = cached;
1804 	} else if (cached->start > cur_start) {
1805 		struct extent_state *prev;
1806 
1807 		/*
1808 		 * The cached state starts after our search range's start. Check
1809 		 * if the previous state record starts at or before the range we
1810 		 * are looking for, and if so, use it - this is a common case
1811 		 * when there are holes between records in the tree. If there is
1812 		 * no previous state record, we can start from our cached state.
1813 		 */
1814 		prev = prev_state(cached);
1815 		if (!prev)
1816 			state = cached;
1817 		else if (prev->start <= cur_start && cur_start <= prev->end)
1818 			state = prev;
1819 	}
1820 
1821 	/*
1822 	 * This search will find all the extents that end after our range
1823 	 * starts.
1824 	 */
1825 search:
1826 	if (!state)
1827 		state = tree_search(tree, cur_start);
1828 
1829 	while (state) {
1830 		if (state->start > search_end)
1831 			break;
1832 		if (contig && found && state->start > last + 1)
1833 			break;
1834 		if (state->end >= cur_start && (state->state & bits) == bits) {
1835 			total_bytes += min(search_end, state->end) + 1 -
1836 				       max(cur_start, state->start);
1837 			if (total_bytes >= max_bytes)
1838 				break;
1839 			if (!found) {
1840 				*start = max(cur_start, state->start);
1841 				found = true;
1842 			}
1843 			last = state->end;
1844 		} else if (contig && found) {
1845 			break;
1846 		}
1847 		state = next_state(state);
1848 	}
1849 
1850 	if (cached_state) {
1851 		btrfs_free_extent_state(*cached_state);
1852 		*cached_state = state;
1853 		if (state)
1854 			refcount_inc(&state->refs);
1855 	}
1856 
1857 	spin_unlock(&tree->lock);
1858 
1859 	return total_bytes;
1860 }
1861 
1862 /*
1863  * Check if the single @bit exists in the given range.
1864  */
btrfs_test_range_bit_exists(struct extent_io_tree * tree,u64 start,u64 end,u32 bit)1865 bool btrfs_test_range_bit_exists(struct extent_io_tree *tree, u64 start, u64 end, u32 bit)
1866 {
1867 	struct extent_state *state;
1868 	bool bitset = false;
1869 
1870 	ASSERT(is_power_of_2(bit));
1871 
1872 	spin_lock(&tree->lock);
1873 	state = tree_search(tree, start);
1874 	while (state) {
1875 		if (state->start > end)
1876 			break;
1877 
1878 		if (state->state & bit) {
1879 			bitset = true;
1880 			break;
1881 		}
1882 
1883 		if (state->end >= end)
1884 			break;
1885 		state = next_state(state);
1886 	}
1887 	spin_unlock(&tree->lock);
1888 	return bitset;
1889 }
1890 
btrfs_get_range_bits(struct extent_io_tree * tree,u64 start,u64 end,u32 * bits,struct extent_state ** cached_state)1891 void btrfs_get_range_bits(struct extent_io_tree *tree, u64 start, u64 end, u32 *bits,
1892 			  struct extent_state **cached_state)
1893 {
1894 	struct extent_state *state;
1895 
1896 	/*
1897 	 * The cached state is currently mandatory and not used to start the
1898 	 * search, only to cache the first state record found in the range.
1899 	 */
1900 	ASSERT(cached_state != NULL);
1901 	ASSERT(*cached_state == NULL);
1902 
1903 	*bits = 0;
1904 
1905 	spin_lock(&tree->lock);
1906 	state = tree_search(tree, start);
1907 	if (state && state->start < end) {
1908 		*cached_state = state;
1909 		refcount_inc(&state->refs);
1910 	}
1911 	while (state) {
1912 		if (state->start > end)
1913 			break;
1914 
1915 		*bits |= state->state;
1916 
1917 		if (state->end >= end)
1918 			break;
1919 
1920 		state = next_state(state);
1921 	}
1922 	spin_unlock(&tree->lock);
1923 }
1924 
1925 /*
1926  * Check if the whole range [@start,@end) contains the single @bit set.
1927  */
btrfs_test_range_bit(struct extent_io_tree * tree,u64 start,u64 end,u32 bit,struct extent_state * cached)1928 bool btrfs_test_range_bit(struct extent_io_tree *tree, u64 start, u64 end, u32 bit,
1929 			  struct extent_state *cached)
1930 {
1931 	struct extent_state *state;
1932 	bool bitset = true;
1933 
1934 	ASSERT(is_power_of_2(bit));
1935 	ASSERT(start < end);
1936 
1937 	spin_lock(&tree->lock);
1938 	if (cached && extent_state_in_tree(cached) && cached->start <= start &&
1939 	    cached->end > start)
1940 		state = cached;
1941 	else
1942 		state = tree_search(tree, start);
1943 	while (state) {
1944 		if (state->start > start) {
1945 			bitset = false;
1946 			break;
1947 		}
1948 
1949 		if ((state->state & bit) == 0) {
1950 			bitset = false;
1951 			break;
1952 		}
1953 
1954 		if (state->end >= end)
1955 			break;
1956 
1957 		/* Next state must start where this one ends. */
1958 		start = state->end + 1;
1959 		state = next_state(state);
1960 	}
1961 
1962 	/* We ran out of states and were still inside of our range. */
1963 	if (!state)
1964 		bitset = false;
1965 	spin_unlock(&tree->lock);
1966 	return bitset;
1967 }
1968 
1969 /* Wrappers around set/clear extent bit */
btrfs_set_record_extent_bits(struct extent_io_tree * tree,u64 start,u64 end,u32 bits,struct extent_changeset * changeset)1970 int btrfs_set_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1971 				 u32 bits, struct extent_changeset *changeset)
1972 {
1973 	/*
1974 	 * We don't support EXTENT_LOCK_BITS yet, as current changeset will
1975 	 * record any bits changed, so for EXTENT_LOCK_BITS case, it will either
1976 	 * fail with -EEXIST or changeset will record the whole range.
1977 	 */
1978 	ASSERT(!(bits & EXTENT_LOCK_BITS));
1979 
1980 	return set_extent_bit(tree, start, end, bits, NULL, NULL, NULL, changeset);
1981 }
1982 
btrfs_clear_record_extent_bits(struct extent_io_tree * tree,u64 start,u64 end,u32 bits,struct extent_changeset * changeset)1983 int btrfs_clear_record_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1984 				   u32 bits, struct extent_changeset *changeset)
1985 {
1986 	/*
1987 	 * Don't support EXTENT_LOCK_BITS case, same reason as
1988 	 * set_record_extent_bits().
1989 	 */
1990 	ASSERT(!(bits & EXTENT_LOCK_BITS));
1991 
1992 	return btrfs_clear_extent_bit_changeset(tree, start, end, bits, NULL, changeset);
1993 }
1994 
btrfs_try_lock_extent_bits(struct extent_io_tree * tree,u64 start,u64 end,u32 bits,struct extent_state ** cached)1995 bool btrfs_try_lock_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
1996 				u32 bits, struct extent_state **cached)
1997 {
1998 	int ret;
1999 	u64 failed_start;
2000 
2001 	ret = set_extent_bit(tree, start, end, bits, &failed_start, NULL, cached, NULL);
2002 	if (ret == -EEXIST) {
2003 		if (failed_start > start)
2004 			btrfs_clear_extent_bit(tree, start, failed_start - 1,
2005 					       bits, cached);
2006 		return 0;
2007 	}
2008 	return 1;
2009 }
2010 
2011 /*
2012  * Either insert or lock state struct between start and end use mask to tell
2013  * us if waiting is desired.
2014  */
btrfs_lock_extent_bits(struct extent_io_tree * tree,u64 start,u64 end,u32 bits,struct extent_state ** cached_state)2015 int btrfs_lock_extent_bits(struct extent_io_tree *tree, u64 start, u64 end, u32 bits,
2016 			   struct extent_state **cached_state)
2017 {
2018 	struct extent_state *failed_state = NULL;
2019 	int ret;
2020 	u64 failed_start;
2021 
2022 	ret = set_extent_bit(tree, start, end, bits, &failed_start,
2023 			     &failed_state, cached_state, NULL);
2024 	while (ret == -EEXIST) {
2025 		if (failed_start != start)
2026 			btrfs_clear_extent_bit(tree, start, failed_start - 1,
2027 					       bits, cached_state);
2028 
2029 		wait_extent_bit(tree, failed_start, end, bits, &failed_state);
2030 		ret = set_extent_bit(tree, start, end, bits, &failed_start,
2031 				     &failed_state, cached_state, NULL);
2032 	}
2033 	return ret;
2034 }
2035 
2036 /*
2037  * Get the extent state that follows the given extent state.
2038  * This is meant to be used in a context where we know no other tasks can
2039  * concurrently modify the tree.
2040  */
btrfs_next_extent_state(struct extent_io_tree * tree,struct extent_state * state)2041 struct extent_state *btrfs_next_extent_state(struct extent_io_tree *tree,
2042 					     struct extent_state *state)
2043 {
2044 	struct extent_state *next;
2045 
2046 	spin_lock(&tree->lock);
2047 	ASSERT(extent_state_in_tree(state));
2048 	next = next_state(state);
2049 	if (next)
2050 		refcount_inc(&next->refs);
2051 	spin_unlock(&tree->lock);
2052 
2053 	return next;
2054 }
2055 
btrfs_extent_state_free_cachep(void)2056 void __cold btrfs_extent_state_free_cachep(void)
2057 {
2058 	btrfs_extent_state_leak_debug_check();
2059 	kmem_cache_destroy(extent_state_cache);
2060 }
2061 
btrfs_extent_state_init_cachep(void)2062 int __init btrfs_extent_state_init_cachep(void)
2063 {
2064 	extent_state_cache = kmem_cache_create("btrfs_extent_state",
2065 					       sizeof(struct extent_state), 0, 0,
2066 					       NULL);
2067 	if (!extent_state_cache)
2068 		return -ENOMEM;
2069 
2070 	return 0;
2071 }
2072