xref: /linux/fs/btrfs/delayed-ref.c (revision 6b3f7af57881f6d6250c6dcc4d910fe8e855a607)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2009 Oracle.  All rights reserved.
4  */
5 
6 #include <linux/sched.h>
7 #include <linux/slab.h>
8 #include <linux/sort.h>
9 #include "messages.h"
10 #include "ctree.h"
11 #include "delayed-ref.h"
12 #include "extent-tree.h"
13 #include "transaction.h"
14 #include "qgroup.h"
15 #include "space-info.h"
16 #include "tree-mod-log.h"
17 #include "fs.h"
18 
19 struct kmem_cache *btrfs_delayed_ref_head_cachep;
20 struct kmem_cache *btrfs_delayed_ref_node_cachep;
21 struct kmem_cache *btrfs_delayed_extent_op_cachep;
22 /*
23  * delayed back reference update tracking.  For subvolume trees
24  * we queue up extent allocations and backref maintenance for
25  * delayed processing.   This avoids deep call chains where we
26  * add extents in the middle of btrfs_search_slot, and it allows
27  * us to buffer up frequently modified backrefs in an rb tree instead
28  * of hammering updates on the extent allocation tree.
29  */
30 
31 bool btrfs_check_space_for_delayed_refs(struct btrfs_fs_info *fs_info)
32 {
33 	struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
34 	struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
35 	bool ret = false;
36 	u64 reserved;
37 
38 	spin_lock(&global_rsv->lock);
39 	reserved = global_rsv->reserved;
40 	spin_unlock(&global_rsv->lock);
41 
42 	/*
43 	 * Since the global reserve is just kind of magic we don't really want
44 	 * to rely on it to save our bacon, so if our size is more than the
45 	 * delayed_refs_rsv and the global rsv then it's time to think about
46 	 * bailing.
47 	 */
48 	spin_lock(&delayed_refs_rsv->lock);
49 	reserved += delayed_refs_rsv->reserved;
50 	if (delayed_refs_rsv->size >= reserved)
51 		ret = true;
52 	spin_unlock(&delayed_refs_rsv->lock);
53 	return ret;
54 }
55 
56 /*
57  * Release a ref head's reservation.
58  *
59  * @fs_info:  the filesystem
60  * @nr_refs:  number of delayed refs to drop
61  * @nr_csums: number of csum items to drop
62  *
63  * Drops the delayed ref head's count from the delayed refs rsv and free any
64  * excess reservation we had.
65  */
66 void btrfs_delayed_refs_rsv_release(struct btrfs_fs_info *fs_info, int nr_refs, int nr_csums)
67 {
68 	struct btrfs_block_rsv *block_rsv = &fs_info->delayed_refs_rsv;
69 	u64 num_bytes;
70 	u64 released;
71 
72 	num_bytes = btrfs_calc_delayed_ref_bytes(fs_info, nr_refs);
73 	num_bytes += btrfs_calc_delayed_ref_csum_bytes(fs_info, nr_csums);
74 
75 	released = btrfs_block_rsv_release(fs_info, block_rsv, num_bytes, NULL);
76 	if (released)
77 		trace_btrfs_space_reservation(fs_info, "delayed_refs_rsv",
78 					      0, released, 0);
79 }
80 
81 /*
82  * Adjust the size of the delayed refs rsv.
83  *
84  * This is to be called anytime we may have adjusted trans->delayed_ref_updates
85  * or trans->delayed_ref_csum_deletions, it'll calculate the additional size and
86  * add it to the delayed_refs_rsv.
87  */
88 void btrfs_update_delayed_refs_rsv(struct btrfs_trans_handle *trans)
89 {
90 	struct btrfs_fs_info *fs_info = trans->fs_info;
91 	struct btrfs_block_rsv *delayed_rsv = &fs_info->delayed_refs_rsv;
92 	struct btrfs_block_rsv *local_rsv = &trans->delayed_rsv;
93 	u64 num_bytes;
94 	u64 reserved_bytes;
95 
96 	if (btrfs_is_testing(fs_info))
97 		return;
98 
99 	num_bytes = btrfs_calc_delayed_ref_bytes(fs_info, trans->delayed_ref_updates);
100 	num_bytes += btrfs_calc_delayed_ref_csum_bytes(fs_info,
101 						       trans->delayed_ref_csum_deletions);
102 
103 	if (num_bytes == 0)
104 		return;
105 
106 	/*
107 	 * Try to take num_bytes from the transaction's local delayed reserve.
108 	 * If not possible, try to take as much as it's available. If the local
109 	 * reserve doesn't have enough reserved space, the delayed refs reserve
110 	 * will be refilled next time btrfs_delayed_refs_rsv_refill() is called
111 	 * by someone or if a transaction commit is triggered before that, the
112 	 * global block reserve will be used. We want to minimize using the
113 	 * global block reserve for cases we can account for in advance, to
114 	 * avoid exhausting it and reach -ENOSPC during a transaction commit.
115 	 */
116 	spin_lock(&local_rsv->lock);
117 	reserved_bytes = min(num_bytes, local_rsv->reserved);
118 	local_rsv->reserved -= reserved_bytes;
119 	local_rsv->full = (local_rsv->reserved >= local_rsv->size);
120 	spin_unlock(&local_rsv->lock);
121 
122 	spin_lock(&delayed_rsv->lock);
123 	delayed_rsv->size += num_bytes;
124 	delayed_rsv->reserved += reserved_bytes;
125 	delayed_rsv->full = (delayed_rsv->reserved >= delayed_rsv->size);
126 	spin_unlock(&delayed_rsv->lock);
127 	trans->delayed_ref_updates = 0;
128 	trans->delayed_ref_csum_deletions = 0;
129 }
130 
131 /*
132  * Adjust the size of the delayed refs block reserve for 1 block group item
133  * insertion, used after allocating a block group.
134  */
135 void btrfs_inc_delayed_refs_rsv_bg_inserts(struct btrfs_fs_info *fs_info)
136 {
137 	struct btrfs_block_rsv *delayed_rsv = &fs_info->delayed_refs_rsv;
138 
139 	spin_lock(&delayed_rsv->lock);
140 	/*
141 	 * Inserting a block group item does not require changing the free space
142 	 * tree, only the extent tree or the block group tree, so this is all we
143 	 * need.
144 	 */
145 	delayed_rsv->size += btrfs_calc_insert_metadata_size(fs_info, 1);
146 	delayed_rsv->full = false;
147 	spin_unlock(&delayed_rsv->lock);
148 }
149 
150 /*
151  * Adjust the size of the delayed refs block reserve to release space for 1
152  * block group item insertion.
153  */
154 void btrfs_dec_delayed_refs_rsv_bg_inserts(struct btrfs_fs_info *fs_info)
155 {
156 	struct btrfs_block_rsv *delayed_rsv = &fs_info->delayed_refs_rsv;
157 	const u64 num_bytes = btrfs_calc_insert_metadata_size(fs_info, 1);
158 	u64 released;
159 
160 	released = btrfs_block_rsv_release(fs_info, delayed_rsv, num_bytes, NULL);
161 	if (released > 0)
162 		trace_btrfs_space_reservation(fs_info, "delayed_refs_rsv",
163 					      0, released, 0);
164 }
165 
166 /*
167  * Adjust the size of the delayed refs block reserve for 1 block group item
168  * update.
169  */
170 void btrfs_inc_delayed_refs_rsv_bg_updates(struct btrfs_fs_info *fs_info)
171 {
172 	struct btrfs_block_rsv *delayed_rsv = &fs_info->delayed_refs_rsv;
173 
174 	spin_lock(&delayed_rsv->lock);
175 	/*
176 	 * Updating a block group item does not result in new nodes/leaves and
177 	 * does not require changing the free space tree, only the extent tree
178 	 * or the block group tree, so this is all we need.
179 	 */
180 	delayed_rsv->size += btrfs_calc_metadata_size(fs_info, 1);
181 	delayed_rsv->full = false;
182 	spin_unlock(&delayed_rsv->lock);
183 }
184 
185 /*
186  * Adjust the size of the delayed refs block reserve to release space for 1
187  * block group item update.
188  */
189 void btrfs_dec_delayed_refs_rsv_bg_updates(struct btrfs_fs_info *fs_info)
190 {
191 	struct btrfs_block_rsv *delayed_rsv = &fs_info->delayed_refs_rsv;
192 	const u64 num_bytes = btrfs_calc_metadata_size(fs_info, 1);
193 	u64 released;
194 
195 	released = btrfs_block_rsv_release(fs_info, delayed_rsv, num_bytes, NULL);
196 	if (released > 0)
197 		trace_btrfs_space_reservation(fs_info, "delayed_refs_rsv",
198 					      0, released, 0);
199 }
200 
201 /*
202  * Refill based on our delayed refs usage.
203  *
204  * @fs_info: the filesystem
205  * @flush:   control how we can flush for this reservation.
206  *
207  * This will refill the delayed block_rsv up to 1 items size worth of space and
208  * will return -ENOSPC if we can't make the reservation.
209  */
210 static int btrfs_zoned_cap_metadata_reservation(struct btrfs_space_info *space_info)
211 {
212 	struct btrfs_fs_info *fs_info = space_info->fs_info;
213 	struct btrfs_block_rsv *block_rsv = &fs_info->delayed_refs_rsv;
214 	u64 usable;
215 	u64 cap;
216 	int ret = 0;
217 
218 	if (!btrfs_is_zoned(fs_info))
219 		return 0;
220 
221 	spin_lock(&space_info->lock);
222 	usable = space_info->total_bytes - space_info->bytes_zone_unusable;
223 	spin_unlock(&space_info->lock);
224 	cap = usable >> 1;
225 
226 	spin_lock(&block_rsv->lock);
227 	if (block_rsv->size > cap)
228 		ret = -EAGAIN;
229 	spin_unlock(&block_rsv->lock);
230 
231 	return ret;
232 }
233 
234 int btrfs_delayed_refs_rsv_refill(struct btrfs_fs_info *fs_info,
235 				  enum btrfs_reserve_flush_enum flush)
236 {
237 	struct btrfs_block_rsv *block_rsv = &fs_info->delayed_refs_rsv;
238 	struct btrfs_space_info *space_info = block_rsv->space_info;
239 	u64 limit = btrfs_calc_delayed_ref_bytes(fs_info, 1);
240 	u64 num_bytes = 0;
241 	u64 refilled_bytes;
242 	u64 to_free;
243 	int ret = -ENOSPC;
244 
245 	spin_lock(&block_rsv->lock);
246 	if (block_rsv->reserved < block_rsv->size) {
247 		num_bytes = block_rsv->size - block_rsv->reserved;
248 		num_bytes = min(num_bytes, limit);
249 	}
250 	spin_unlock(&block_rsv->lock);
251 
252 	if (!num_bytes)
253 		return 0;
254 
255 	ret = btrfs_zoned_cap_metadata_reservation(space_info);
256 	if (ret)
257 		return ret;
258 
259 	ret = btrfs_reserve_metadata_bytes(space_info, num_bytes, flush);
260 	if (ret)
261 		return ret;
262 
263 	/*
264 	 * We may have raced with someone else, so check again if we the block
265 	 * reserve is still not full and release any excess space.
266 	 */
267 	spin_lock(&block_rsv->lock);
268 	if (block_rsv->reserved < block_rsv->size) {
269 		u64 needed = block_rsv->size - block_rsv->reserved;
270 
271 		if (num_bytes >= needed) {
272 			block_rsv->reserved += needed;
273 			block_rsv->full = true;
274 			to_free = num_bytes - needed;
275 			refilled_bytes = needed;
276 		} else {
277 			block_rsv->reserved += num_bytes;
278 			to_free = 0;
279 			refilled_bytes = num_bytes;
280 		}
281 	} else {
282 		to_free = num_bytes;
283 		refilled_bytes = 0;
284 	}
285 	spin_unlock(&block_rsv->lock);
286 
287 	if (to_free > 0)
288 		btrfs_space_info_free_bytes_may_use(space_info, to_free);
289 
290 	if (refilled_bytes > 0)
291 		trace_btrfs_space_reservation(fs_info, "delayed_refs_rsv", 0,
292 					      refilled_bytes, 1);
293 	return 0;
294 }
295 
296 /*
297  * compare two delayed data backrefs with same bytenr and type
298  */
299 static int comp_data_refs(const struct btrfs_delayed_ref_node *ref1,
300 			  const struct btrfs_delayed_ref_node *ref2)
301 {
302 	if (ref1->data_ref.objectid < ref2->data_ref.objectid)
303 		return -1;
304 	if (ref1->data_ref.objectid > ref2->data_ref.objectid)
305 		return 1;
306 	if (ref1->data_ref.offset < ref2->data_ref.offset)
307 		return -1;
308 	if (ref1->data_ref.offset > ref2->data_ref.offset)
309 		return 1;
310 	return 0;
311 }
312 
313 static int comp_refs(const struct btrfs_delayed_ref_node *ref1,
314 		     const struct btrfs_delayed_ref_node *ref2,
315 		     bool check_seq)
316 {
317 	int ret = 0;
318 
319 	if (ref1->type < ref2->type)
320 		return -1;
321 	if (ref1->type > ref2->type)
322 		return 1;
323 	if (ref1->type == BTRFS_SHARED_BLOCK_REF_KEY ||
324 	    ref1->type == BTRFS_SHARED_DATA_REF_KEY) {
325 		if (ref1->parent < ref2->parent)
326 			return -1;
327 		if (ref1->parent > ref2->parent)
328 			return 1;
329 	} else {
330 		if (ref1->ref_root < ref2->ref_root)
331 			return -1;
332 		if (ref1->ref_root > ref2->ref_root)
333 			return 1;
334 		if (ref1->type == BTRFS_EXTENT_DATA_REF_KEY)
335 			ret = comp_data_refs(ref1, ref2);
336 	}
337 	if (ret)
338 		return ret;
339 	if (check_seq) {
340 		if (ref1->seq < ref2->seq)
341 			return -1;
342 		if (ref1->seq > ref2->seq)
343 			return 1;
344 	}
345 	return 0;
346 }
347 
348 static int cmp_refs_node(const struct rb_node *new, const struct rb_node *exist)
349 {
350 	const struct btrfs_delayed_ref_node *new_node =
351 		rb_entry(new, struct btrfs_delayed_ref_node, ref_node);
352 	const struct btrfs_delayed_ref_node *exist_node =
353 		rb_entry(exist, struct btrfs_delayed_ref_node, ref_node);
354 
355 	return comp_refs(new_node, exist_node, true);
356 }
357 
358 static struct btrfs_delayed_ref_node* tree_insert(struct rb_root_cached *root,
359 		struct btrfs_delayed_ref_node *ins)
360 {
361 	struct rb_node *node = &ins->ref_node;
362 	struct rb_node *exist = rb_find_add_cached(node, root, cmp_refs_node);
363 
364 	return rb_entry_safe(exist, struct btrfs_delayed_ref_node, ref_node);
365 }
366 
367 static struct btrfs_delayed_ref_head *find_first_ref_head(
368 		struct btrfs_delayed_ref_root *dr)
369 {
370 	unsigned long from = 0;
371 
372 	lockdep_assert_held(&dr->lock);
373 
374 	return xa_find(&dr->head_refs, &from, ULONG_MAX, XA_PRESENT);
375 }
376 
377 static bool btrfs_delayed_ref_lock(struct btrfs_delayed_ref_root *delayed_refs,
378 				   struct btrfs_delayed_ref_head *head)
379 {
380 	lockdep_assert_held(&delayed_refs->lock);
381 	if (mutex_trylock(&head->mutex))
382 		return true;
383 
384 	refcount_inc(&head->refs);
385 	spin_unlock(&delayed_refs->lock);
386 
387 	mutex_lock(&head->mutex);
388 	spin_lock(&delayed_refs->lock);
389 	if (!head->tracked) {
390 		mutex_unlock(&head->mutex);
391 		btrfs_put_delayed_ref_head(head);
392 		return false;
393 	}
394 	btrfs_put_delayed_ref_head(head);
395 	return true;
396 }
397 
398 static inline void drop_delayed_ref(struct btrfs_fs_info *fs_info,
399 				    struct btrfs_delayed_ref_root *delayed_refs,
400 				    struct btrfs_delayed_ref_head *head,
401 				    struct btrfs_delayed_ref_node *ref)
402 {
403 	lockdep_assert_held(&head->lock);
404 	rb_erase_cached(&ref->ref_node, &head->ref_tree);
405 	RB_CLEAR_NODE(&ref->ref_node);
406 	if (!list_empty(&ref->add_list))
407 		list_del(&ref->add_list);
408 	btrfs_put_delayed_ref(ref);
409 	btrfs_delayed_refs_rsv_release(fs_info, 1, 0);
410 }
411 
412 static bool merge_ref(struct btrfs_fs_info *fs_info,
413 		      struct btrfs_delayed_ref_root *delayed_refs,
414 		      struct btrfs_delayed_ref_head *head,
415 		      struct btrfs_delayed_ref_node *ref,
416 		      u64 seq)
417 {
418 	struct btrfs_delayed_ref_node *next;
419 	struct rb_node *node = rb_next(&ref->ref_node);
420 	bool done = false;
421 
422 	while (!done && node) {
423 		int mod;
424 
425 		next = rb_entry(node, struct btrfs_delayed_ref_node, ref_node);
426 		node = rb_next(node);
427 		if (seq && next->seq >= seq)
428 			break;
429 		if (comp_refs(ref, next, false))
430 			break;
431 
432 		if (ref->action == next->action) {
433 			mod = next->ref_mod;
434 		} else {
435 			if (ref->ref_mod < next->ref_mod) {
436 				swap(ref, next);
437 				done = true;
438 			}
439 			mod = -next->ref_mod;
440 		}
441 
442 		drop_delayed_ref(fs_info, delayed_refs, head, next);
443 		ref->ref_mod += mod;
444 		if (ref->ref_mod == 0) {
445 			drop_delayed_ref(fs_info, delayed_refs, head, ref);
446 			done = true;
447 		} else {
448 			/*
449 			 * Can't have multiples of the same ref on a tree block.
450 			 */
451 			WARN_ON(ref->type == BTRFS_TREE_BLOCK_REF_KEY ||
452 				ref->type == BTRFS_SHARED_BLOCK_REF_KEY);
453 		}
454 	}
455 
456 	return done;
457 }
458 
459 void btrfs_merge_delayed_refs(struct btrfs_fs_info *fs_info,
460 			      struct btrfs_delayed_ref_root *delayed_refs,
461 			      struct btrfs_delayed_ref_head *head)
462 {
463 	struct btrfs_delayed_ref_node *ref;
464 	struct rb_node *node;
465 	u64 seq = 0;
466 
467 	lockdep_assert_held(&head->lock);
468 
469 	if (RB_EMPTY_ROOT(&head->ref_tree.rb_root))
470 		return;
471 
472 	/* We don't have too many refs to merge for data. */
473 	if (head->is_data)
474 		return;
475 
476 	seq = btrfs_tree_mod_log_lowest_seq(fs_info);
477 again:
478 	for (node = rb_first_cached(&head->ref_tree); node;
479 	     node = rb_next(node)) {
480 		ref = rb_entry(node, struct btrfs_delayed_ref_node, ref_node);
481 		if (seq && ref->seq >= seq)
482 			continue;
483 		if (merge_ref(fs_info, delayed_refs, head, ref, seq))
484 			goto again;
485 	}
486 }
487 
488 int btrfs_check_delayed_seq(struct btrfs_fs_info *fs_info, u64 seq)
489 {
490 	int ret = 0;
491 	u64 min_seq = btrfs_tree_mod_log_lowest_seq(fs_info);
492 
493 	if (min_seq != 0 && seq >= min_seq) {
494 		btrfs_debug(fs_info,
495 			    "holding back delayed_ref %llu, lowest is %llu",
496 			    seq, min_seq);
497 		ret = 1;
498 	}
499 
500 	return ret;
501 }
502 
503 struct btrfs_delayed_ref_head *btrfs_select_ref_head(
504 		const struct btrfs_fs_info *fs_info,
505 		struct btrfs_delayed_ref_root *delayed_refs)
506 {
507 	struct btrfs_delayed_ref_head *head;
508 	unsigned long start_index;
509 	unsigned long found_index;
510 	bool found_head = false;
511 	bool locked;
512 
513 	spin_lock(&delayed_refs->lock);
514 again:
515 	start_index = (delayed_refs->run_delayed_start >> fs_info->sectorsize_bits);
516 	xa_for_each_start(&delayed_refs->head_refs, found_index, head, start_index) {
517 		if (!head->processing) {
518 			found_head = true;
519 			break;
520 		}
521 	}
522 	if (!found_head) {
523 		if (delayed_refs->run_delayed_start == 0) {
524 			spin_unlock(&delayed_refs->lock);
525 			return NULL;
526 		}
527 		delayed_refs->run_delayed_start = 0;
528 		goto again;
529 	}
530 
531 	head->processing = true;
532 	WARN_ON(delayed_refs->num_heads_ready == 0);
533 	delayed_refs->num_heads_ready--;
534 	delayed_refs->run_delayed_start = head->bytenr +
535 		head->num_bytes;
536 
537 	locked = btrfs_delayed_ref_lock(delayed_refs, head);
538 	spin_unlock(&delayed_refs->lock);
539 
540 	/*
541 	 * We may have dropped the spin lock to get the head mutex lock, and
542 	 * that might have given someone else time to free the head.  If that's
543 	 * true, it has been removed from our list and we can move on.
544 	 */
545 	if (!locked)
546 		return ERR_PTR(-EAGAIN);
547 
548 	return head;
549 }
550 
551 void btrfs_unselect_ref_head(struct btrfs_delayed_ref_root *delayed_refs,
552 			     struct btrfs_delayed_ref_head *head)
553 {
554 	spin_lock(&delayed_refs->lock);
555 	head->processing = false;
556 	delayed_refs->num_heads_ready++;
557 	spin_unlock(&delayed_refs->lock);
558 	btrfs_delayed_ref_unlock(head);
559 }
560 
561 void btrfs_delete_ref_head(const struct btrfs_fs_info *fs_info,
562 			   struct btrfs_delayed_ref_root *delayed_refs,
563 			   struct btrfs_delayed_ref_head *head)
564 {
565 	const unsigned long index = (head->bytenr >> fs_info->sectorsize_bits);
566 
567 	lockdep_assert_held(&delayed_refs->lock);
568 	lockdep_assert_held(&head->lock);
569 
570 	xa_erase(&delayed_refs->head_refs, index);
571 	head->tracked = false;
572 	delayed_refs->num_heads--;
573 	if (!head->processing)
574 		delayed_refs->num_heads_ready--;
575 }
576 
577 struct btrfs_delayed_ref_node *btrfs_select_delayed_ref(struct btrfs_delayed_ref_head *head)
578 {
579 	struct btrfs_delayed_ref_node *ref;
580 
581 	lockdep_assert_held(&head->mutex);
582 	lockdep_assert_held(&head->lock);
583 
584 	if (RB_EMPTY_ROOT(&head->ref_tree.rb_root))
585 		return NULL;
586 
587 	/*
588 	 * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
589 	 * This is to prevent a ref count from going down to zero, which deletes
590 	 * the extent item from the extent tree, when there still are references
591 	 * to add, which would fail because they would not find the extent item.
592 	 */
593 	if (!list_empty(&head->ref_add_list))
594 		return list_first_entry(&head->ref_add_list,
595 					struct btrfs_delayed_ref_node, add_list);
596 
597 	ref = rb_entry(rb_first_cached(&head->ref_tree),
598 		       struct btrfs_delayed_ref_node, ref_node);
599 	ASSERT(list_empty(&ref->add_list));
600 	return ref;
601 }
602 
603 /*
604  * Helper to insert the ref_node to the tail or merge with tail.
605  *
606  * Return false if the ref was inserted.
607  * Return true if the ref was merged into an existing one (and therefore can be
608  * freed by the caller).
609  */
610 static bool insert_delayed_ref(struct btrfs_trans_handle *trans,
611 			       struct btrfs_delayed_ref_head *href,
612 			       struct btrfs_delayed_ref_node *ref)
613 {
614 	struct btrfs_delayed_ref_root *root = &trans->transaction->delayed_refs;
615 	struct btrfs_delayed_ref_node *exist;
616 	int mod;
617 
618 	ASSERT(ref->action == BTRFS_ADD_DELAYED_REF ||
619 	       ref->action == BTRFS_DROP_DELAYED_REF);
620 
621 	spin_lock(&href->lock);
622 	exist = tree_insert(&href->ref_tree, ref);
623 	if (!exist) {
624 		if (ref->action == BTRFS_ADD_DELAYED_REF)
625 			list_add_tail(&ref->add_list, &href->ref_add_list);
626 		spin_unlock(&href->lock);
627 		trans->delayed_ref_updates++;
628 		return false;
629 	}
630 
631 	/* Now we are sure we can merge */
632 	if (exist->action == ref->action) {
633 		mod = ref->ref_mod;
634 	} else {
635 		/* Need to change action */
636 		if (exist->ref_mod < ref->ref_mod) {
637 			exist->action = ref->action;
638 			mod = -exist->ref_mod;
639 			exist->ref_mod = ref->ref_mod;
640 			if (ref->action == BTRFS_ADD_DELAYED_REF)
641 				list_add_tail(&exist->add_list,
642 					      &href->ref_add_list);
643 			else if (ref->action == BTRFS_DROP_DELAYED_REF) {
644 				ASSERT(!list_empty(&exist->add_list));
645 				list_del_init(&exist->add_list);
646 			} else {
647 				DEBUG_WARN();
648 			}
649 		} else
650 			mod = -ref->ref_mod;
651 	}
652 	exist->ref_mod += mod;
653 
654 	/* remove existing tail if its ref_mod is zero */
655 	if (exist->ref_mod == 0)
656 		drop_delayed_ref(trans->fs_info, root, href, exist);
657 	spin_unlock(&href->lock);
658 	return true;
659 }
660 
661 /*
662  * helper function to update the accounting in the head ref
663  * existing and update must have the same bytenr
664  */
665 static noinline void update_existing_head_ref(struct btrfs_trans_handle *trans,
666 			 struct btrfs_delayed_ref_head *existing,
667 			 struct btrfs_delayed_ref_head *update)
668 {
669 	struct btrfs_delayed_ref_root *delayed_refs =
670 		&trans->transaction->delayed_refs;
671 	struct btrfs_fs_info *fs_info = trans->fs_info;
672 	int old_ref_mod;
673 
674 	BUG_ON(existing->is_data != update->is_data);
675 
676 	spin_lock(&existing->lock);
677 
678 	/*
679 	 * When freeing an extent, we may not know the owning root when we
680 	 * first create the head_ref. However, some deref before the last deref
681 	 * will know it, so we just need to update the head_ref accordingly.
682 	 */
683 	if (!existing->owning_root)
684 		existing->owning_root = update->owning_root;
685 
686 	if (update->must_insert_reserved) {
687 		/* if the extent was freed and then
688 		 * reallocated before the delayed ref
689 		 * entries were processed, we can end up
690 		 * with an existing head ref without
691 		 * the must_insert_reserved flag set.
692 		 * Set it again here
693 		 */
694 		existing->must_insert_reserved = update->must_insert_reserved;
695 		existing->owning_root = update->owning_root;
696 
697 		/*
698 		 * update the num_bytes so we make sure the accounting
699 		 * is done correctly
700 		 */
701 		existing->num_bytes = update->num_bytes;
702 
703 	}
704 
705 	if (update->extent_op) {
706 		if (!existing->extent_op) {
707 			existing->extent_op = update->extent_op;
708 		} else {
709 			if (update->extent_op->update_key) {
710 				memcpy(&existing->extent_op->key,
711 				       &update->extent_op->key,
712 				       sizeof(update->extent_op->key));
713 				existing->extent_op->update_key = true;
714 			}
715 			if (update->extent_op->update_flags) {
716 				existing->extent_op->flags_to_set |=
717 					update->extent_op->flags_to_set;
718 				existing->extent_op->update_flags = true;
719 			}
720 			btrfs_free_delayed_extent_op(update->extent_op);
721 		}
722 	}
723 	/*
724 	 * update the reference mod on the head to reflect this new operation,
725 	 * only need the lock for this case cause we could be processing it
726 	 * currently, for refs we just added we know we're a-ok.
727 	 */
728 	old_ref_mod = existing->total_ref_mod;
729 	existing->ref_mod += update->ref_mod;
730 	existing->total_ref_mod += update->ref_mod;
731 
732 	/*
733 	 * If we are going to from a positive ref mod to a negative or vice
734 	 * versa we need to make sure to adjust pending_csums accordingly.
735 	 * We reserve bytes for csum deletion when adding or updating a ref head
736 	 * see add_delayed_ref_head() for more details.
737 	 */
738 	if (existing->is_data) {
739 		u64 csum_leaves =
740 			btrfs_csum_bytes_to_leaves(fs_info,
741 						   existing->num_bytes);
742 
743 		if (existing->total_ref_mod >= 0 && old_ref_mod < 0) {
744 			delayed_refs->pending_csums -= existing->num_bytes;
745 			btrfs_delayed_refs_rsv_release(fs_info, 0, csum_leaves);
746 		}
747 		if (existing->total_ref_mod < 0 && old_ref_mod >= 0) {
748 			delayed_refs->pending_csums += existing->num_bytes;
749 			trans->delayed_ref_csum_deletions += csum_leaves;
750 		}
751 	}
752 
753 	spin_unlock(&existing->lock);
754 }
755 
756 static void init_delayed_ref_head(struct btrfs_delayed_ref_head *head_ref,
757 				  struct btrfs_ref *generic_ref,
758 				  struct btrfs_qgroup_extent_record *qrecord,
759 				  u64 reserved)
760 {
761 	int count_mod = 1;
762 	bool must_insert_reserved = false;
763 
764 	/* If reserved is provided, it must be a data extent. */
765 	BUG_ON(generic_ref->type != BTRFS_REF_DATA && reserved);
766 
767 	switch (generic_ref->action) {
768 	case BTRFS_ADD_DELAYED_REF:
769 		/* count_mod is already set to 1. */
770 		break;
771 	case BTRFS_UPDATE_DELAYED_HEAD:
772 		count_mod = 0;
773 		break;
774 	case BTRFS_DROP_DELAYED_REF:
775 		/*
776 		 * The head node stores the sum of all the mods, so dropping a ref
777 		 * should drop the sum in the head node by one.
778 		 */
779 		count_mod = -1;
780 		break;
781 	case BTRFS_ADD_DELAYED_EXTENT:
782 		/*
783 		 * BTRFS_ADD_DELAYED_EXTENT means that we need to update the
784 		 * reserved accounting when the extent is finally added, or if a
785 		 * later modification deletes the delayed ref without ever
786 		 * inserting the extent into the extent allocation tree.
787 		 * ref->must_insert_reserved is the flag used to record that
788 		 * accounting mods are required.
789 		 *
790 		 * Once we record must_insert_reserved, switch the action to
791 		 * BTRFS_ADD_DELAYED_REF because other special casing is not
792 		 * required.
793 		 */
794 		must_insert_reserved = true;
795 		break;
796 	}
797 
798 	refcount_set(&head_ref->refs, 1);
799 	head_ref->bytenr = generic_ref->bytenr;
800 	head_ref->num_bytes = generic_ref->num_bytes;
801 	head_ref->ref_mod = count_mod;
802 	head_ref->reserved_bytes = reserved;
803 	head_ref->must_insert_reserved = must_insert_reserved;
804 	head_ref->owning_root = generic_ref->owning_root;
805 	head_ref->is_data = (generic_ref->type == BTRFS_REF_DATA);
806 	head_ref->is_system = (generic_ref->ref_root == BTRFS_CHUNK_TREE_OBJECTID);
807 	head_ref->ref_tree = RB_ROOT_CACHED;
808 	INIT_LIST_HEAD(&head_ref->ref_add_list);
809 	head_ref->tracked = false;
810 	head_ref->processing = false;
811 	head_ref->total_ref_mod = count_mod;
812 	spin_lock_init(&head_ref->lock);
813 	mutex_init(&head_ref->mutex);
814 
815 	/* If not metadata set an impossible level to help debugging. */
816 	if (generic_ref->type == BTRFS_REF_METADATA)
817 		head_ref->level = generic_ref->tree_ref.level;
818 	else
819 		head_ref->level = U8_MAX;
820 
821 	if (qrecord) {
822 		if (generic_ref->ref_root && reserved) {
823 			qrecord->data_rsv = reserved;
824 			qrecord->data_rsv_refroot = generic_ref->ref_root;
825 		}
826 		qrecord->num_bytes = generic_ref->num_bytes;
827 		qrecord->old_roots = NULL;
828 	}
829 }
830 
831 /*
832  * Helper function to actually insert a head node into the xarray. This does all
833  * the dirty work in terms of maintaining the correct overall modification
834  * count.
835  *
836  * The caller is responsible for calling kfree() on @qrecord. More specifically,
837  * if this function reports that it did not insert it as noted in
838  * @qrecord_inserted_ret, then it's safe to call kfree() on it.
839  *
840  * Returns an error pointer in case of an error.
841  */
842 static noinline struct btrfs_delayed_ref_head *
843 add_delayed_ref_head(struct btrfs_trans_handle *trans,
844 		     struct btrfs_delayed_ref_head *head_ref,
845 		     struct btrfs_qgroup_extent_record *qrecord,
846 		     int action, bool *qrecord_inserted_ret)
847 {
848 	struct btrfs_fs_info *fs_info = trans->fs_info;
849 	struct btrfs_delayed_ref_head *existing;
850 	struct btrfs_delayed_ref_root *delayed_refs;
851 	const unsigned long index = (head_ref->bytenr >> fs_info->sectorsize_bits);
852 
853 	/*
854 	 * If 'qrecord_inserted_ret' is provided, then the first thing we need
855 	 * to do is to initialize it to false just in case we have an exit
856 	 * before trying to insert the record.
857 	 */
858 	if (qrecord_inserted_ret)
859 		*qrecord_inserted_ret = false;
860 
861 	delayed_refs = &trans->transaction->delayed_refs;
862 	lockdep_assert_held(&delayed_refs->lock);
863 
864 #if BITS_PER_LONG == 32
865 	if (head_ref->bytenr >= MAX_LFS_FILESIZE) {
866 		if (qrecord)
867 			xa_release(&delayed_refs->dirty_extents, index);
868 		btrfs_err_rl(fs_info,
869 "delayed ref head %llu is beyond 32bit page cache and xarray index limit",
870 			     head_ref->bytenr);
871 		btrfs_err_32bit_limit(fs_info);
872 		return ERR_PTR(-EOVERFLOW);
873 	}
874 #endif
875 
876 	/* Record qgroup extent info if provided */
877 	if (qrecord) {
878 		/*
879 		 * Setting 'qrecord' but not 'qrecord_inserted_ret' will likely
880 		 * result in a memory leakage.
881 		 */
882 		ASSERT(qrecord_inserted_ret != NULL);
883 
884 		int ret;
885 
886 		ret = btrfs_qgroup_trace_extent_nolock(fs_info, delayed_refs, qrecord,
887 						       head_ref->bytenr);
888 		if (ret) {
889 			/* Clean up if insertion fails or item exists. */
890 			xa_release(&delayed_refs->dirty_extents, index);
891 			if (ret < 0)
892 				return ERR_PTR(ret);
893 		} else if (qrecord_inserted_ret) {
894 			*qrecord_inserted_ret = true;
895 		}
896 	}
897 
898 	trace_add_delayed_ref_head(fs_info, head_ref, action);
899 
900 	existing = xa_load(&delayed_refs->head_refs, index);
901 	if (existing) {
902 		update_existing_head_ref(trans, existing, head_ref);
903 		/*
904 		 * we've updated the existing ref, free the newly
905 		 * allocated ref
906 		 */
907 		kmem_cache_free(btrfs_delayed_ref_head_cachep, head_ref);
908 		head_ref = existing;
909 	} else {
910 		existing = xa_store(&delayed_refs->head_refs, index, head_ref, GFP_ATOMIC);
911 		if (xa_is_err(existing)) {
912 			/* Memory was preallocated by the caller. */
913 			ASSERT(xa_err(existing) != -ENOMEM);
914 			return ERR_PTR(xa_err(existing));
915 		} else if (WARN_ON(existing)) {
916 			/*
917 			 * Shouldn't happen we just did a lookup before under
918 			 * delayed_refs->lock.
919 			 */
920 			return ERR_PTR(-EEXIST);
921 		}
922 		head_ref->tracked = true;
923 		/*
924 		 * We reserve the amount of bytes needed to delete csums when
925 		 * adding the ref head and not when adding individual drop refs
926 		 * since the csum items are deleted only after running the last
927 		 * delayed drop ref (the data extent's ref count drops to 0).
928 		 */
929 		if (head_ref->is_data && head_ref->ref_mod < 0) {
930 			delayed_refs->pending_csums += head_ref->num_bytes;
931 			trans->delayed_ref_csum_deletions +=
932 				btrfs_csum_bytes_to_leaves(fs_info, head_ref->num_bytes);
933 		}
934 		delayed_refs->num_heads++;
935 		delayed_refs->num_heads_ready++;
936 	}
937 
938 	return head_ref;
939 }
940 
941 /*
942  * Initialize the structure which represents a modification to an extent.
943  *
944  * @fs_info:    Internal to the mounted filesystem mount structure.
945  *
946  * @ref:	The structure which is going to be initialized.
947  *
948  * @bytenr:	The logical address of the extent for which a modification is
949  *		going to be recorded.
950  *
951  * @num_bytes:  Size of the extent whose modification is being recorded.
952  *
953  * @ref_root:	The id of the root where this modification has originated, this
954  *		can be either one of the well-known metadata trees or the
955  *		subvolume id which references this extent.
956  *
957  * @action:	Can be one of BTRFS_ADD_DELAYED_REF/BTRFS_DROP_DELAYED_REF or
958  *		BTRFS_ADD_DELAYED_EXTENT
959  *
960  * @ref_type:	Holds the type of the extent which is being recorded, can be
961  *		one of BTRFS_SHARED_BLOCK_REF_KEY/BTRFS_TREE_BLOCK_REF_KEY
962  *		when recording a metadata extent or BTRFS_SHARED_DATA_REF_KEY/
963  *		BTRFS_EXTENT_DATA_REF_KEY when recording data extent
964  */
965 static void init_delayed_ref_common(struct btrfs_fs_info *fs_info,
966 				    struct btrfs_delayed_ref_node *ref,
967 				    struct btrfs_ref *generic_ref)
968 {
969 	int action = generic_ref->action;
970 	u64 seq = 0;
971 
972 	if (action == BTRFS_ADD_DELAYED_EXTENT)
973 		action = BTRFS_ADD_DELAYED_REF;
974 
975 	if (btrfs_is_fstree(generic_ref->ref_root))
976 		seq = atomic64_read(&fs_info->tree_mod_seq);
977 
978 	refcount_set(&ref->refs, 1);
979 	ref->bytenr = generic_ref->bytenr;
980 	ref->num_bytes = generic_ref->num_bytes;
981 	ref->ref_mod = 1;
982 	ref->action = action;
983 	ref->seq = seq;
984 	ref->type = btrfs_ref_type(generic_ref);
985 	ref->ref_root = generic_ref->ref_root;
986 	ref->parent = generic_ref->parent;
987 	RB_CLEAR_NODE(&ref->ref_node);
988 	INIT_LIST_HEAD(&ref->add_list);
989 
990 	if (generic_ref->type == BTRFS_REF_DATA)
991 		ref->data_ref = generic_ref->data_ref;
992 	else
993 		ref->tree_ref = generic_ref->tree_ref;
994 }
995 
996 void btrfs_init_tree_ref(struct btrfs_ref *generic_ref, int level, u64 mod_root,
997 			 bool skip_qgroup)
998 {
999 #ifdef CONFIG_BTRFS_DEBUG
1000 	/* If @real_root not set, use @root as fallback */
1001 	generic_ref->real_root = mod_root ?: generic_ref->ref_root;
1002 #endif
1003 	generic_ref->tree_ref.level = level;
1004 	generic_ref->type = BTRFS_REF_METADATA;
1005 	if (skip_qgroup || !(btrfs_is_fstree(generic_ref->ref_root) &&
1006 			     (!mod_root || btrfs_is_fstree(mod_root))))
1007 		generic_ref->skip_qgroup = true;
1008 	else
1009 		generic_ref->skip_qgroup = false;
1010 
1011 }
1012 
1013 void btrfs_init_data_ref(struct btrfs_ref *generic_ref, u64 ino, u64 offset,
1014 			 u64 mod_root, bool skip_qgroup)
1015 {
1016 #ifdef CONFIG_BTRFS_DEBUG
1017 	/* If @real_root not set, use @root as fallback */
1018 	generic_ref->real_root = mod_root ?: generic_ref->ref_root;
1019 #endif
1020 	generic_ref->data_ref.objectid = ino;
1021 	generic_ref->data_ref.offset = offset;
1022 	generic_ref->type = BTRFS_REF_DATA;
1023 	if (skip_qgroup || !(btrfs_is_fstree(generic_ref->ref_root) &&
1024 			     (!mod_root || btrfs_is_fstree(mod_root))))
1025 		generic_ref->skip_qgroup = true;
1026 	else
1027 		generic_ref->skip_qgroup = false;
1028 }
1029 
1030 static int add_delayed_ref(struct btrfs_trans_handle *trans,
1031 			   struct btrfs_ref *generic_ref,
1032 			   struct btrfs_delayed_extent_op *extent_op,
1033 			   u64 reserved)
1034 {
1035 	struct btrfs_fs_info *fs_info = trans->fs_info;
1036 	struct btrfs_delayed_ref_node *node;
1037 	struct btrfs_delayed_ref_head *head_ref;
1038 	struct btrfs_delayed_ref_head *new_head_ref;
1039 	struct btrfs_delayed_ref_root *delayed_refs;
1040 	struct btrfs_qgroup_extent_record *record = NULL;
1041 	const unsigned long index = (generic_ref->bytenr >> fs_info->sectorsize_bits);
1042 	bool qrecord_reserved = false;
1043 	bool qrecord_inserted;
1044 	int action = generic_ref->action;
1045 	bool merged;
1046 	int ret;
1047 
1048 	node = kmem_cache_alloc(btrfs_delayed_ref_node_cachep, GFP_NOFS);
1049 	if (!node)
1050 		return -ENOMEM;
1051 
1052 	head_ref = kmem_cache_alloc(btrfs_delayed_ref_head_cachep, GFP_NOFS);
1053 	if (!head_ref) {
1054 		ret = -ENOMEM;
1055 		goto free_node;
1056 	}
1057 
1058 	delayed_refs = &trans->transaction->delayed_refs;
1059 
1060 	if (btrfs_qgroup_full_accounting(fs_info) && !generic_ref->skip_qgroup) {
1061 		record = kzalloc_obj(*record, GFP_NOFS);
1062 		if (!record) {
1063 			ret = -ENOMEM;
1064 			goto free_head_ref;
1065 		}
1066 		if (xa_reserve(&delayed_refs->dirty_extents, index, GFP_NOFS)) {
1067 			ret = -ENOMEM;
1068 			goto free_record;
1069 		}
1070 		qrecord_reserved = true;
1071 	}
1072 
1073 	ret = xa_reserve(&delayed_refs->head_refs, index, GFP_NOFS);
1074 	if (ret) {
1075 		if (qrecord_reserved)
1076 			xa_release(&delayed_refs->dirty_extents, index);
1077 		goto free_record;
1078 	}
1079 
1080 	init_delayed_ref_common(fs_info, node, generic_ref);
1081 	init_delayed_ref_head(head_ref, generic_ref, record, reserved);
1082 	head_ref->extent_op = extent_op;
1083 
1084 	spin_lock(&delayed_refs->lock);
1085 
1086 	/*
1087 	 * insert both the head node and the new ref without dropping
1088 	 * the spin lock
1089 	 */
1090 	new_head_ref = add_delayed_ref_head(trans, head_ref, record,
1091 					    action, &qrecord_inserted);
1092 	if (IS_ERR(new_head_ref)) {
1093 		xa_release(&delayed_refs->head_refs, index);
1094 		spin_unlock(&delayed_refs->lock);
1095 		ret = PTR_ERR(new_head_ref);
1096 
1097 		/*
1098 		 * It's only safe to call kfree() on 'qrecord' if
1099 		 * add_delayed_ref_head() has _not_ inserted it for
1100 		 * tracing. Otherwise we need to handle this here.
1101 		 */
1102 		if (!qrecord_reserved || qrecord_inserted)
1103 			goto free_head_ref;
1104 		goto free_record;
1105 	}
1106 	head_ref = new_head_ref;
1107 
1108 	merged = insert_delayed_ref(trans, head_ref, node);
1109 	spin_unlock(&delayed_refs->lock);
1110 
1111 	/*
1112 	 * Need to update the delayed_refs_rsv with any changes we may have
1113 	 * made.
1114 	 */
1115 	btrfs_update_delayed_refs_rsv(trans);
1116 
1117 	if (generic_ref->type == BTRFS_REF_DATA)
1118 		trace_add_delayed_data_ref(trans->fs_info, node);
1119 	else
1120 		trace_add_delayed_tree_ref(trans->fs_info, node);
1121 	if (merged)
1122 		kmem_cache_free(btrfs_delayed_ref_node_cachep, node);
1123 
1124 	if (qrecord_inserted)
1125 		return btrfs_qgroup_trace_extent_post(trans, record, generic_ref->bytenr);
1126 
1127 	kfree(record);
1128 	return 0;
1129 
1130 free_record:
1131 	kfree(record);
1132 free_head_ref:
1133 	kmem_cache_free(btrfs_delayed_ref_head_cachep, head_ref);
1134 free_node:
1135 	kmem_cache_free(btrfs_delayed_ref_node_cachep, node);
1136 	return ret;
1137 }
1138 
1139 /*
1140  * Add a delayed tree ref. This does all of the accounting required to make sure
1141  * the delayed ref is eventually processed before this transaction commits.
1142  */
1143 int btrfs_add_delayed_tree_ref(struct btrfs_trans_handle *trans,
1144 			       struct btrfs_ref *generic_ref,
1145 			       struct btrfs_delayed_extent_op *extent_op)
1146 {
1147 	ASSERT(generic_ref->type == BTRFS_REF_METADATA && generic_ref->action);
1148 	return add_delayed_ref(trans, generic_ref, extent_op, 0);
1149 }
1150 
1151 /*
1152  * add a delayed data ref. it's similar to btrfs_add_delayed_tree_ref.
1153  */
1154 int btrfs_add_delayed_data_ref(struct btrfs_trans_handle *trans,
1155 			       struct btrfs_ref *generic_ref,
1156 			       u64 reserved)
1157 {
1158 	ASSERT(generic_ref->type == BTRFS_REF_DATA && generic_ref->action);
1159 	return add_delayed_ref(trans, generic_ref, NULL, reserved);
1160 }
1161 
1162 int btrfs_add_delayed_extent_op(struct btrfs_trans_handle *trans,
1163 				u64 bytenr, u64 num_bytes, u8 level,
1164 				struct btrfs_delayed_extent_op *extent_op)
1165 {
1166 	const unsigned long index = (bytenr >> trans->fs_info->sectorsize_bits);
1167 	struct btrfs_delayed_ref_head *head_ref;
1168 	struct btrfs_delayed_ref_head *head_ref_ret;
1169 	struct btrfs_delayed_ref_root *delayed_refs;
1170 	struct btrfs_ref generic_ref = {
1171 		.type = BTRFS_REF_METADATA,
1172 		.action = BTRFS_UPDATE_DELAYED_HEAD,
1173 		.bytenr = bytenr,
1174 		.num_bytes = num_bytes,
1175 		.tree_ref.level = level,
1176 	};
1177 	int ret;
1178 
1179 	head_ref = kmem_cache_alloc(btrfs_delayed_ref_head_cachep, GFP_NOFS);
1180 	if (!head_ref)
1181 		return -ENOMEM;
1182 
1183 	init_delayed_ref_head(head_ref, &generic_ref, NULL, 0);
1184 	head_ref->extent_op = extent_op;
1185 
1186 	delayed_refs = &trans->transaction->delayed_refs;
1187 
1188 	ret = xa_reserve(&delayed_refs->head_refs, index, GFP_NOFS);
1189 	if (ret) {
1190 		kmem_cache_free(btrfs_delayed_ref_head_cachep, head_ref);
1191 		return ret;
1192 	}
1193 
1194 	spin_lock(&delayed_refs->lock);
1195 	head_ref_ret = add_delayed_ref_head(trans, head_ref, NULL,
1196 					    BTRFS_UPDATE_DELAYED_HEAD, NULL);
1197 	if (IS_ERR(head_ref_ret)) {
1198 		xa_release(&delayed_refs->head_refs, index);
1199 		spin_unlock(&delayed_refs->lock);
1200 		kmem_cache_free(btrfs_delayed_ref_head_cachep, head_ref);
1201 		return PTR_ERR(head_ref_ret);
1202 	}
1203 	spin_unlock(&delayed_refs->lock);
1204 
1205 	/*
1206 	 * Need to update the delayed_refs_rsv with any changes we may have
1207 	 * made.
1208 	 */
1209 	btrfs_update_delayed_refs_rsv(trans);
1210 	return 0;
1211 }
1212 
1213 void btrfs_put_delayed_ref(struct btrfs_delayed_ref_node *ref)
1214 {
1215 	if (refcount_dec_and_test(&ref->refs)) {
1216 		WARN_ON(!RB_EMPTY_NODE(&ref->ref_node));
1217 		kmem_cache_free(btrfs_delayed_ref_node_cachep, ref);
1218 	}
1219 }
1220 
1221 /*
1222  * This does a simple search for the head node for a given extent.  Returns the
1223  * head node if found, or NULL if not.
1224  */
1225 struct btrfs_delayed_ref_head *
1226 btrfs_find_delayed_ref_head(const struct btrfs_fs_info *fs_info,
1227 			    struct btrfs_delayed_ref_root *delayed_refs,
1228 			    u64 bytenr)
1229 {
1230 	const unsigned long index = (bytenr >> fs_info->sectorsize_bits);
1231 
1232 	lockdep_assert_held(&delayed_refs->lock);
1233 
1234 	return xa_load(&delayed_refs->head_refs, index);
1235 }
1236 
1237 static int find_comp(struct btrfs_delayed_ref_node *entry, u64 root, u64 parent)
1238 {
1239 	int type = parent ? BTRFS_SHARED_BLOCK_REF_KEY : BTRFS_TREE_BLOCK_REF_KEY;
1240 
1241 	if (type < entry->type)
1242 		return -1;
1243 	if (type > entry->type)
1244 		return 1;
1245 
1246 	if (type == BTRFS_TREE_BLOCK_REF_KEY) {
1247 		if (root < entry->ref_root)
1248 			return -1;
1249 		if (root > entry->ref_root)
1250 			return 1;
1251 	} else {
1252 		if (parent < entry->parent)
1253 			return -1;
1254 		if (parent > entry->parent)
1255 			return 1;
1256 	}
1257 	return 0;
1258 }
1259 
1260 /*
1261  * Check to see if a given root/parent reference is attached to the head.  This
1262  * only checks for BTRFS_ADD_DELAYED_REF references that match, as that
1263  * indicates the reference exists for the given root or parent.  This is for
1264  * tree blocks only.
1265  *
1266  * @head: the head of the bytenr we're searching.
1267  * @root: the root objectid of the reference if it is a normal reference.
1268  * @parent: the parent if this is a shared backref.
1269  */
1270 bool btrfs_find_delayed_tree_ref(struct btrfs_delayed_ref_head *head,
1271 				 u64 root, u64 parent)
1272 {
1273 	struct rb_node *node;
1274 	bool found = false;
1275 
1276 	lockdep_assert_held(&head->mutex);
1277 
1278 	spin_lock(&head->lock);
1279 	node = head->ref_tree.rb_root.rb_node;
1280 	while (node) {
1281 		struct btrfs_delayed_ref_node *entry;
1282 		int ret;
1283 
1284 		entry = rb_entry(node, struct btrfs_delayed_ref_node, ref_node);
1285 		ret = find_comp(entry, root, parent);
1286 		if (ret < 0) {
1287 			node = node->rb_left;
1288 		} else if (ret > 0) {
1289 			node = node->rb_right;
1290 		} else {
1291 			/*
1292 			 * We only want to count ADD actions, as drops mean the
1293 			 * ref doesn't exist.
1294 			 */
1295 			if (entry->action == BTRFS_ADD_DELAYED_REF)
1296 				found = true;
1297 			break;
1298 		}
1299 	}
1300 	spin_unlock(&head->lock);
1301 	return found;
1302 }
1303 
1304 void btrfs_destroy_delayed_refs(struct btrfs_transaction *trans)
1305 {
1306 	struct btrfs_delayed_ref_root *delayed_refs = &trans->delayed_refs;
1307 	struct btrfs_fs_info *fs_info = trans->fs_info;
1308 
1309 	spin_lock(&delayed_refs->lock);
1310 	while (true) {
1311 		struct btrfs_delayed_ref_head *head;
1312 		struct rb_node *n;
1313 		bool pin_bytes = false;
1314 
1315 		head = find_first_ref_head(delayed_refs);
1316 		if (!head)
1317 			break;
1318 
1319 		if (!btrfs_delayed_ref_lock(delayed_refs, head))
1320 			continue;
1321 
1322 		spin_lock(&head->lock);
1323 		while ((n = rb_first_cached(&head->ref_tree)) != NULL) {
1324 			struct btrfs_delayed_ref_node *ref;
1325 
1326 			ref = rb_entry(n, struct btrfs_delayed_ref_node, ref_node);
1327 			drop_delayed_ref(fs_info, delayed_refs, head, ref);
1328 		}
1329 		if (head->must_insert_reserved)
1330 			pin_bytes = true;
1331 		btrfs_free_delayed_extent_op(head->extent_op);
1332 		btrfs_delete_ref_head(fs_info, delayed_refs, head);
1333 		spin_unlock(&head->lock);
1334 		spin_unlock(&delayed_refs->lock);
1335 		mutex_unlock(&head->mutex);
1336 
1337 		if (!btrfs_is_testing(fs_info) && pin_bytes) {
1338 			struct btrfs_block_group *bg;
1339 
1340 			bg = btrfs_lookup_block_group(fs_info, head->bytenr);
1341 			if (WARN_ON_ONCE(bg == NULL)) {
1342 				/*
1343 				 * Unexpected and there's nothing we can do here
1344 				 * because we are in a transaction abort path,
1345 				 * so any errors can only be ignored or reported
1346 				 * while attempting to cleanup all resources.
1347 				 */
1348 				btrfs_err(fs_info,
1349 "block group for delayed ref at %llu was not found while destroying ref head",
1350 					  head->bytenr);
1351 			} else {
1352 				spin_lock(&bg->space_info->lock);
1353 				spin_lock(&bg->lock);
1354 				bg->pinned += head->num_bytes;
1355 				btrfs_space_info_update_bytes_pinned(bg->space_info,
1356 								     head->num_bytes);
1357 				bg->reserved -= head->num_bytes;
1358 				bg->space_info->bytes_reserved -= head->num_bytes;
1359 				spin_unlock(&bg->lock);
1360 				spin_unlock(&bg->space_info->lock);
1361 
1362 				btrfs_put_block_group(bg);
1363 			}
1364 
1365 			btrfs_error_unpin_extent_range(fs_info, head->bytenr,
1366 				head->bytenr + head->num_bytes - 1);
1367 		}
1368 		if (!btrfs_is_testing(fs_info))
1369 			btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
1370 		btrfs_put_delayed_ref_head(head);
1371 		cond_resched();
1372 		spin_lock(&delayed_refs->lock);
1373 	}
1374 
1375 	if (!btrfs_is_testing(fs_info))
1376 		btrfs_qgroup_destroy_extent_records(trans);
1377 
1378 	spin_unlock(&delayed_refs->lock);
1379 }
1380 
1381 void __cold btrfs_delayed_ref_exit(void)
1382 {
1383 	kmem_cache_destroy(btrfs_delayed_ref_head_cachep);
1384 	kmem_cache_destroy(btrfs_delayed_ref_node_cachep);
1385 	kmem_cache_destroy(btrfs_delayed_extent_op_cachep);
1386 }
1387 
1388 int __init btrfs_delayed_ref_init(void)
1389 {
1390 	btrfs_delayed_ref_head_cachep = KMEM_CACHE(btrfs_delayed_ref_head, 0);
1391 	if (!btrfs_delayed_ref_head_cachep)
1392 		return -ENOMEM;
1393 
1394 	btrfs_delayed_ref_node_cachep = KMEM_CACHE(btrfs_delayed_ref_node, 0);
1395 	if (!btrfs_delayed_ref_node_cachep)
1396 		goto fail;
1397 
1398 	btrfs_delayed_extent_op_cachep = KMEM_CACHE(btrfs_delayed_extent_op, 0);
1399 	if (!btrfs_delayed_extent_op_cachep)
1400 		goto fail;
1401 
1402 	return 0;
1403 fail:
1404 	btrfs_delayed_ref_exit();
1405 	return -ENOMEM;
1406 }
1407