1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/sched.h>
7 #include <linux/sched/signal.h>
8 #include <linux/pagemap.h>
9 #include <linux/writeback.h>
10 #include <linux/blkdev.h>
11 #include <linux/sort.h>
12 #include <linux/rcupdate.h>
13 #include <linux/kthread.h>
14 #include <linux/slab.h>
15 #include <linux/ratelimit.h>
16 #include <linux/percpu_counter.h>
17 #include <linux/lockdep.h>
18 #include <linux/crc32c.h>
21 #include "print-tree.h"
25 #include "free-space-cache.h"
26 #include "free-space-tree.h"
30 #include "ref-verify.h"
31 #include "space-info.h"
33 #undef SCRAMBLE_DELAYED_REFS
36 * Declare a helper function to detect underflow of various space info members
38 #define DECLARE_SPACE_INFO_UPDATE(name) \
39 static inline void update_##name(struct btrfs_fs_info *fs_info, \
40 struct btrfs_space_info *sinfo, \
43 lockdep_assert_held(&sinfo->lock); \
44 trace_update_##name(fs_info, sinfo, sinfo->name, bytes); \
45 if (bytes < 0 && sinfo->name < -bytes) { \
50 sinfo->name += bytes; \
53 DECLARE_SPACE_INFO_UPDATE(bytes_may_use);
54 DECLARE_SPACE_INFO_UPDATE(bytes_pinned);
56 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
57 struct btrfs_delayed_ref_node *node, u64 parent,
58 u64 root_objectid, u64 owner_objectid,
59 u64 owner_offset, int refs_to_drop,
60 struct btrfs_delayed_extent_op *extra_op);
61 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
62 struct extent_buffer *leaf,
63 struct btrfs_extent_item *ei);
64 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
65 u64 parent, u64 root_objectid,
66 u64 flags, u64 owner, u64 offset,
67 struct btrfs_key *ins, int ref_mod);
68 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
69 struct btrfs_delayed_ref_node *node,
70 struct btrfs_delayed_extent_op *extent_op);
71 static int find_next_key(struct btrfs_path *path, int level,
72 struct btrfs_key *key);
73 static void dump_space_info(struct btrfs_fs_info *fs_info,
74 struct btrfs_space_info *info, u64 bytes,
75 int dump_block_groups);
76 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
80 block_group_cache_done(struct btrfs_block_group_cache *cache)
83 return cache->cached == BTRFS_CACHE_FINISHED ||
84 cache->cached == BTRFS_CACHE_ERROR;
87 static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
89 return (cache->flags & bits) == bits;
92 void btrfs_get_block_group(struct btrfs_block_group_cache *cache)
94 atomic_inc(&cache->count);
97 void btrfs_put_block_group(struct btrfs_block_group_cache *cache)
99 if (atomic_dec_and_test(&cache->count)) {
100 WARN_ON(cache->pinned > 0);
101 WARN_ON(cache->reserved > 0);
104 * If not empty, someone is still holding mutex of
105 * full_stripe_lock, which can only be released by caller.
106 * And it will definitely cause use-after-free when caller
107 * tries to release full stripe lock.
109 * No better way to resolve, but only to warn.
111 WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root));
112 kfree(cache->free_space_ctl);
118 * this adds the block group to the fs_info rb tree for the block group
121 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
122 struct btrfs_block_group_cache *block_group)
125 struct rb_node *parent = NULL;
126 struct btrfs_block_group_cache *cache;
128 spin_lock(&info->block_group_cache_lock);
129 p = &info->block_group_cache_tree.rb_node;
133 cache = rb_entry(parent, struct btrfs_block_group_cache,
135 if (block_group->key.objectid < cache->key.objectid) {
137 } else if (block_group->key.objectid > cache->key.objectid) {
140 spin_unlock(&info->block_group_cache_lock);
145 rb_link_node(&block_group->cache_node, parent, p);
146 rb_insert_color(&block_group->cache_node,
147 &info->block_group_cache_tree);
149 if (info->first_logical_byte > block_group->key.objectid)
150 info->first_logical_byte = block_group->key.objectid;
152 spin_unlock(&info->block_group_cache_lock);
158 * This will return the block group at or after bytenr if contains is 0, else
159 * it will return the block group that contains the bytenr
161 static struct btrfs_block_group_cache *
162 block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
165 struct btrfs_block_group_cache *cache, *ret = NULL;
169 spin_lock(&info->block_group_cache_lock);
170 n = info->block_group_cache_tree.rb_node;
173 cache = rb_entry(n, struct btrfs_block_group_cache,
175 end = cache->key.objectid + cache->key.offset - 1;
176 start = cache->key.objectid;
178 if (bytenr < start) {
179 if (!contains && (!ret || start < ret->key.objectid))
182 } else if (bytenr > start) {
183 if (contains && bytenr <= end) {
194 btrfs_get_block_group(ret);
195 if (bytenr == 0 && info->first_logical_byte > ret->key.objectid)
196 info->first_logical_byte = ret->key.objectid;
198 spin_unlock(&info->block_group_cache_lock);
203 static int add_excluded_extent(struct btrfs_fs_info *fs_info,
204 u64 start, u64 num_bytes)
206 u64 end = start + num_bytes - 1;
207 set_extent_bits(&fs_info->freed_extents[0],
208 start, end, EXTENT_UPTODATE);
209 set_extent_bits(&fs_info->freed_extents[1],
210 start, end, EXTENT_UPTODATE);
214 static void free_excluded_extents(struct btrfs_block_group_cache *cache)
216 struct btrfs_fs_info *fs_info = cache->fs_info;
219 start = cache->key.objectid;
220 end = start + cache->key.offset - 1;
222 clear_extent_bits(&fs_info->freed_extents[0],
223 start, end, EXTENT_UPTODATE);
224 clear_extent_bits(&fs_info->freed_extents[1],
225 start, end, EXTENT_UPTODATE);
228 static int exclude_super_stripes(struct btrfs_block_group_cache *cache)
230 struct btrfs_fs_info *fs_info = cache->fs_info;
236 if (cache->key.objectid < BTRFS_SUPER_INFO_OFFSET) {
237 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->key.objectid;
238 cache->bytes_super += stripe_len;
239 ret = add_excluded_extent(fs_info, cache->key.objectid,
245 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
246 bytenr = btrfs_sb_offset(i);
247 ret = btrfs_rmap_block(fs_info, cache->key.objectid,
248 bytenr, &logical, &nr, &stripe_len);
255 if (logical[nr] > cache->key.objectid +
259 if (logical[nr] + stripe_len <= cache->key.objectid)
263 if (start < cache->key.objectid) {
264 start = cache->key.objectid;
265 len = (logical[nr] + stripe_len) - start;
267 len = min_t(u64, stripe_len,
268 cache->key.objectid +
269 cache->key.offset - start);
272 cache->bytes_super += len;
273 ret = add_excluded_extent(fs_info, start, len);
285 static struct btrfs_caching_control *
286 get_caching_control(struct btrfs_block_group_cache *cache)
288 struct btrfs_caching_control *ctl;
290 spin_lock(&cache->lock);
291 if (!cache->caching_ctl) {
292 spin_unlock(&cache->lock);
296 ctl = cache->caching_ctl;
297 refcount_inc(&ctl->count);
298 spin_unlock(&cache->lock);
302 static void put_caching_control(struct btrfs_caching_control *ctl)
304 if (refcount_dec_and_test(&ctl->count))
308 #ifdef CONFIG_BTRFS_DEBUG
309 static void fragment_free_space(struct btrfs_block_group_cache *block_group)
311 struct btrfs_fs_info *fs_info = block_group->fs_info;
312 u64 start = block_group->key.objectid;
313 u64 len = block_group->key.offset;
314 u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
315 fs_info->nodesize : fs_info->sectorsize;
316 u64 step = chunk << 1;
318 while (len > chunk) {
319 btrfs_remove_free_space(block_group, start, chunk);
330 * this is only called by cache_block_group, since we could have freed extents
331 * we need to check the pinned_extents for any extents that can't be used yet
332 * since their free space will be released as soon as the transaction commits.
334 u64 add_new_free_space(struct btrfs_block_group_cache *block_group,
337 struct btrfs_fs_info *info = block_group->fs_info;
338 u64 extent_start, extent_end, size, total_added = 0;
341 while (start < end) {
342 ret = find_first_extent_bit(info->pinned_extents, start,
343 &extent_start, &extent_end,
344 EXTENT_DIRTY | EXTENT_UPTODATE,
349 if (extent_start <= start) {
350 start = extent_end + 1;
351 } else if (extent_start > start && extent_start < end) {
352 size = extent_start - start;
354 ret = btrfs_add_free_space(block_group, start,
356 BUG_ON(ret); /* -ENOMEM or logic error */
357 start = extent_end + 1;
366 ret = btrfs_add_free_space(block_group, start, size);
367 BUG_ON(ret); /* -ENOMEM or logic error */
373 static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
375 struct btrfs_block_group_cache *block_group = caching_ctl->block_group;
376 struct btrfs_fs_info *fs_info = block_group->fs_info;
377 struct btrfs_root *extent_root = fs_info->extent_root;
378 struct btrfs_path *path;
379 struct extent_buffer *leaf;
380 struct btrfs_key key;
387 path = btrfs_alloc_path();
391 last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
393 #ifdef CONFIG_BTRFS_DEBUG
395 * If we're fragmenting we don't want to make anybody think we can
396 * allocate from this block group until we've had a chance to fragment
399 if (btrfs_should_fragment_free_space(block_group))
403 * We don't want to deadlock with somebody trying to allocate a new
404 * extent for the extent root while also trying to search the extent
405 * root to add free space. So we skip locking and search the commit
406 * root, since its read-only
408 path->skip_locking = 1;
409 path->search_commit_root = 1;
410 path->reada = READA_FORWARD;
414 key.type = BTRFS_EXTENT_ITEM_KEY;
417 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
421 leaf = path->nodes[0];
422 nritems = btrfs_header_nritems(leaf);
425 if (btrfs_fs_closing(fs_info) > 1) {
430 if (path->slots[0] < nritems) {
431 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
433 ret = find_next_key(path, 0, &key);
437 if (need_resched() ||
438 rwsem_is_contended(&fs_info->commit_root_sem)) {
440 caching_ctl->progress = last;
441 btrfs_release_path(path);
442 up_read(&fs_info->commit_root_sem);
443 mutex_unlock(&caching_ctl->mutex);
445 mutex_lock(&caching_ctl->mutex);
446 down_read(&fs_info->commit_root_sem);
450 ret = btrfs_next_leaf(extent_root, path);
455 leaf = path->nodes[0];
456 nritems = btrfs_header_nritems(leaf);
460 if (key.objectid < last) {
463 key.type = BTRFS_EXTENT_ITEM_KEY;
466 caching_ctl->progress = last;
467 btrfs_release_path(path);
471 if (key.objectid < block_group->key.objectid) {
476 if (key.objectid >= block_group->key.objectid +
477 block_group->key.offset)
480 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
481 key.type == BTRFS_METADATA_ITEM_KEY) {
482 total_found += add_new_free_space(block_group, last,
484 if (key.type == BTRFS_METADATA_ITEM_KEY)
485 last = key.objectid +
488 last = key.objectid + key.offset;
490 if (total_found > CACHING_CTL_WAKE_UP) {
493 wake_up(&caching_ctl->wait);
500 total_found += add_new_free_space(block_group, last,
501 block_group->key.objectid +
502 block_group->key.offset);
503 caching_ctl->progress = (u64)-1;
506 btrfs_free_path(path);
510 static noinline void caching_thread(struct btrfs_work *work)
512 struct btrfs_block_group_cache *block_group;
513 struct btrfs_fs_info *fs_info;
514 struct btrfs_caching_control *caching_ctl;
517 caching_ctl = container_of(work, struct btrfs_caching_control, work);
518 block_group = caching_ctl->block_group;
519 fs_info = block_group->fs_info;
521 mutex_lock(&caching_ctl->mutex);
522 down_read(&fs_info->commit_root_sem);
524 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
525 ret = load_free_space_tree(caching_ctl);
527 ret = load_extent_tree_free(caching_ctl);
529 spin_lock(&block_group->lock);
530 block_group->caching_ctl = NULL;
531 block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
532 spin_unlock(&block_group->lock);
534 #ifdef CONFIG_BTRFS_DEBUG
535 if (btrfs_should_fragment_free_space(block_group)) {
538 spin_lock(&block_group->space_info->lock);
539 spin_lock(&block_group->lock);
540 bytes_used = block_group->key.offset -
541 btrfs_block_group_used(&block_group->item);
542 block_group->space_info->bytes_used += bytes_used >> 1;
543 spin_unlock(&block_group->lock);
544 spin_unlock(&block_group->space_info->lock);
545 fragment_free_space(block_group);
549 caching_ctl->progress = (u64)-1;
551 up_read(&fs_info->commit_root_sem);
552 free_excluded_extents(block_group);
553 mutex_unlock(&caching_ctl->mutex);
555 wake_up(&caching_ctl->wait);
557 put_caching_control(caching_ctl);
558 btrfs_put_block_group(block_group);
561 static int cache_block_group(struct btrfs_block_group_cache *cache,
565 struct btrfs_fs_info *fs_info = cache->fs_info;
566 struct btrfs_caching_control *caching_ctl;
569 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
573 INIT_LIST_HEAD(&caching_ctl->list);
574 mutex_init(&caching_ctl->mutex);
575 init_waitqueue_head(&caching_ctl->wait);
576 caching_ctl->block_group = cache;
577 caching_ctl->progress = cache->key.objectid;
578 refcount_set(&caching_ctl->count, 1);
579 btrfs_init_work(&caching_ctl->work, btrfs_cache_helper,
580 caching_thread, NULL, NULL);
582 spin_lock(&cache->lock);
584 * This should be a rare occasion, but this could happen I think in the
585 * case where one thread starts to load the space cache info, and then
586 * some other thread starts a transaction commit which tries to do an
587 * allocation while the other thread is still loading the space cache
588 * info. The previous loop should have kept us from choosing this block
589 * group, but if we've moved to the state where we will wait on caching
590 * block groups we need to first check if we're doing a fast load here,
591 * so we can wait for it to finish, otherwise we could end up allocating
592 * from a block group who's cache gets evicted for one reason or
595 while (cache->cached == BTRFS_CACHE_FAST) {
596 struct btrfs_caching_control *ctl;
598 ctl = cache->caching_ctl;
599 refcount_inc(&ctl->count);
600 prepare_to_wait(&ctl->wait, &wait, TASK_UNINTERRUPTIBLE);
601 spin_unlock(&cache->lock);
605 finish_wait(&ctl->wait, &wait);
606 put_caching_control(ctl);
607 spin_lock(&cache->lock);
610 if (cache->cached != BTRFS_CACHE_NO) {
611 spin_unlock(&cache->lock);
615 WARN_ON(cache->caching_ctl);
616 cache->caching_ctl = caching_ctl;
617 cache->cached = BTRFS_CACHE_FAST;
618 spin_unlock(&cache->lock);
620 if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
621 mutex_lock(&caching_ctl->mutex);
622 ret = load_free_space_cache(cache);
624 spin_lock(&cache->lock);
626 cache->caching_ctl = NULL;
627 cache->cached = BTRFS_CACHE_FINISHED;
628 cache->last_byte_to_unpin = (u64)-1;
629 caching_ctl->progress = (u64)-1;
631 if (load_cache_only) {
632 cache->caching_ctl = NULL;
633 cache->cached = BTRFS_CACHE_NO;
635 cache->cached = BTRFS_CACHE_STARTED;
636 cache->has_caching_ctl = 1;
639 spin_unlock(&cache->lock);
640 #ifdef CONFIG_BTRFS_DEBUG
642 btrfs_should_fragment_free_space(cache)) {
645 spin_lock(&cache->space_info->lock);
646 spin_lock(&cache->lock);
647 bytes_used = cache->key.offset -
648 btrfs_block_group_used(&cache->item);
649 cache->space_info->bytes_used += bytes_used >> 1;
650 spin_unlock(&cache->lock);
651 spin_unlock(&cache->space_info->lock);
652 fragment_free_space(cache);
655 mutex_unlock(&caching_ctl->mutex);
657 wake_up(&caching_ctl->wait);
659 put_caching_control(caching_ctl);
660 free_excluded_extents(cache);
665 * We're either using the free space tree or no caching at all.
666 * Set cached to the appropriate value and wakeup any waiters.
668 spin_lock(&cache->lock);
669 if (load_cache_only) {
670 cache->caching_ctl = NULL;
671 cache->cached = BTRFS_CACHE_NO;
673 cache->cached = BTRFS_CACHE_STARTED;
674 cache->has_caching_ctl = 1;
676 spin_unlock(&cache->lock);
677 wake_up(&caching_ctl->wait);
680 if (load_cache_only) {
681 put_caching_control(caching_ctl);
685 down_write(&fs_info->commit_root_sem);
686 refcount_inc(&caching_ctl->count);
687 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
688 up_write(&fs_info->commit_root_sem);
690 btrfs_get_block_group(cache);
692 btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
698 * return the block group that starts at or after bytenr
700 static struct btrfs_block_group_cache *
701 btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
703 return block_group_cache_tree_search(info, bytenr, 0);
707 * return the block group that contains the given bytenr
709 struct btrfs_block_group_cache *btrfs_lookup_block_group(
710 struct btrfs_fs_info *info,
713 return block_group_cache_tree_search(info, bytenr, 1);
716 static struct btrfs_space_info *__find_space_info(struct btrfs_fs_info *info,
719 struct list_head *head = &info->space_info;
720 struct btrfs_space_info *found;
722 flags &= BTRFS_BLOCK_GROUP_TYPE_MASK;
725 list_for_each_entry_rcu(found, head, list) {
726 if (found->flags & flags) {
735 static u64 generic_ref_to_space_flags(struct btrfs_ref *ref)
737 if (ref->type == BTRFS_REF_METADATA) {
738 if (ref->tree_ref.root == BTRFS_CHUNK_TREE_OBJECTID)
739 return BTRFS_BLOCK_GROUP_SYSTEM;
741 return BTRFS_BLOCK_GROUP_METADATA;
743 return BTRFS_BLOCK_GROUP_DATA;
746 static void add_pinned_bytes(struct btrfs_fs_info *fs_info,
747 struct btrfs_ref *ref)
749 struct btrfs_space_info *space_info;
750 u64 flags = generic_ref_to_space_flags(ref);
752 space_info = __find_space_info(fs_info, flags);
754 percpu_counter_add_batch(&space_info->total_bytes_pinned, ref->len,
755 BTRFS_TOTAL_BYTES_PINNED_BATCH);
758 static void sub_pinned_bytes(struct btrfs_fs_info *fs_info,
759 struct btrfs_ref *ref)
761 struct btrfs_space_info *space_info;
762 u64 flags = generic_ref_to_space_flags(ref);
764 space_info = __find_space_info(fs_info, flags);
766 percpu_counter_add_batch(&space_info->total_bytes_pinned, -ref->len,
767 BTRFS_TOTAL_BYTES_PINNED_BATCH);
771 * after adding space to the filesystem, we need to clear the full flags
772 * on all the space infos.
774 void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
776 struct list_head *head = &info->space_info;
777 struct btrfs_space_info *found;
780 list_for_each_entry_rcu(found, head, list)
785 /* simple helper to search for an existing data extent at a given offset */
786 int btrfs_lookup_data_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len)
789 struct btrfs_key key;
790 struct btrfs_path *path;
792 path = btrfs_alloc_path();
796 key.objectid = start;
798 key.type = BTRFS_EXTENT_ITEM_KEY;
799 ret = btrfs_search_slot(NULL, fs_info->extent_root, &key, path, 0, 0);
800 btrfs_free_path(path);
805 * helper function to lookup reference count and flags of a tree block.
807 * the head node for delayed ref is used to store the sum of all the
808 * reference count modifications queued up in the rbtree. the head
809 * node may also store the extent flags to set. This way you can check
810 * to see what the reference count and extent flags would be if all of
811 * the delayed refs are not processed.
813 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
814 struct btrfs_fs_info *fs_info, u64 bytenr,
815 u64 offset, int metadata, u64 *refs, u64 *flags)
817 struct btrfs_delayed_ref_head *head;
818 struct btrfs_delayed_ref_root *delayed_refs;
819 struct btrfs_path *path;
820 struct btrfs_extent_item *ei;
821 struct extent_buffer *leaf;
822 struct btrfs_key key;
829 * If we don't have skinny metadata, don't bother doing anything
832 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA)) {
833 offset = fs_info->nodesize;
837 path = btrfs_alloc_path();
842 path->skip_locking = 1;
843 path->search_commit_root = 1;
847 key.objectid = bytenr;
850 key.type = BTRFS_METADATA_ITEM_KEY;
852 key.type = BTRFS_EXTENT_ITEM_KEY;
854 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 0);
858 if (ret > 0 && metadata && key.type == BTRFS_METADATA_ITEM_KEY) {
859 if (path->slots[0]) {
861 btrfs_item_key_to_cpu(path->nodes[0], &key,
863 if (key.objectid == bytenr &&
864 key.type == BTRFS_EXTENT_ITEM_KEY &&
865 key.offset == fs_info->nodesize)
871 leaf = path->nodes[0];
872 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
873 if (item_size >= sizeof(*ei)) {
874 ei = btrfs_item_ptr(leaf, path->slots[0],
875 struct btrfs_extent_item);
876 num_refs = btrfs_extent_refs(leaf, ei);
877 extent_flags = btrfs_extent_flags(leaf, ei);
880 btrfs_print_v0_err(fs_info);
882 btrfs_abort_transaction(trans, ret);
884 btrfs_handle_fs_error(fs_info, ret, NULL);
889 BUG_ON(num_refs == 0);
899 delayed_refs = &trans->transaction->delayed_refs;
900 spin_lock(&delayed_refs->lock);
901 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
903 if (!mutex_trylock(&head->mutex)) {
904 refcount_inc(&head->refs);
905 spin_unlock(&delayed_refs->lock);
907 btrfs_release_path(path);
910 * Mutex was contended, block until it's released and try
913 mutex_lock(&head->mutex);
914 mutex_unlock(&head->mutex);
915 btrfs_put_delayed_ref_head(head);
918 spin_lock(&head->lock);
919 if (head->extent_op && head->extent_op->update_flags)
920 extent_flags |= head->extent_op->flags_to_set;
922 BUG_ON(num_refs == 0);
924 num_refs += head->ref_mod;
925 spin_unlock(&head->lock);
926 mutex_unlock(&head->mutex);
928 spin_unlock(&delayed_refs->lock);
930 WARN_ON(num_refs == 0);
934 *flags = extent_flags;
936 btrfs_free_path(path);
941 * Back reference rules. Back refs have three main goals:
943 * 1) differentiate between all holders of references to an extent so that
944 * when a reference is dropped we can make sure it was a valid reference
945 * before freeing the extent.
947 * 2) Provide enough information to quickly find the holders of an extent
948 * if we notice a given block is corrupted or bad.
950 * 3) Make it easy to migrate blocks for FS shrinking or storage pool
951 * maintenance. This is actually the same as #2, but with a slightly
952 * different use case.
954 * There are two kinds of back refs. The implicit back refs is optimized
955 * for pointers in non-shared tree blocks. For a given pointer in a block,
956 * back refs of this kind provide information about the block's owner tree
957 * and the pointer's key. These information allow us to find the block by
958 * b-tree searching. The full back refs is for pointers in tree blocks not
959 * referenced by their owner trees. The location of tree block is recorded
960 * in the back refs. Actually the full back refs is generic, and can be
961 * used in all cases the implicit back refs is used. The major shortcoming
962 * of the full back refs is its overhead. Every time a tree block gets
963 * COWed, we have to update back refs entry for all pointers in it.
965 * For a newly allocated tree block, we use implicit back refs for
966 * pointers in it. This means most tree related operations only involve
967 * implicit back refs. For a tree block created in old transaction, the
968 * only way to drop a reference to it is COW it. So we can detect the
969 * event that tree block loses its owner tree's reference and do the
970 * back refs conversion.
972 * When a tree block is COWed through a tree, there are four cases:
974 * The reference count of the block is one and the tree is the block's
975 * owner tree. Nothing to do in this case.
977 * The reference count of the block is one and the tree is not the
978 * block's owner tree. In this case, full back refs is used for pointers
979 * in the block. Remove these full back refs, add implicit back refs for
980 * every pointers in the new block.
982 * The reference count of the block is greater than one and the tree is
983 * the block's owner tree. In this case, implicit back refs is used for
984 * pointers in the block. Add full back refs for every pointers in the
985 * block, increase lower level extents' reference counts. The original
986 * implicit back refs are entailed to the new block.
988 * The reference count of the block is greater than one and the tree is
989 * not the block's owner tree. Add implicit back refs for every pointer in
990 * the new block, increase lower level extents' reference count.
992 * Back Reference Key composing:
994 * The key objectid corresponds to the first byte in the extent,
995 * The key type is used to differentiate between types of back refs.
996 * There are different meanings of the key offset for different types
999 * File extents can be referenced by:
1001 * - multiple snapshots, subvolumes, or different generations in one subvol
1002 * - different files inside a single subvolume
1003 * - different offsets inside a file (bookend extents in file.c)
1005 * The extent ref structure for the implicit back refs has fields for:
1007 * - Objectid of the subvolume root
1008 * - objectid of the file holding the reference
1009 * - original offset in the file
1010 * - how many bookend extents
1012 * The key offset for the implicit back refs is hash of the first
1015 * The extent ref structure for the full back refs has field for:
1017 * - number of pointers in the tree leaf
1019 * The key offset for the implicit back refs is the first byte of
1022 * When a file extent is allocated, The implicit back refs is used.
1023 * the fields are filled in:
1025 * (root_key.objectid, inode objectid, offset in file, 1)
1027 * When a file extent is removed file truncation, we find the
1028 * corresponding implicit back refs and check the following fields:
1030 * (btrfs_header_owner(leaf), inode objectid, offset in file)
1032 * Btree extents can be referenced by:
1034 * - Different subvolumes
1036 * Both the implicit back refs and the full back refs for tree blocks
1037 * only consist of key. The key offset for the implicit back refs is
1038 * objectid of block's owner tree. The key offset for the full back refs
1039 * is the first byte of parent block.
1041 * When implicit back refs is used, information about the lowest key and
1042 * level of the tree block are required. These information are stored in
1043 * tree block info structure.
1047 * is_data == BTRFS_REF_TYPE_BLOCK, tree block type is required,
1048 * is_data == BTRFS_REF_TYPE_DATA, data type is requiried,
1049 * is_data == BTRFS_REF_TYPE_ANY, either type is OK.
1051 int btrfs_get_extent_inline_ref_type(const struct extent_buffer *eb,
1052 struct btrfs_extent_inline_ref *iref,
1053 enum btrfs_inline_ref_type is_data)
1055 int type = btrfs_extent_inline_ref_type(eb, iref);
1056 u64 offset = btrfs_extent_inline_ref_offset(eb, iref);
1058 if (type == BTRFS_TREE_BLOCK_REF_KEY ||
1059 type == BTRFS_SHARED_BLOCK_REF_KEY ||
1060 type == BTRFS_SHARED_DATA_REF_KEY ||
1061 type == BTRFS_EXTENT_DATA_REF_KEY) {
1062 if (is_data == BTRFS_REF_TYPE_BLOCK) {
1063 if (type == BTRFS_TREE_BLOCK_REF_KEY)
1065 if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1066 ASSERT(eb->fs_info);
1068 * Every shared one has parent tree
1069 * block, which must be aligned to
1073 IS_ALIGNED(offset, eb->fs_info->nodesize))
1076 } else if (is_data == BTRFS_REF_TYPE_DATA) {
1077 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1079 if (type == BTRFS_SHARED_DATA_REF_KEY) {
1080 ASSERT(eb->fs_info);
1082 * Every shared one has parent tree
1083 * block, which must be aligned to
1087 IS_ALIGNED(offset, eb->fs_info->nodesize))
1091 ASSERT(is_data == BTRFS_REF_TYPE_ANY);
1096 btrfs_print_leaf((struct extent_buffer *)eb);
1097 btrfs_err(eb->fs_info, "eb %llu invalid extent inline ref type %d",
1101 return BTRFS_REF_TYPE_INVALID;
1104 static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
1106 u32 high_crc = ~(u32)0;
1107 u32 low_crc = ~(u32)0;
1110 lenum = cpu_to_le64(root_objectid);
1111 high_crc = btrfs_crc32c(high_crc, &lenum, sizeof(lenum));
1112 lenum = cpu_to_le64(owner);
1113 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
1114 lenum = cpu_to_le64(offset);
1115 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
1117 return ((u64)high_crc << 31) ^ (u64)low_crc;
1120 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
1121 struct btrfs_extent_data_ref *ref)
1123 return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
1124 btrfs_extent_data_ref_objectid(leaf, ref),
1125 btrfs_extent_data_ref_offset(leaf, ref));
1128 static int match_extent_data_ref(struct extent_buffer *leaf,
1129 struct btrfs_extent_data_ref *ref,
1130 u64 root_objectid, u64 owner, u64 offset)
1132 if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
1133 btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
1134 btrfs_extent_data_ref_offset(leaf, ref) != offset)
1139 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
1140 struct btrfs_path *path,
1141 u64 bytenr, u64 parent,
1143 u64 owner, u64 offset)
1145 struct btrfs_root *root = trans->fs_info->extent_root;
1146 struct btrfs_key key;
1147 struct btrfs_extent_data_ref *ref;
1148 struct extent_buffer *leaf;
1154 key.objectid = bytenr;
1156 key.type = BTRFS_SHARED_DATA_REF_KEY;
1157 key.offset = parent;
1159 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1160 key.offset = hash_extent_data_ref(root_objectid,
1165 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1177 leaf = path->nodes[0];
1178 nritems = btrfs_header_nritems(leaf);
1180 if (path->slots[0] >= nritems) {
1181 ret = btrfs_next_leaf(root, path);
1187 leaf = path->nodes[0];
1188 nritems = btrfs_header_nritems(leaf);
1192 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1193 if (key.objectid != bytenr ||
1194 key.type != BTRFS_EXTENT_DATA_REF_KEY)
1197 ref = btrfs_item_ptr(leaf, path->slots[0],
1198 struct btrfs_extent_data_ref);
1200 if (match_extent_data_ref(leaf, ref, root_objectid,
1203 btrfs_release_path(path);
1215 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
1216 struct btrfs_path *path,
1217 u64 bytenr, u64 parent,
1218 u64 root_objectid, u64 owner,
1219 u64 offset, int refs_to_add)
1221 struct btrfs_root *root = trans->fs_info->extent_root;
1222 struct btrfs_key key;
1223 struct extent_buffer *leaf;
1228 key.objectid = bytenr;
1230 key.type = BTRFS_SHARED_DATA_REF_KEY;
1231 key.offset = parent;
1232 size = sizeof(struct btrfs_shared_data_ref);
1234 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1235 key.offset = hash_extent_data_ref(root_objectid,
1237 size = sizeof(struct btrfs_extent_data_ref);
1240 ret = btrfs_insert_empty_item(trans, root, path, &key, size);
1241 if (ret && ret != -EEXIST)
1244 leaf = path->nodes[0];
1246 struct btrfs_shared_data_ref *ref;
1247 ref = btrfs_item_ptr(leaf, path->slots[0],
1248 struct btrfs_shared_data_ref);
1250 btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
1252 num_refs = btrfs_shared_data_ref_count(leaf, ref);
1253 num_refs += refs_to_add;
1254 btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
1257 struct btrfs_extent_data_ref *ref;
1258 while (ret == -EEXIST) {
1259 ref = btrfs_item_ptr(leaf, path->slots[0],
1260 struct btrfs_extent_data_ref);
1261 if (match_extent_data_ref(leaf, ref, root_objectid,
1264 btrfs_release_path(path);
1266 ret = btrfs_insert_empty_item(trans, root, path, &key,
1268 if (ret && ret != -EEXIST)
1271 leaf = path->nodes[0];
1273 ref = btrfs_item_ptr(leaf, path->slots[0],
1274 struct btrfs_extent_data_ref);
1276 btrfs_set_extent_data_ref_root(leaf, ref,
1278 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
1279 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
1280 btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
1282 num_refs = btrfs_extent_data_ref_count(leaf, ref);
1283 num_refs += refs_to_add;
1284 btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
1287 btrfs_mark_buffer_dirty(leaf);
1290 btrfs_release_path(path);
1294 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
1295 struct btrfs_path *path,
1296 int refs_to_drop, int *last_ref)
1298 struct btrfs_key key;
1299 struct btrfs_extent_data_ref *ref1 = NULL;
1300 struct btrfs_shared_data_ref *ref2 = NULL;
1301 struct extent_buffer *leaf;
1305 leaf = path->nodes[0];
1306 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1308 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1309 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1310 struct btrfs_extent_data_ref);
1311 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1312 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1313 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1314 struct btrfs_shared_data_ref);
1315 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1316 } else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
1317 btrfs_print_v0_err(trans->fs_info);
1318 btrfs_abort_transaction(trans, -EINVAL);
1324 BUG_ON(num_refs < refs_to_drop);
1325 num_refs -= refs_to_drop;
1327 if (num_refs == 0) {
1328 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
1331 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
1332 btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
1333 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
1334 btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
1335 btrfs_mark_buffer_dirty(leaf);
1340 static noinline u32 extent_data_ref_count(struct btrfs_path *path,
1341 struct btrfs_extent_inline_ref *iref)
1343 struct btrfs_key key;
1344 struct extent_buffer *leaf;
1345 struct btrfs_extent_data_ref *ref1;
1346 struct btrfs_shared_data_ref *ref2;
1350 leaf = path->nodes[0];
1351 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1353 BUG_ON(key.type == BTRFS_EXTENT_REF_V0_KEY);
1356 * If type is invalid, we should have bailed out earlier than
1359 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
1360 ASSERT(type != BTRFS_REF_TYPE_INVALID);
1361 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1362 ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
1363 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1365 ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
1366 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1368 } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1369 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1370 struct btrfs_extent_data_ref);
1371 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1372 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1373 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1374 struct btrfs_shared_data_ref);
1375 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1382 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
1383 struct btrfs_path *path,
1384 u64 bytenr, u64 parent,
1387 struct btrfs_root *root = trans->fs_info->extent_root;
1388 struct btrfs_key key;
1391 key.objectid = bytenr;
1393 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1394 key.offset = parent;
1396 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1397 key.offset = root_objectid;
1400 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1406 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
1407 struct btrfs_path *path,
1408 u64 bytenr, u64 parent,
1411 struct btrfs_key key;
1414 key.objectid = bytenr;
1416 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1417 key.offset = parent;
1419 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1420 key.offset = root_objectid;
1423 ret = btrfs_insert_empty_item(trans, trans->fs_info->extent_root,
1425 btrfs_release_path(path);
1429 static inline int extent_ref_type(u64 parent, u64 owner)
1432 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1434 type = BTRFS_SHARED_BLOCK_REF_KEY;
1436 type = BTRFS_TREE_BLOCK_REF_KEY;
1439 type = BTRFS_SHARED_DATA_REF_KEY;
1441 type = BTRFS_EXTENT_DATA_REF_KEY;
1446 static int find_next_key(struct btrfs_path *path, int level,
1447 struct btrfs_key *key)
1450 for (; level < BTRFS_MAX_LEVEL; level++) {
1451 if (!path->nodes[level])
1453 if (path->slots[level] + 1 >=
1454 btrfs_header_nritems(path->nodes[level]))
1457 btrfs_item_key_to_cpu(path->nodes[level], key,
1458 path->slots[level] + 1);
1460 btrfs_node_key_to_cpu(path->nodes[level], key,
1461 path->slots[level] + 1);
1468 * look for inline back ref. if back ref is found, *ref_ret is set
1469 * to the address of inline back ref, and 0 is returned.
1471 * if back ref isn't found, *ref_ret is set to the address where it
1472 * should be inserted, and -ENOENT is returned.
1474 * if insert is true and there are too many inline back refs, the path
1475 * points to the extent item, and -EAGAIN is returned.
1477 * NOTE: inline back refs are ordered in the same way that back ref
1478 * items in the tree are ordered.
1480 static noinline_for_stack
1481 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
1482 struct btrfs_path *path,
1483 struct btrfs_extent_inline_ref **ref_ret,
1484 u64 bytenr, u64 num_bytes,
1485 u64 parent, u64 root_objectid,
1486 u64 owner, u64 offset, int insert)
1488 struct btrfs_fs_info *fs_info = trans->fs_info;
1489 struct btrfs_root *root = fs_info->extent_root;
1490 struct btrfs_key key;
1491 struct extent_buffer *leaf;
1492 struct btrfs_extent_item *ei;
1493 struct btrfs_extent_inline_ref *iref;
1503 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
1506 key.objectid = bytenr;
1507 key.type = BTRFS_EXTENT_ITEM_KEY;
1508 key.offset = num_bytes;
1510 want = extent_ref_type(parent, owner);
1512 extra_size = btrfs_extent_inline_ref_size(want);
1513 path->keep_locks = 1;
1518 * Owner is our level, so we can just add one to get the level for the
1519 * block we are interested in.
1521 if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
1522 key.type = BTRFS_METADATA_ITEM_KEY;
1527 ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
1534 * We may be a newly converted file system which still has the old fat
1535 * extent entries for metadata, so try and see if we have one of those.
1537 if (ret > 0 && skinny_metadata) {
1538 skinny_metadata = false;
1539 if (path->slots[0]) {
1541 btrfs_item_key_to_cpu(path->nodes[0], &key,
1543 if (key.objectid == bytenr &&
1544 key.type == BTRFS_EXTENT_ITEM_KEY &&
1545 key.offset == num_bytes)
1549 key.objectid = bytenr;
1550 key.type = BTRFS_EXTENT_ITEM_KEY;
1551 key.offset = num_bytes;
1552 btrfs_release_path(path);
1557 if (ret && !insert) {
1560 } else if (WARN_ON(ret)) {
1565 leaf = path->nodes[0];
1566 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1567 if (unlikely(item_size < sizeof(*ei))) {
1569 btrfs_print_v0_err(fs_info);
1570 btrfs_abort_transaction(trans, err);
1574 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1575 flags = btrfs_extent_flags(leaf, ei);
1577 ptr = (unsigned long)(ei + 1);
1578 end = (unsigned long)ei + item_size;
1580 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
1581 ptr += sizeof(struct btrfs_tree_block_info);
1585 if (owner >= BTRFS_FIRST_FREE_OBJECTID)
1586 needed = BTRFS_REF_TYPE_DATA;
1588 needed = BTRFS_REF_TYPE_BLOCK;
1596 iref = (struct btrfs_extent_inline_ref *)ptr;
1597 type = btrfs_get_extent_inline_ref_type(leaf, iref, needed);
1598 if (type == BTRFS_REF_TYPE_INVALID) {
1606 ptr += btrfs_extent_inline_ref_size(type);
1610 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1611 struct btrfs_extent_data_ref *dref;
1612 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1613 if (match_extent_data_ref(leaf, dref, root_objectid,
1618 if (hash_extent_data_ref_item(leaf, dref) <
1619 hash_extent_data_ref(root_objectid, owner, offset))
1623 ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1625 if (parent == ref_offset) {
1629 if (ref_offset < parent)
1632 if (root_objectid == ref_offset) {
1636 if (ref_offset < root_objectid)
1640 ptr += btrfs_extent_inline_ref_size(type);
1642 if (err == -ENOENT && insert) {
1643 if (item_size + extra_size >=
1644 BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1649 * To add new inline back ref, we have to make sure
1650 * there is no corresponding back ref item.
1651 * For simplicity, we just do not add new inline back
1652 * ref if there is any kind of item for this block
1654 if (find_next_key(path, 0, &key) == 0 &&
1655 key.objectid == bytenr &&
1656 key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
1661 *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1664 path->keep_locks = 0;
1665 btrfs_unlock_up_safe(path, 1);
1671 * helper to add new inline back ref
1673 static noinline_for_stack
1674 void setup_inline_extent_backref(struct btrfs_fs_info *fs_info,
1675 struct btrfs_path *path,
1676 struct btrfs_extent_inline_ref *iref,
1677 u64 parent, u64 root_objectid,
1678 u64 owner, u64 offset, int refs_to_add,
1679 struct btrfs_delayed_extent_op *extent_op)
1681 struct extent_buffer *leaf;
1682 struct btrfs_extent_item *ei;
1685 unsigned long item_offset;
1690 leaf = path->nodes[0];
1691 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1692 item_offset = (unsigned long)iref - (unsigned long)ei;
1694 type = extent_ref_type(parent, owner);
1695 size = btrfs_extent_inline_ref_size(type);
1697 btrfs_extend_item(path, size);
1699 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1700 refs = btrfs_extent_refs(leaf, ei);
1701 refs += refs_to_add;
1702 btrfs_set_extent_refs(leaf, ei, refs);
1704 __run_delayed_extent_op(extent_op, leaf, ei);
1706 ptr = (unsigned long)ei + item_offset;
1707 end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1708 if (ptr < end - size)
1709 memmove_extent_buffer(leaf, ptr + size, ptr,
1712 iref = (struct btrfs_extent_inline_ref *)ptr;
1713 btrfs_set_extent_inline_ref_type(leaf, iref, type);
1714 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1715 struct btrfs_extent_data_ref *dref;
1716 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1717 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1718 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1719 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1720 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1721 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1722 struct btrfs_shared_data_ref *sref;
1723 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1724 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1725 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1726 } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1727 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1729 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1731 btrfs_mark_buffer_dirty(leaf);
1734 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1735 struct btrfs_path *path,
1736 struct btrfs_extent_inline_ref **ref_ret,
1737 u64 bytenr, u64 num_bytes, u64 parent,
1738 u64 root_objectid, u64 owner, u64 offset)
1742 ret = lookup_inline_extent_backref(trans, path, ref_ret, bytenr,
1743 num_bytes, parent, root_objectid,
1748 btrfs_release_path(path);
1751 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1752 ret = lookup_tree_block_ref(trans, path, bytenr, parent,
1755 ret = lookup_extent_data_ref(trans, path, bytenr, parent,
1756 root_objectid, owner, offset);
1762 * helper to update/remove inline back ref
1764 static noinline_for_stack
1765 void update_inline_extent_backref(struct btrfs_path *path,
1766 struct btrfs_extent_inline_ref *iref,
1768 struct btrfs_delayed_extent_op *extent_op,
1771 struct extent_buffer *leaf = path->nodes[0];
1772 struct btrfs_extent_item *ei;
1773 struct btrfs_extent_data_ref *dref = NULL;
1774 struct btrfs_shared_data_ref *sref = NULL;
1782 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1783 refs = btrfs_extent_refs(leaf, ei);
1784 WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1785 refs += refs_to_mod;
1786 btrfs_set_extent_refs(leaf, ei, refs);
1788 __run_delayed_extent_op(extent_op, leaf, ei);
1791 * If type is invalid, we should have bailed out after
1792 * lookup_inline_extent_backref().
1794 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY);
1795 ASSERT(type != BTRFS_REF_TYPE_INVALID);
1797 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1798 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1799 refs = btrfs_extent_data_ref_count(leaf, dref);
1800 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1801 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1802 refs = btrfs_shared_data_ref_count(leaf, sref);
1805 BUG_ON(refs_to_mod != -1);
1808 BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1809 refs += refs_to_mod;
1812 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1813 btrfs_set_extent_data_ref_count(leaf, dref, refs);
1815 btrfs_set_shared_data_ref_count(leaf, sref, refs);
1818 size = btrfs_extent_inline_ref_size(type);
1819 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1820 ptr = (unsigned long)iref;
1821 end = (unsigned long)ei + item_size;
1822 if (ptr + size < end)
1823 memmove_extent_buffer(leaf, ptr, ptr + size,
1826 btrfs_truncate_item(path, item_size, 1);
1828 btrfs_mark_buffer_dirty(leaf);
1831 static noinline_for_stack
1832 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1833 struct btrfs_path *path,
1834 u64 bytenr, u64 num_bytes, u64 parent,
1835 u64 root_objectid, u64 owner,
1836 u64 offset, int refs_to_add,
1837 struct btrfs_delayed_extent_op *extent_op)
1839 struct btrfs_extent_inline_ref *iref;
1842 ret = lookup_inline_extent_backref(trans, path, &iref, bytenr,
1843 num_bytes, parent, root_objectid,
1846 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1847 update_inline_extent_backref(path, iref, refs_to_add,
1849 } else if (ret == -ENOENT) {
1850 setup_inline_extent_backref(trans->fs_info, path, iref, parent,
1851 root_objectid, owner, offset,
1852 refs_to_add, extent_op);
1858 static int insert_extent_backref(struct btrfs_trans_handle *trans,
1859 struct btrfs_path *path,
1860 u64 bytenr, u64 parent, u64 root_objectid,
1861 u64 owner, u64 offset, int refs_to_add)
1864 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1865 BUG_ON(refs_to_add != 1);
1866 ret = insert_tree_block_ref(trans, path, bytenr, parent,
1869 ret = insert_extent_data_ref(trans, path, bytenr, parent,
1870 root_objectid, owner, offset,
1876 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1877 struct btrfs_path *path,
1878 struct btrfs_extent_inline_ref *iref,
1879 int refs_to_drop, int is_data, int *last_ref)
1883 BUG_ON(!is_data && refs_to_drop != 1);
1885 update_inline_extent_backref(path, iref, -refs_to_drop, NULL,
1887 } else if (is_data) {
1888 ret = remove_extent_data_ref(trans, path, refs_to_drop,
1892 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
1897 static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
1898 u64 *discarded_bytes)
1901 u64 bytes_left, end;
1902 u64 aligned_start = ALIGN(start, 1 << 9);
1904 if (WARN_ON(start != aligned_start)) {
1905 len -= aligned_start - start;
1906 len = round_down(len, 1 << 9);
1907 start = aligned_start;
1910 *discarded_bytes = 0;
1918 /* Skip any superblocks on this device. */
1919 for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
1920 u64 sb_start = btrfs_sb_offset(j);
1921 u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
1922 u64 size = sb_start - start;
1924 if (!in_range(sb_start, start, bytes_left) &&
1925 !in_range(sb_end, start, bytes_left) &&
1926 !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
1930 * Superblock spans beginning of range. Adjust start and
1933 if (sb_start <= start) {
1934 start += sb_end - start;
1939 bytes_left = end - start;
1944 ret = blkdev_issue_discard(bdev, start >> 9, size >> 9,
1947 *discarded_bytes += size;
1948 else if (ret != -EOPNOTSUPP)
1957 bytes_left = end - start;
1961 ret = blkdev_issue_discard(bdev, start >> 9, bytes_left >> 9,
1964 *discarded_bytes += bytes_left;
1969 int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr,
1970 u64 num_bytes, u64 *actual_bytes)
1973 u64 discarded_bytes = 0;
1974 struct btrfs_bio *bbio = NULL;
1978 * Avoid races with device replace and make sure our bbio has devices
1979 * associated to its stripes that don't go away while we are discarding.
1981 btrfs_bio_counter_inc_blocked(fs_info);
1982 /* Tell the block device(s) that the sectors can be discarded */
1983 ret = btrfs_map_block(fs_info, BTRFS_MAP_DISCARD, bytenr, &num_bytes,
1985 /* Error condition is -ENOMEM */
1987 struct btrfs_bio_stripe *stripe = bbio->stripes;
1991 for (i = 0; i < bbio->num_stripes; i++, stripe++) {
1993 struct request_queue *req_q;
1995 if (!stripe->dev->bdev) {
1996 ASSERT(btrfs_test_opt(fs_info, DEGRADED));
1999 req_q = bdev_get_queue(stripe->dev->bdev);
2000 if (!blk_queue_discard(req_q))
2003 ret = btrfs_issue_discard(stripe->dev->bdev,
2008 discarded_bytes += bytes;
2009 else if (ret != -EOPNOTSUPP)
2010 break; /* Logic errors or -ENOMEM, or -EIO but I don't know how that could happen JDM */
2013 * Just in case we get back EOPNOTSUPP for some reason,
2014 * just ignore the return value so we don't screw up
2015 * people calling discard_extent.
2019 btrfs_put_bbio(bbio);
2021 btrfs_bio_counter_dec(fs_info);
2024 *actual_bytes = discarded_bytes;
2027 if (ret == -EOPNOTSUPP)
2032 /* Can return -ENOMEM */
2033 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2034 struct btrfs_ref *generic_ref)
2036 struct btrfs_fs_info *fs_info = trans->fs_info;
2037 int old_ref_mod, new_ref_mod;
2040 ASSERT(generic_ref->type != BTRFS_REF_NOT_SET &&
2041 generic_ref->action);
2042 BUG_ON(generic_ref->type == BTRFS_REF_METADATA &&
2043 generic_ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID);
2045 if (generic_ref->type == BTRFS_REF_METADATA)
2046 ret = btrfs_add_delayed_tree_ref(trans, generic_ref,
2047 NULL, &old_ref_mod, &new_ref_mod);
2049 ret = btrfs_add_delayed_data_ref(trans, generic_ref, 0,
2050 &old_ref_mod, &new_ref_mod);
2052 btrfs_ref_tree_mod(fs_info, generic_ref);
2054 if (ret == 0 && old_ref_mod < 0 && new_ref_mod >= 0)
2055 sub_pinned_bytes(fs_info, generic_ref);
2061 * __btrfs_inc_extent_ref - insert backreference for a given extent
2063 * @trans: Handle of transaction
2065 * @node: The delayed ref node used to get the bytenr/length for
2066 * extent whose references are incremented.
2068 * @parent: If this is a shared extent (BTRFS_SHARED_DATA_REF_KEY/
2069 * BTRFS_SHARED_BLOCK_REF_KEY) then it holds the logical
2070 * bytenr of the parent block. Since new extents are always
2071 * created with indirect references, this will only be the case
2072 * when relocating a shared extent. In that case, root_objectid
2073 * will be BTRFS_TREE_RELOC_OBJECTID. Otheriwse, parent must
2076 * @root_objectid: The id of the root where this modification has originated,
2077 * this can be either one of the well-known metadata trees or
2078 * the subvolume id which references this extent.
2080 * @owner: For data extents it is the inode number of the owning file.
2081 * For metadata extents this parameter holds the level in the
2082 * tree of the extent.
2084 * @offset: For metadata extents the offset is ignored and is currently
2085 * always passed as 0. For data extents it is the fileoffset
2086 * this extent belongs to.
2088 * @refs_to_add Number of references to add
2090 * @extent_op Pointer to a structure, holding information necessary when
2091 * updating a tree block's flags
2094 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2095 struct btrfs_delayed_ref_node *node,
2096 u64 parent, u64 root_objectid,
2097 u64 owner, u64 offset, int refs_to_add,
2098 struct btrfs_delayed_extent_op *extent_op)
2100 struct btrfs_path *path;
2101 struct extent_buffer *leaf;
2102 struct btrfs_extent_item *item;
2103 struct btrfs_key key;
2104 u64 bytenr = node->bytenr;
2105 u64 num_bytes = node->num_bytes;
2109 path = btrfs_alloc_path();
2113 path->reada = READA_FORWARD;
2114 path->leave_spinning = 1;
2115 /* this will setup the path even if it fails to insert the back ref */
2116 ret = insert_inline_extent_backref(trans, path, bytenr, num_bytes,
2117 parent, root_objectid, owner,
2118 offset, refs_to_add, extent_op);
2119 if ((ret < 0 && ret != -EAGAIN) || !ret)
2123 * Ok we had -EAGAIN which means we didn't have space to insert and
2124 * inline extent ref, so just update the reference count and add a
2127 leaf = path->nodes[0];
2128 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2129 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2130 refs = btrfs_extent_refs(leaf, item);
2131 btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
2133 __run_delayed_extent_op(extent_op, leaf, item);
2135 btrfs_mark_buffer_dirty(leaf);
2136 btrfs_release_path(path);
2138 path->reada = READA_FORWARD;
2139 path->leave_spinning = 1;
2140 /* now insert the actual backref */
2141 ret = insert_extent_backref(trans, path, bytenr, parent, root_objectid,
2142 owner, offset, refs_to_add);
2144 btrfs_abort_transaction(trans, ret);
2146 btrfs_free_path(path);
2150 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
2151 struct btrfs_delayed_ref_node *node,
2152 struct btrfs_delayed_extent_op *extent_op,
2153 int insert_reserved)
2156 struct btrfs_delayed_data_ref *ref;
2157 struct btrfs_key ins;
2162 ins.objectid = node->bytenr;
2163 ins.offset = node->num_bytes;
2164 ins.type = BTRFS_EXTENT_ITEM_KEY;
2166 ref = btrfs_delayed_node_to_data_ref(node);
2167 trace_run_delayed_data_ref(trans->fs_info, node, ref, node->action);
2169 if (node->type == BTRFS_SHARED_DATA_REF_KEY)
2170 parent = ref->parent;
2171 ref_root = ref->root;
2173 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2175 flags |= extent_op->flags_to_set;
2176 ret = alloc_reserved_file_extent(trans, parent, ref_root,
2177 flags, ref->objectid,
2180 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2181 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
2182 ref->objectid, ref->offset,
2183 node->ref_mod, extent_op);
2184 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2185 ret = __btrfs_free_extent(trans, node, parent,
2186 ref_root, ref->objectid,
2187 ref->offset, node->ref_mod,
2195 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
2196 struct extent_buffer *leaf,
2197 struct btrfs_extent_item *ei)
2199 u64 flags = btrfs_extent_flags(leaf, ei);
2200 if (extent_op->update_flags) {
2201 flags |= extent_op->flags_to_set;
2202 btrfs_set_extent_flags(leaf, ei, flags);
2205 if (extent_op->update_key) {
2206 struct btrfs_tree_block_info *bi;
2207 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
2208 bi = (struct btrfs_tree_block_info *)(ei + 1);
2209 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
2213 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
2214 struct btrfs_delayed_ref_head *head,
2215 struct btrfs_delayed_extent_op *extent_op)
2217 struct btrfs_fs_info *fs_info = trans->fs_info;
2218 struct btrfs_key key;
2219 struct btrfs_path *path;
2220 struct btrfs_extent_item *ei;
2221 struct extent_buffer *leaf;
2225 int metadata = !extent_op->is_data;
2230 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2233 path = btrfs_alloc_path();
2237 key.objectid = head->bytenr;
2240 key.type = BTRFS_METADATA_ITEM_KEY;
2241 key.offset = extent_op->level;
2243 key.type = BTRFS_EXTENT_ITEM_KEY;
2244 key.offset = head->num_bytes;
2248 path->reada = READA_FORWARD;
2249 path->leave_spinning = 1;
2250 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 1);
2257 if (path->slots[0] > 0) {
2259 btrfs_item_key_to_cpu(path->nodes[0], &key,
2261 if (key.objectid == head->bytenr &&
2262 key.type == BTRFS_EXTENT_ITEM_KEY &&
2263 key.offset == head->num_bytes)
2267 btrfs_release_path(path);
2270 key.objectid = head->bytenr;
2271 key.offset = head->num_bytes;
2272 key.type = BTRFS_EXTENT_ITEM_KEY;
2281 leaf = path->nodes[0];
2282 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2284 if (unlikely(item_size < sizeof(*ei))) {
2286 btrfs_print_v0_err(fs_info);
2287 btrfs_abort_transaction(trans, err);
2291 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2292 __run_delayed_extent_op(extent_op, leaf, ei);
2294 btrfs_mark_buffer_dirty(leaf);
2296 btrfs_free_path(path);
2300 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
2301 struct btrfs_delayed_ref_node *node,
2302 struct btrfs_delayed_extent_op *extent_op,
2303 int insert_reserved)
2306 struct btrfs_delayed_tree_ref *ref;
2310 ref = btrfs_delayed_node_to_tree_ref(node);
2311 trace_run_delayed_tree_ref(trans->fs_info, node, ref, node->action);
2313 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2314 parent = ref->parent;
2315 ref_root = ref->root;
2317 if (node->ref_mod != 1) {
2318 btrfs_err(trans->fs_info,
2319 "btree block(%llu) has %d references rather than 1: action %d ref_root %llu parent %llu",
2320 node->bytenr, node->ref_mod, node->action, ref_root,
2324 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2325 BUG_ON(!extent_op || !extent_op->update_flags);
2326 ret = alloc_reserved_tree_block(trans, node, extent_op);
2327 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2328 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
2329 ref->level, 0, 1, extent_op);
2330 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2331 ret = __btrfs_free_extent(trans, node, parent, ref_root,
2332 ref->level, 0, 1, extent_op);
2339 /* helper function to actually process a single delayed ref entry */
2340 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
2341 struct btrfs_delayed_ref_node *node,
2342 struct btrfs_delayed_extent_op *extent_op,
2343 int insert_reserved)
2347 if (trans->aborted) {
2348 if (insert_reserved)
2349 btrfs_pin_extent(trans->fs_info, node->bytenr,
2350 node->num_bytes, 1);
2354 if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
2355 node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2356 ret = run_delayed_tree_ref(trans, node, extent_op,
2358 else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
2359 node->type == BTRFS_SHARED_DATA_REF_KEY)
2360 ret = run_delayed_data_ref(trans, node, extent_op,
2364 if (ret && insert_reserved)
2365 btrfs_pin_extent(trans->fs_info, node->bytenr,
2366 node->num_bytes, 1);
2370 static inline struct btrfs_delayed_ref_node *
2371 select_delayed_ref(struct btrfs_delayed_ref_head *head)
2373 struct btrfs_delayed_ref_node *ref;
2375 if (RB_EMPTY_ROOT(&head->ref_tree.rb_root))
2379 * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
2380 * This is to prevent a ref count from going down to zero, which deletes
2381 * the extent item from the extent tree, when there still are references
2382 * to add, which would fail because they would not find the extent item.
2384 if (!list_empty(&head->ref_add_list))
2385 return list_first_entry(&head->ref_add_list,
2386 struct btrfs_delayed_ref_node, add_list);
2388 ref = rb_entry(rb_first_cached(&head->ref_tree),
2389 struct btrfs_delayed_ref_node, ref_node);
2390 ASSERT(list_empty(&ref->add_list));
2394 static void unselect_delayed_ref_head(struct btrfs_delayed_ref_root *delayed_refs,
2395 struct btrfs_delayed_ref_head *head)
2397 spin_lock(&delayed_refs->lock);
2398 head->processing = 0;
2399 delayed_refs->num_heads_ready++;
2400 spin_unlock(&delayed_refs->lock);
2401 btrfs_delayed_ref_unlock(head);
2404 static struct btrfs_delayed_extent_op *cleanup_extent_op(
2405 struct btrfs_delayed_ref_head *head)
2407 struct btrfs_delayed_extent_op *extent_op = head->extent_op;
2412 if (head->must_insert_reserved) {
2413 head->extent_op = NULL;
2414 btrfs_free_delayed_extent_op(extent_op);
2420 static int run_and_cleanup_extent_op(struct btrfs_trans_handle *trans,
2421 struct btrfs_delayed_ref_head *head)
2423 struct btrfs_delayed_extent_op *extent_op;
2426 extent_op = cleanup_extent_op(head);
2429 head->extent_op = NULL;
2430 spin_unlock(&head->lock);
2431 ret = run_delayed_extent_op(trans, head, extent_op);
2432 btrfs_free_delayed_extent_op(extent_op);
2433 return ret ? ret : 1;
2436 void btrfs_cleanup_ref_head_accounting(struct btrfs_fs_info *fs_info,
2437 struct btrfs_delayed_ref_root *delayed_refs,
2438 struct btrfs_delayed_ref_head *head)
2440 int nr_items = 1; /* Dropping this ref head update. */
2442 if (head->total_ref_mod < 0) {
2443 struct btrfs_space_info *space_info;
2447 flags = BTRFS_BLOCK_GROUP_DATA;
2448 else if (head->is_system)
2449 flags = BTRFS_BLOCK_GROUP_SYSTEM;
2451 flags = BTRFS_BLOCK_GROUP_METADATA;
2452 space_info = __find_space_info(fs_info, flags);
2454 percpu_counter_add_batch(&space_info->total_bytes_pinned,
2456 BTRFS_TOTAL_BYTES_PINNED_BATCH);
2459 * We had csum deletions accounted for in our delayed refs rsv,
2460 * we need to drop the csum leaves for this update from our
2463 if (head->is_data) {
2464 spin_lock(&delayed_refs->lock);
2465 delayed_refs->pending_csums -= head->num_bytes;
2466 spin_unlock(&delayed_refs->lock);
2467 nr_items += btrfs_csum_bytes_to_leaves(fs_info,
2472 btrfs_delayed_refs_rsv_release(fs_info, nr_items);
2475 static int cleanup_ref_head(struct btrfs_trans_handle *trans,
2476 struct btrfs_delayed_ref_head *head)
2479 struct btrfs_fs_info *fs_info = trans->fs_info;
2480 struct btrfs_delayed_ref_root *delayed_refs;
2483 delayed_refs = &trans->transaction->delayed_refs;
2485 ret = run_and_cleanup_extent_op(trans, head);
2487 unselect_delayed_ref_head(delayed_refs, head);
2488 btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
2495 * Need to drop our head ref lock and re-acquire the delayed ref lock
2496 * and then re-check to make sure nobody got added.
2498 spin_unlock(&head->lock);
2499 spin_lock(&delayed_refs->lock);
2500 spin_lock(&head->lock);
2501 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root) || head->extent_op) {
2502 spin_unlock(&head->lock);
2503 spin_unlock(&delayed_refs->lock);
2506 btrfs_delete_ref_head(delayed_refs, head);
2507 spin_unlock(&head->lock);
2508 spin_unlock(&delayed_refs->lock);
2510 if (head->must_insert_reserved) {
2511 btrfs_pin_extent(fs_info, head->bytenr,
2512 head->num_bytes, 1);
2513 if (head->is_data) {
2514 ret = btrfs_del_csums(trans, fs_info, head->bytenr,
2519 btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
2521 trace_run_delayed_ref_head(fs_info, head, 0);
2522 btrfs_delayed_ref_unlock(head);
2523 btrfs_put_delayed_ref_head(head);
2527 static struct btrfs_delayed_ref_head *btrfs_obtain_ref_head(
2528 struct btrfs_trans_handle *trans)
2530 struct btrfs_delayed_ref_root *delayed_refs =
2531 &trans->transaction->delayed_refs;
2532 struct btrfs_delayed_ref_head *head = NULL;
2535 spin_lock(&delayed_refs->lock);
2536 head = btrfs_select_ref_head(delayed_refs);
2538 spin_unlock(&delayed_refs->lock);
2543 * Grab the lock that says we are going to process all the refs for
2546 ret = btrfs_delayed_ref_lock(delayed_refs, head);
2547 spin_unlock(&delayed_refs->lock);
2550 * We may have dropped the spin lock to get the head mutex lock, and
2551 * that might have given someone else time to free the head. If that's
2552 * true, it has been removed from our list and we can move on.
2555 head = ERR_PTR(-EAGAIN);
2560 static int btrfs_run_delayed_refs_for_head(struct btrfs_trans_handle *trans,
2561 struct btrfs_delayed_ref_head *locked_ref,
2562 unsigned long *run_refs)
2564 struct btrfs_fs_info *fs_info = trans->fs_info;
2565 struct btrfs_delayed_ref_root *delayed_refs;
2566 struct btrfs_delayed_extent_op *extent_op;
2567 struct btrfs_delayed_ref_node *ref;
2568 int must_insert_reserved = 0;
2571 delayed_refs = &trans->transaction->delayed_refs;
2573 lockdep_assert_held(&locked_ref->mutex);
2574 lockdep_assert_held(&locked_ref->lock);
2576 while ((ref = select_delayed_ref(locked_ref))) {
2578 btrfs_check_delayed_seq(fs_info, ref->seq)) {
2579 spin_unlock(&locked_ref->lock);
2580 unselect_delayed_ref_head(delayed_refs, locked_ref);
2586 rb_erase_cached(&ref->ref_node, &locked_ref->ref_tree);
2587 RB_CLEAR_NODE(&ref->ref_node);
2588 if (!list_empty(&ref->add_list))
2589 list_del(&ref->add_list);
2591 * When we play the delayed ref, also correct the ref_mod on
2594 switch (ref->action) {
2595 case BTRFS_ADD_DELAYED_REF:
2596 case BTRFS_ADD_DELAYED_EXTENT:
2597 locked_ref->ref_mod -= ref->ref_mod;
2599 case BTRFS_DROP_DELAYED_REF:
2600 locked_ref->ref_mod += ref->ref_mod;
2605 atomic_dec(&delayed_refs->num_entries);
2608 * Record the must_insert_reserved flag before we drop the
2611 must_insert_reserved = locked_ref->must_insert_reserved;
2612 locked_ref->must_insert_reserved = 0;
2614 extent_op = locked_ref->extent_op;
2615 locked_ref->extent_op = NULL;
2616 spin_unlock(&locked_ref->lock);
2618 ret = run_one_delayed_ref(trans, ref, extent_op,
2619 must_insert_reserved);
2621 btrfs_free_delayed_extent_op(extent_op);
2623 unselect_delayed_ref_head(delayed_refs, locked_ref);
2624 btrfs_put_delayed_ref(ref);
2625 btrfs_debug(fs_info, "run_one_delayed_ref returned %d",
2630 btrfs_put_delayed_ref(ref);
2633 spin_lock(&locked_ref->lock);
2634 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
2641 * Returns 0 on success or if called with an already aborted transaction.
2642 * Returns -ENOMEM or -EIO on failure and will abort the transaction.
2644 static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2647 struct btrfs_fs_info *fs_info = trans->fs_info;
2648 struct btrfs_delayed_ref_root *delayed_refs;
2649 struct btrfs_delayed_ref_head *locked_ref = NULL;
2650 ktime_t start = ktime_get();
2652 unsigned long count = 0;
2653 unsigned long actual_count = 0;
2655 delayed_refs = &trans->transaction->delayed_refs;
2658 locked_ref = btrfs_obtain_ref_head(trans);
2659 if (IS_ERR_OR_NULL(locked_ref)) {
2660 if (PTR_ERR(locked_ref) == -EAGAIN) {
2669 * We need to try and merge add/drops of the same ref since we
2670 * can run into issues with relocate dropping the implicit ref
2671 * and then it being added back again before the drop can
2672 * finish. If we merged anything we need to re-loop so we can
2674 * Or we can get node references of the same type that weren't
2675 * merged when created due to bumps in the tree mod seq, and
2676 * we need to merge them to prevent adding an inline extent
2677 * backref before dropping it (triggering a BUG_ON at
2678 * insert_inline_extent_backref()).
2680 spin_lock(&locked_ref->lock);
2681 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
2683 ret = btrfs_run_delayed_refs_for_head(trans, locked_ref,
2685 if (ret < 0 && ret != -EAGAIN) {
2687 * Error, btrfs_run_delayed_refs_for_head already
2688 * unlocked everything so just bail out
2693 * Success, perform the usual cleanup of a processed
2696 ret = cleanup_ref_head(trans, locked_ref);
2698 /* We dropped our lock, we need to loop. */
2707 * Either success case or btrfs_run_delayed_refs_for_head
2708 * returned -EAGAIN, meaning we need to select another head
2713 } while ((nr != -1 && count < nr) || locked_ref);
2716 * We don't want to include ref heads since we can have empty ref heads
2717 * and those will drastically skew our runtime down since we just do
2718 * accounting, no actual extent tree updates.
2720 if (actual_count > 0) {
2721 u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
2725 * We weigh the current average higher than our current runtime
2726 * to avoid large swings in the average.
2728 spin_lock(&delayed_refs->lock);
2729 avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
2730 fs_info->avg_delayed_ref_runtime = avg >> 2; /* div by 4 */
2731 spin_unlock(&delayed_refs->lock);
2736 #ifdef SCRAMBLE_DELAYED_REFS
2738 * Normally delayed refs get processed in ascending bytenr order. This
2739 * correlates in most cases to the order added. To expose dependencies on this
2740 * order, we start to process the tree in the middle instead of the beginning
2742 static u64 find_middle(struct rb_root *root)
2744 struct rb_node *n = root->rb_node;
2745 struct btrfs_delayed_ref_node *entry;
2748 u64 first = 0, last = 0;
2752 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2753 first = entry->bytenr;
2757 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2758 last = entry->bytenr;
2763 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2764 WARN_ON(!entry->in_tree);
2766 middle = entry->bytenr;
2779 static inline u64 heads_to_leaves(struct btrfs_fs_info *fs_info, u64 heads)
2783 num_bytes = heads * (sizeof(struct btrfs_extent_item) +
2784 sizeof(struct btrfs_extent_inline_ref));
2785 if (!btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2786 num_bytes += heads * sizeof(struct btrfs_tree_block_info);
2789 * We don't ever fill up leaves all the way so multiply by 2 just to be
2790 * closer to what we're really going to want to use.
2792 return div_u64(num_bytes, BTRFS_LEAF_DATA_SIZE(fs_info));
2796 * Takes the number of bytes to be csumm'ed and figures out how many leaves it
2797 * would require to store the csums for that many bytes.
2799 u64 btrfs_csum_bytes_to_leaves(struct btrfs_fs_info *fs_info, u64 csum_bytes)
2802 u64 num_csums_per_leaf;
2805 csum_size = BTRFS_MAX_ITEM_SIZE(fs_info);
2806 num_csums_per_leaf = div64_u64(csum_size,
2807 (u64)btrfs_super_csum_size(fs_info->super_copy));
2808 num_csums = div64_u64(csum_bytes, fs_info->sectorsize);
2809 num_csums += num_csums_per_leaf - 1;
2810 num_csums = div64_u64(num_csums, num_csums_per_leaf);
2814 bool btrfs_check_space_for_delayed_refs(struct btrfs_fs_info *fs_info)
2816 struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
2817 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
2821 spin_lock(&global_rsv->lock);
2822 reserved = global_rsv->reserved;
2823 spin_unlock(&global_rsv->lock);
2826 * Since the global reserve is just kind of magic we don't really want
2827 * to rely on it to save our bacon, so if our size is more than the
2828 * delayed_refs_rsv and the global rsv then it's time to think about
2831 spin_lock(&delayed_refs_rsv->lock);
2832 reserved += delayed_refs_rsv->reserved;
2833 if (delayed_refs_rsv->size >= reserved)
2835 spin_unlock(&delayed_refs_rsv->lock);
2839 int btrfs_should_throttle_delayed_refs(struct btrfs_trans_handle *trans)
2842 atomic_read(&trans->transaction->delayed_refs.num_entries);
2847 avg_runtime = trans->fs_info->avg_delayed_ref_runtime;
2848 val = num_entries * avg_runtime;
2849 if (val >= NSEC_PER_SEC)
2851 if (val >= NSEC_PER_SEC / 2)
2854 return btrfs_check_space_for_delayed_refs(trans->fs_info);
2858 * this starts processing the delayed reference count updates and
2859 * extent insertions we have queued up so far. count can be
2860 * 0, which means to process everything in the tree at the start
2861 * of the run (but not newly added entries), or it can be some target
2862 * number you'd like to process.
2864 * Returns 0 on success or if called with an aborted transaction
2865 * Returns <0 on error and aborts the transaction
2867 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2868 unsigned long count)
2870 struct btrfs_fs_info *fs_info = trans->fs_info;
2871 struct rb_node *node;
2872 struct btrfs_delayed_ref_root *delayed_refs;
2873 struct btrfs_delayed_ref_head *head;
2875 int run_all = count == (unsigned long)-1;
2877 /* We'll clean this up in btrfs_cleanup_transaction */
2881 if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
2884 delayed_refs = &trans->transaction->delayed_refs;
2886 count = atomic_read(&delayed_refs->num_entries) * 2;
2889 #ifdef SCRAMBLE_DELAYED_REFS
2890 delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2892 ret = __btrfs_run_delayed_refs(trans, count);
2894 btrfs_abort_transaction(trans, ret);
2899 btrfs_create_pending_block_groups(trans);
2901 spin_lock(&delayed_refs->lock);
2902 node = rb_first_cached(&delayed_refs->href_root);
2904 spin_unlock(&delayed_refs->lock);
2907 head = rb_entry(node, struct btrfs_delayed_ref_head,
2909 refcount_inc(&head->refs);
2910 spin_unlock(&delayed_refs->lock);
2912 /* Mutex was contended, block until it's released and retry. */
2913 mutex_lock(&head->mutex);
2914 mutex_unlock(&head->mutex);
2916 btrfs_put_delayed_ref_head(head);
2924 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2925 u64 bytenr, u64 num_bytes, u64 flags,
2926 int level, int is_data)
2928 struct btrfs_delayed_extent_op *extent_op;
2931 extent_op = btrfs_alloc_delayed_extent_op();
2935 extent_op->flags_to_set = flags;
2936 extent_op->update_flags = true;
2937 extent_op->update_key = false;
2938 extent_op->is_data = is_data ? true : false;
2939 extent_op->level = level;
2941 ret = btrfs_add_delayed_extent_op(trans, bytenr, num_bytes, extent_op);
2943 btrfs_free_delayed_extent_op(extent_op);
2947 static noinline int check_delayed_ref(struct btrfs_root *root,
2948 struct btrfs_path *path,
2949 u64 objectid, u64 offset, u64 bytenr)
2951 struct btrfs_delayed_ref_head *head;
2952 struct btrfs_delayed_ref_node *ref;
2953 struct btrfs_delayed_data_ref *data_ref;
2954 struct btrfs_delayed_ref_root *delayed_refs;
2955 struct btrfs_transaction *cur_trans;
2956 struct rb_node *node;
2959 spin_lock(&root->fs_info->trans_lock);
2960 cur_trans = root->fs_info->running_transaction;
2962 refcount_inc(&cur_trans->use_count);
2963 spin_unlock(&root->fs_info->trans_lock);
2967 delayed_refs = &cur_trans->delayed_refs;
2968 spin_lock(&delayed_refs->lock);
2969 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
2971 spin_unlock(&delayed_refs->lock);
2972 btrfs_put_transaction(cur_trans);
2976 if (!mutex_trylock(&head->mutex)) {
2977 refcount_inc(&head->refs);
2978 spin_unlock(&delayed_refs->lock);
2980 btrfs_release_path(path);
2983 * Mutex was contended, block until it's released and let
2986 mutex_lock(&head->mutex);
2987 mutex_unlock(&head->mutex);
2988 btrfs_put_delayed_ref_head(head);
2989 btrfs_put_transaction(cur_trans);
2992 spin_unlock(&delayed_refs->lock);
2994 spin_lock(&head->lock);
2996 * XXX: We should replace this with a proper search function in the
2999 for (node = rb_first_cached(&head->ref_tree); node;
3000 node = rb_next(node)) {
3001 ref = rb_entry(node, struct btrfs_delayed_ref_node, ref_node);
3002 /* If it's a shared ref we know a cross reference exists */
3003 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
3008 data_ref = btrfs_delayed_node_to_data_ref(ref);
3011 * If our ref doesn't match the one we're currently looking at
3012 * then we have a cross reference.
3014 if (data_ref->root != root->root_key.objectid ||
3015 data_ref->objectid != objectid ||
3016 data_ref->offset != offset) {
3021 spin_unlock(&head->lock);
3022 mutex_unlock(&head->mutex);
3023 btrfs_put_transaction(cur_trans);
3027 static noinline int check_committed_ref(struct btrfs_root *root,
3028 struct btrfs_path *path,
3029 u64 objectid, u64 offset, u64 bytenr)
3031 struct btrfs_fs_info *fs_info = root->fs_info;
3032 struct btrfs_root *extent_root = fs_info->extent_root;
3033 struct extent_buffer *leaf;
3034 struct btrfs_extent_data_ref *ref;
3035 struct btrfs_extent_inline_ref *iref;
3036 struct btrfs_extent_item *ei;
3037 struct btrfs_key key;
3042 key.objectid = bytenr;
3043 key.offset = (u64)-1;
3044 key.type = BTRFS_EXTENT_ITEM_KEY;
3046 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
3049 BUG_ON(ret == 0); /* Corruption */
3052 if (path->slots[0] == 0)
3056 leaf = path->nodes[0];
3057 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3059 if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
3063 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3064 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
3066 if (item_size != sizeof(*ei) +
3067 btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
3070 if (btrfs_extent_generation(leaf, ei) <=
3071 btrfs_root_last_snapshot(&root->root_item))
3074 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
3076 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
3077 if (type != BTRFS_EXTENT_DATA_REF_KEY)
3080 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
3081 if (btrfs_extent_refs(leaf, ei) !=
3082 btrfs_extent_data_ref_count(leaf, ref) ||
3083 btrfs_extent_data_ref_root(leaf, ref) !=
3084 root->root_key.objectid ||
3085 btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
3086 btrfs_extent_data_ref_offset(leaf, ref) != offset)
3094 int btrfs_cross_ref_exist(struct btrfs_root *root, u64 objectid, u64 offset,
3097 struct btrfs_path *path;
3100 path = btrfs_alloc_path();
3105 ret = check_committed_ref(root, path, objectid,
3107 if (ret && ret != -ENOENT)
3110 ret = check_delayed_ref(root, path, objectid, offset, bytenr);
3111 } while (ret == -EAGAIN);
3114 btrfs_free_path(path);
3115 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
3120 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
3121 struct btrfs_root *root,
3122 struct extent_buffer *buf,
3123 int full_backref, int inc)
3125 struct btrfs_fs_info *fs_info = root->fs_info;
3131 struct btrfs_key key;
3132 struct btrfs_file_extent_item *fi;
3133 struct btrfs_ref generic_ref = { 0 };
3134 bool for_reloc = btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC);
3140 if (btrfs_is_testing(fs_info))
3143 ref_root = btrfs_header_owner(buf);
3144 nritems = btrfs_header_nritems(buf);
3145 level = btrfs_header_level(buf);
3147 if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state) && level == 0)
3151 parent = buf->start;
3155 action = BTRFS_ADD_DELAYED_REF;
3157 action = BTRFS_DROP_DELAYED_REF;
3159 for (i = 0; i < nritems; i++) {
3161 btrfs_item_key_to_cpu(buf, &key, i);
3162 if (key.type != BTRFS_EXTENT_DATA_KEY)
3164 fi = btrfs_item_ptr(buf, i,
3165 struct btrfs_file_extent_item);
3166 if (btrfs_file_extent_type(buf, fi) ==
3167 BTRFS_FILE_EXTENT_INLINE)
3169 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
3173 num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
3174 key.offset -= btrfs_file_extent_offset(buf, fi);
3175 btrfs_init_generic_ref(&generic_ref, action, bytenr,
3177 generic_ref.real_root = root->root_key.objectid;
3178 btrfs_init_data_ref(&generic_ref, ref_root, key.objectid,
3180 generic_ref.skip_qgroup = for_reloc;
3182 ret = btrfs_inc_extent_ref(trans, &generic_ref);
3184 ret = btrfs_free_extent(trans, &generic_ref);
3188 bytenr = btrfs_node_blockptr(buf, i);
3189 num_bytes = fs_info->nodesize;
3190 btrfs_init_generic_ref(&generic_ref, action, bytenr,
3192 generic_ref.real_root = root->root_key.objectid;
3193 btrfs_init_tree_ref(&generic_ref, level - 1, ref_root);
3194 generic_ref.skip_qgroup = for_reloc;
3196 ret = btrfs_inc_extent_ref(trans, &generic_ref);
3198 ret = btrfs_free_extent(trans, &generic_ref);
3208 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3209 struct extent_buffer *buf, int full_backref)
3211 return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
3214 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3215 struct extent_buffer *buf, int full_backref)
3217 return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
3220 static int write_one_cache_group(struct btrfs_trans_handle *trans,
3221 struct btrfs_path *path,
3222 struct btrfs_block_group_cache *cache)
3224 struct btrfs_fs_info *fs_info = trans->fs_info;
3226 struct btrfs_root *extent_root = fs_info->extent_root;
3228 struct extent_buffer *leaf;
3230 ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
3237 leaf = path->nodes[0];
3238 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
3239 write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
3240 btrfs_mark_buffer_dirty(leaf);
3242 btrfs_release_path(path);
3247 static struct btrfs_block_group_cache *next_block_group(
3248 struct btrfs_block_group_cache *cache)
3250 struct btrfs_fs_info *fs_info = cache->fs_info;
3251 struct rb_node *node;
3253 spin_lock(&fs_info->block_group_cache_lock);
3255 /* If our block group was removed, we need a full search. */
3256 if (RB_EMPTY_NODE(&cache->cache_node)) {
3257 const u64 next_bytenr = cache->key.objectid + cache->key.offset;
3259 spin_unlock(&fs_info->block_group_cache_lock);
3260 btrfs_put_block_group(cache);
3261 cache = btrfs_lookup_first_block_group(fs_info, next_bytenr); return cache;
3263 node = rb_next(&cache->cache_node);
3264 btrfs_put_block_group(cache);
3266 cache = rb_entry(node, struct btrfs_block_group_cache,
3268 btrfs_get_block_group(cache);
3271 spin_unlock(&fs_info->block_group_cache_lock);
3275 static int cache_save_setup(struct btrfs_block_group_cache *block_group,
3276 struct btrfs_trans_handle *trans,
3277 struct btrfs_path *path)
3279 struct btrfs_fs_info *fs_info = block_group->fs_info;
3280 struct btrfs_root *root = fs_info->tree_root;
3281 struct inode *inode = NULL;
3282 struct extent_changeset *data_reserved = NULL;
3284 int dcs = BTRFS_DC_ERROR;
3290 * If this block group is smaller than 100 megs don't bother caching the
3293 if (block_group->key.offset < (100 * SZ_1M)) {
3294 spin_lock(&block_group->lock);
3295 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
3296 spin_unlock(&block_group->lock);
3303 inode = lookup_free_space_inode(block_group, path);
3304 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
3305 ret = PTR_ERR(inode);
3306 btrfs_release_path(path);
3310 if (IS_ERR(inode)) {
3314 if (block_group->ro)
3317 ret = create_free_space_inode(trans, block_group, path);
3324 * We want to set the generation to 0, that way if anything goes wrong
3325 * from here on out we know not to trust this cache when we load up next
3328 BTRFS_I(inode)->generation = 0;
3329 ret = btrfs_update_inode(trans, root, inode);
3332 * So theoretically we could recover from this, simply set the
3333 * super cache generation to 0 so we know to invalidate the
3334 * cache, but then we'd have to keep track of the block groups
3335 * that fail this way so we know we _have_ to reset this cache
3336 * before the next commit or risk reading stale cache. So to
3337 * limit our exposure to horrible edge cases lets just abort the
3338 * transaction, this only happens in really bad situations
3341 btrfs_abort_transaction(trans, ret);
3346 /* We've already setup this transaction, go ahead and exit */
3347 if (block_group->cache_generation == trans->transid &&
3348 i_size_read(inode)) {
3349 dcs = BTRFS_DC_SETUP;
3353 if (i_size_read(inode) > 0) {
3354 ret = btrfs_check_trunc_cache_free_space(fs_info,
3355 &fs_info->global_block_rsv);
3359 ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
3364 spin_lock(&block_group->lock);
3365 if (block_group->cached != BTRFS_CACHE_FINISHED ||
3366 !btrfs_test_opt(fs_info, SPACE_CACHE)) {
3368 * don't bother trying to write stuff out _if_
3369 * a) we're not cached,
3370 * b) we're with nospace_cache mount option,
3371 * c) we're with v2 space_cache (FREE_SPACE_TREE).
3373 dcs = BTRFS_DC_WRITTEN;
3374 spin_unlock(&block_group->lock);
3377 spin_unlock(&block_group->lock);
3380 * We hit an ENOSPC when setting up the cache in this transaction, just
3381 * skip doing the setup, we've already cleared the cache so we're safe.
3383 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
3389 * Try to preallocate enough space based on how big the block group is.
3390 * Keep in mind this has to include any pinned space which could end up
3391 * taking up quite a bit since it's not folded into the other space
3394 num_pages = div_u64(block_group->key.offset, SZ_256M);
3399 num_pages *= PAGE_SIZE;
3401 ret = btrfs_check_data_free_space(inode, &data_reserved, 0, num_pages);
3405 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
3406 num_pages, num_pages,
3409 * Our cache requires contiguous chunks so that we don't modify a bunch
3410 * of metadata or split extents when writing the cache out, which means
3411 * we can enospc if we are heavily fragmented in addition to just normal
3412 * out of space conditions. So if we hit this just skip setting up any
3413 * other block groups for this transaction, maybe we'll unpin enough
3414 * space the next time around.
3417 dcs = BTRFS_DC_SETUP;
3418 else if (ret == -ENOSPC)
3419 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
3424 btrfs_release_path(path);
3426 spin_lock(&block_group->lock);
3427 if (!ret && dcs == BTRFS_DC_SETUP)
3428 block_group->cache_generation = trans->transid;
3429 block_group->disk_cache_state = dcs;
3430 spin_unlock(&block_group->lock);
3432 extent_changeset_free(data_reserved);
3436 int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
3438 struct btrfs_fs_info *fs_info = trans->fs_info;
3439 struct btrfs_block_group_cache *cache, *tmp;
3440 struct btrfs_transaction *cur_trans = trans->transaction;
3441 struct btrfs_path *path;
3443 if (list_empty(&cur_trans->dirty_bgs) ||
3444 !btrfs_test_opt(fs_info, SPACE_CACHE))
3447 path = btrfs_alloc_path();
3451 /* Could add new block groups, use _safe just in case */
3452 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
3454 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
3455 cache_save_setup(cache, trans, path);
3458 btrfs_free_path(path);
3463 * transaction commit does final block group cache writeback during a
3464 * critical section where nothing is allowed to change the FS. This is
3465 * required in order for the cache to actually match the block group,
3466 * but can introduce a lot of latency into the commit.
3468 * So, btrfs_start_dirty_block_groups is here to kick off block group
3469 * cache IO. There's a chance we'll have to redo some of it if the
3470 * block group changes again during the commit, but it greatly reduces
3471 * the commit latency by getting rid of the easy block groups while
3472 * we're still allowing others to join the commit.
3474 int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
3476 struct btrfs_fs_info *fs_info = trans->fs_info;
3477 struct btrfs_block_group_cache *cache;
3478 struct btrfs_transaction *cur_trans = trans->transaction;
3481 struct btrfs_path *path = NULL;
3483 struct list_head *io = &cur_trans->io_bgs;
3484 int num_started = 0;
3487 spin_lock(&cur_trans->dirty_bgs_lock);
3488 if (list_empty(&cur_trans->dirty_bgs)) {
3489 spin_unlock(&cur_trans->dirty_bgs_lock);
3492 list_splice_init(&cur_trans->dirty_bgs, &dirty);
3493 spin_unlock(&cur_trans->dirty_bgs_lock);
3497 * make sure all the block groups on our dirty list actually
3500 btrfs_create_pending_block_groups(trans);
3503 path = btrfs_alloc_path();
3509 * cache_write_mutex is here only to save us from balance or automatic
3510 * removal of empty block groups deleting this block group while we are
3511 * writing out the cache
3513 mutex_lock(&trans->transaction->cache_write_mutex);
3514 while (!list_empty(&dirty)) {
3515 bool drop_reserve = true;
3517 cache = list_first_entry(&dirty,
3518 struct btrfs_block_group_cache,
3521 * this can happen if something re-dirties a block
3522 * group that is already under IO. Just wait for it to
3523 * finish and then do it all again
3525 if (!list_empty(&cache->io_list)) {
3526 list_del_init(&cache->io_list);
3527 btrfs_wait_cache_io(trans, cache, path);
3528 btrfs_put_block_group(cache);
3533 * btrfs_wait_cache_io uses the cache->dirty_list to decide
3534 * if it should update the cache_state. Don't delete
3535 * until after we wait.
3537 * Since we're not running in the commit critical section
3538 * we need the dirty_bgs_lock to protect from update_block_group
3540 spin_lock(&cur_trans->dirty_bgs_lock);
3541 list_del_init(&cache->dirty_list);
3542 spin_unlock(&cur_trans->dirty_bgs_lock);
3546 cache_save_setup(cache, trans, path);
3548 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
3549 cache->io_ctl.inode = NULL;
3550 ret = btrfs_write_out_cache(trans, cache, path);
3551 if (ret == 0 && cache->io_ctl.inode) {
3556 * The cache_write_mutex is protecting the
3557 * io_list, also refer to the definition of
3558 * btrfs_transaction::io_bgs for more details
3560 list_add_tail(&cache->io_list, io);
3563 * if we failed to write the cache, the
3564 * generation will be bad and life goes on
3570 ret = write_one_cache_group(trans, path, cache);
3572 * Our block group might still be attached to the list
3573 * of new block groups in the transaction handle of some
3574 * other task (struct btrfs_trans_handle->new_bgs). This
3575 * means its block group item isn't yet in the extent
3576 * tree. If this happens ignore the error, as we will
3577 * try again later in the critical section of the
3578 * transaction commit.
3580 if (ret == -ENOENT) {
3582 spin_lock(&cur_trans->dirty_bgs_lock);
3583 if (list_empty(&cache->dirty_list)) {
3584 list_add_tail(&cache->dirty_list,
3585 &cur_trans->dirty_bgs);
3586 btrfs_get_block_group(cache);
3587 drop_reserve = false;
3589 spin_unlock(&cur_trans->dirty_bgs_lock);
3591 btrfs_abort_transaction(trans, ret);
3595 /* if it's not on the io list, we need to put the block group */
3597 btrfs_put_block_group(cache);
3599 btrfs_delayed_refs_rsv_release(fs_info, 1);
3605 * Avoid blocking other tasks for too long. It might even save
3606 * us from writing caches for block groups that are going to be
3609 mutex_unlock(&trans->transaction->cache_write_mutex);
3610 mutex_lock(&trans->transaction->cache_write_mutex);
3612 mutex_unlock(&trans->transaction->cache_write_mutex);
3615 * go through delayed refs for all the stuff we've just kicked off
3616 * and then loop back (just once)
3618 ret = btrfs_run_delayed_refs(trans, 0);
3619 if (!ret && loops == 0) {
3621 spin_lock(&cur_trans->dirty_bgs_lock);
3622 list_splice_init(&cur_trans->dirty_bgs, &dirty);
3624 * dirty_bgs_lock protects us from concurrent block group
3625 * deletes too (not just cache_write_mutex).
3627 if (!list_empty(&dirty)) {
3628 spin_unlock(&cur_trans->dirty_bgs_lock);
3631 spin_unlock(&cur_trans->dirty_bgs_lock);
3632 } else if (ret < 0) {
3633 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
3636 btrfs_free_path(path);
3640 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
3642 struct btrfs_fs_info *fs_info = trans->fs_info;
3643 struct btrfs_block_group_cache *cache;
3644 struct btrfs_transaction *cur_trans = trans->transaction;
3647 struct btrfs_path *path;
3648 struct list_head *io = &cur_trans->io_bgs;
3649 int num_started = 0;
3651 path = btrfs_alloc_path();
3656 * Even though we are in the critical section of the transaction commit,
3657 * we can still have concurrent tasks adding elements to this
3658 * transaction's list of dirty block groups. These tasks correspond to
3659 * endio free space workers started when writeback finishes for a
3660 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
3661 * allocate new block groups as a result of COWing nodes of the root
3662 * tree when updating the free space inode. The writeback for the space
3663 * caches is triggered by an earlier call to
3664 * btrfs_start_dirty_block_groups() and iterations of the following
3666 * Also we want to do the cache_save_setup first and then run the
3667 * delayed refs to make sure we have the best chance at doing this all
3670 spin_lock(&cur_trans->dirty_bgs_lock);
3671 while (!list_empty(&cur_trans->dirty_bgs)) {
3672 cache = list_first_entry(&cur_trans->dirty_bgs,
3673 struct btrfs_block_group_cache,
3677 * this can happen if cache_save_setup re-dirties a block
3678 * group that is already under IO. Just wait for it to
3679 * finish and then do it all again
3681 if (!list_empty(&cache->io_list)) {
3682 spin_unlock(&cur_trans->dirty_bgs_lock);
3683 list_del_init(&cache->io_list);
3684 btrfs_wait_cache_io(trans, cache, path);
3685 btrfs_put_block_group(cache);
3686 spin_lock(&cur_trans->dirty_bgs_lock);
3690 * don't remove from the dirty list until after we've waited
3693 list_del_init(&cache->dirty_list);
3694 spin_unlock(&cur_trans->dirty_bgs_lock);
3697 cache_save_setup(cache, trans, path);
3700 ret = btrfs_run_delayed_refs(trans,
3701 (unsigned long) -1);
3703 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
3704 cache->io_ctl.inode = NULL;
3705 ret = btrfs_write_out_cache(trans, cache, path);
3706 if (ret == 0 && cache->io_ctl.inode) {
3709 list_add_tail(&cache->io_list, io);
3712 * if we failed to write the cache, the
3713 * generation will be bad and life goes on
3719 ret = write_one_cache_group(trans, path, cache);
3721 * One of the free space endio workers might have
3722 * created a new block group while updating a free space
3723 * cache's inode (at inode.c:btrfs_finish_ordered_io())
3724 * and hasn't released its transaction handle yet, in
3725 * which case the new block group is still attached to
3726 * its transaction handle and its creation has not
3727 * finished yet (no block group item in the extent tree
3728 * yet, etc). If this is the case, wait for all free
3729 * space endio workers to finish and retry. This is a
3730 * a very rare case so no need for a more efficient and
3733 if (ret == -ENOENT) {
3734 wait_event(cur_trans->writer_wait,
3735 atomic_read(&cur_trans->num_writers) == 1);
3736 ret = write_one_cache_group(trans, path, cache);
3739 btrfs_abort_transaction(trans, ret);
3742 /* if its not on the io list, we need to put the block group */
3744 btrfs_put_block_group(cache);
3745 btrfs_delayed_refs_rsv_release(fs_info, 1);
3746 spin_lock(&cur_trans->dirty_bgs_lock);
3748 spin_unlock(&cur_trans->dirty_bgs_lock);
3751 * Refer to the definition of io_bgs member for details why it's safe
3752 * to use it without any locking
3754 while (!list_empty(io)) {
3755 cache = list_first_entry(io, struct btrfs_block_group_cache,
3757 list_del_init(&cache->io_list);
3758 btrfs_wait_cache_io(trans, cache, path);
3759 btrfs_put_block_group(cache);
3762 btrfs_free_path(path);
3766 int btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
3768 struct btrfs_block_group_cache *block_group;
3771 block_group = btrfs_lookup_block_group(fs_info, bytenr);
3772 if (!block_group || block_group->ro)
3775 btrfs_put_block_group(block_group);
3779 bool btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
3781 struct btrfs_block_group_cache *bg;
3784 bg = btrfs_lookup_block_group(fs_info, bytenr);
3788 spin_lock(&bg->lock);
3792 atomic_inc(&bg->nocow_writers);
3793 spin_unlock(&bg->lock);
3795 /* no put on block group, done by btrfs_dec_nocow_writers */
3797 btrfs_put_block_group(bg);
3803 void btrfs_dec_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
3805 struct btrfs_block_group_cache *bg;
3807 bg = btrfs_lookup_block_group(fs_info, bytenr);
3809 if (atomic_dec_and_test(&bg->nocow_writers))
3810 wake_up_var(&bg->nocow_writers);
3812 * Once for our lookup and once for the lookup done by a previous call
3813 * to btrfs_inc_nocow_writers()
3815 btrfs_put_block_group(bg);
3816 btrfs_put_block_group(bg);
3819 void btrfs_wait_nocow_writers(struct btrfs_block_group_cache *bg)
3821 wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers));
3824 static const char *alloc_name(u64 flags)
3827 case BTRFS_BLOCK_GROUP_METADATA|BTRFS_BLOCK_GROUP_DATA:
3829 case BTRFS_BLOCK_GROUP_METADATA:
3831 case BTRFS_BLOCK_GROUP_DATA:
3833 case BTRFS_BLOCK_GROUP_SYSTEM:
3837 return "invalid-combination";
3841 static int create_space_info(struct btrfs_fs_info *info, u64 flags)
3844 struct btrfs_space_info *space_info;
3848 space_info = kzalloc(sizeof(*space_info), GFP_NOFS);
3852 ret = percpu_counter_init(&space_info->total_bytes_pinned, 0,
3859 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
3860 INIT_LIST_HEAD(&space_info->block_groups[i]);
3861 init_rwsem(&space_info->groups_sem);
3862 spin_lock_init(&space_info->lock);
3863 space_info->flags = flags & BTRFS_BLOCK_GROUP_TYPE_MASK;
3864 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
3865 init_waitqueue_head(&space_info->wait);
3866 INIT_LIST_HEAD(&space_info->ro_bgs);
3867 INIT_LIST_HEAD(&space_info->tickets);
3868 INIT_LIST_HEAD(&space_info->priority_tickets);
3870 ret = kobject_init_and_add(&space_info->kobj, &space_info_ktype,
3871 info->space_info_kobj, "%s",
3872 alloc_name(space_info->flags));
3874 kobject_put(&space_info->kobj);
3878 list_add_rcu(&space_info->list, &info->space_info);
3879 if (flags & BTRFS_BLOCK_GROUP_DATA)
3880 info->data_sinfo = space_info;
3885 static void update_space_info(struct btrfs_fs_info *info, u64 flags,
3886 u64 total_bytes, u64 bytes_used,
3888 struct btrfs_space_info **space_info)
3890 struct btrfs_space_info *found;
3893 factor = btrfs_bg_type_to_factor(flags);
3895 found = __find_space_info(info, flags);
3897 spin_lock(&found->lock);
3898 found->total_bytes += total_bytes;
3899 found->disk_total += total_bytes * factor;
3900 found->bytes_used += bytes_used;
3901 found->disk_used += bytes_used * factor;
3902 found->bytes_readonly += bytes_readonly;
3903 if (total_bytes > 0)
3905 btrfs_space_info_add_new_bytes(info, found, total_bytes -
3906 bytes_used - bytes_readonly);
3907 spin_unlock(&found->lock);
3908 *space_info = found;
3911 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
3913 u64 extra_flags = chunk_to_extended(flags) &
3914 BTRFS_EXTENDED_PROFILE_MASK;
3916 write_seqlock(&fs_info->profiles_lock);
3917 if (flags & BTRFS_BLOCK_GROUP_DATA)
3918 fs_info->avail_data_alloc_bits |= extra_flags;
3919 if (flags & BTRFS_BLOCK_GROUP_METADATA)
3920 fs_info->avail_metadata_alloc_bits |= extra_flags;
3921 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3922 fs_info->avail_system_alloc_bits |= extra_flags;
3923 write_sequnlock(&fs_info->profiles_lock);
3927 * returns target flags in extended format or 0 if restripe for this
3928 * chunk_type is not in progress
3930 * should be called with balance_lock held
3932 static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
3934 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3940 if (flags & BTRFS_BLOCK_GROUP_DATA &&
3941 bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3942 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
3943 } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
3944 bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3945 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
3946 } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
3947 bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3948 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
3955 * @flags: available profiles in extended format (see ctree.h)
3957 * Returns reduced profile in chunk format. If profile changing is in
3958 * progress (either running or paused) picks the target profile (if it's
3959 * already available), otherwise falls back to plain reducing.
3961 static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
3963 u64 num_devices = fs_info->fs_devices->rw_devices;
3969 * see if restripe for this chunk_type is in progress, if so
3970 * try to reduce to the target profile
3972 spin_lock(&fs_info->balance_lock);
3973 target = get_restripe_target(fs_info, flags);
3975 /* pick target profile only if it's already available */
3976 if ((flags & target) & BTRFS_EXTENDED_PROFILE_MASK) {
3977 spin_unlock(&fs_info->balance_lock);
3978 return extended_to_chunk(target);
3981 spin_unlock(&fs_info->balance_lock);
3983 /* First, mask out the RAID levels which aren't possible */
3984 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
3985 if (num_devices >= btrfs_raid_array[raid_type].devs_min)
3986 allowed |= btrfs_raid_array[raid_type].bg_flag;
3990 if (allowed & BTRFS_BLOCK_GROUP_RAID6)
3991 allowed = BTRFS_BLOCK_GROUP_RAID6;
3992 else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
3993 allowed = BTRFS_BLOCK_GROUP_RAID5;
3994 else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
3995 allowed = BTRFS_BLOCK_GROUP_RAID10;
3996 else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
3997 allowed = BTRFS_BLOCK_GROUP_RAID1;
3998 else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
3999 allowed = BTRFS_BLOCK_GROUP_RAID0;
4001 flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
4003 return extended_to_chunk(flags | allowed);
4006 static u64 get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
4013 seq = read_seqbegin(&fs_info->profiles_lock);
4015 if (flags & BTRFS_BLOCK_GROUP_DATA)
4016 flags |= fs_info->avail_data_alloc_bits;
4017 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
4018 flags |= fs_info->avail_system_alloc_bits;
4019 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
4020 flags |= fs_info->avail_metadata_alloc_bits;
4021 } while (read_seqretry(&fs_info->profiles_lock, seq));
4023 return btrfs_reduce_alloc_profile(fs_info, flags);
4026 static u64 get_alloc_profile_by_root(struct btrfs_root *root, int data)
4028 struct btrfs_fs_info *fs_info = root->fs_info;
4033 flags = BTRFS_BLOCK_GROUP_DATA;
4034 else if (root == fs_info->chunk_root)
4035 flags = BTRFS_BLOCK_GROUP_SYSTEM;
4037 flags = BTRFS_BLOCK_GROUP_METADATA;
4039 ret = get_alloc_profile(fs_info, flags);
4043 u64 btrfs_data_alloc_profile(struct btrfs_fs_info *fs_info)
4045 return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_DATA);
4048 u64 btrfs_metadata_alloc_profile(struct btrfs_fs_info *fs_info)
4050 return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4053 u64 btrfs_system_alloc_profile(struct btrfs_fs_info *fs_info)
4055 return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4058 static u64 btrfs_space_info_used(struct btrfs_space_info *s_info,
4059 bool may_use_included)
4062 return s_info->bytes_used + s_info->bytes_reserved +
4063 s_info->bytes_pinned + s_info->bytes_readonly +
4064 (may_use_included ? s_info->bytes_may_use : 0);
4067 int btrfs_alloc_data_chunk_ondemand(struct btrfs_inode *inode, u64 bytes)
4069 struct btrfs_root *root = inode->root;
4070 struct btrfs_fs_info *fs_info = root->fs_info;
4071 struct btrfs_space_info *data_sinfo = fs_info->data_sinfo;
4074 int need_commit = 2;
4075 int have_pinned_space;
4077 /* make sure bytes are sectorsize aligned */
4078 bytes = ALIGN(bytes, fs_info->sectorsize);
4080 if (btrfs_is_free_space_inode(inode)) {
4082 ASSERT(current->journal_info);
4086 /* make sure we have enough space to handle the data first */
4087 spin_lock(&data_sinfo->lock);
4088 used = btrfs_space_info_used(data_sinfo, true);
4090 if (used + bytes > data_sinfo->total_bytes) {
4091 struct btrfs_trans_handle *trans;
4094 * if we don't have enough free bytes in this space then we need
4095 * to alloc a new chunk.
4097 if (!data_sinfo->full) {
4100 data_sinfo->force_alloc = CHUNK_ALLOC_FORCE;
4101 spin_unlock(&data_sinfo->lock);
4103 alloc_target = btrfs_data_alloc_profile(fs_info);
4105 * It is ugly that we don't call nolock join
4106 * transaction for the free space inode case here.
4107 * But it is safe because we only do the data space
4108 * reservation for the free space cache in the
4109 * transaction context, the common join transaction
4110 * just increase the counter of the current transaction
4111 * handler, doesn't try to acquire the trans_lock of
4114 trans = btrfs_join_transaction(root);
4116 return PTR_ERR(trans);
4118 ret = btrfs_chunk_alloc(trans, alloc_target,
4119 CHUNK_ALLOC_NO_FORCE);
4120 btrfs_end_transaction(trans);
4125 have_pinned_space = 1;
4134 * If we don't have enough pinned space to deal with this
4135 * allocation, and no removed chunk in current transaction,
4136 * don't bother committing the transaction.
4138 have_pinned_space = __percpu_counter_compare(
4139 &data_sinfo->total_bytes_pinned,
4140 used + bytes - data_sinfo->total_bytes,
4141 BTRFS_TOTAL_BYTES_PINNED_BATCH);
4142 spin_unlock(&data_sinfo->lock);
4144 /* commit the current transaction and try again */
4149 if (need_commit > 0) {
4150 btrfs_start_delalloc_roots(fs_info, -1);
4151 btrfs_wait_ordered_roots(fs_info, U64_MAX, 0,
4155 trans = btrfs_join_transaction(root);
4157 return PTR_ERR(trans);
4158 if (have_pinned_space >= 0 ||
4159 test_bit(BTRFS_TRANS_HAVE_FREE_BGS,
4160 &trans->transaction->flags) ||
4162 ret = btrfs_commit_transaction(trans);
4166 * The cleaner kthread might still be doing iput
4167 * operations. Wait for it to finish so that
4168 * more space is released. We don't need to
4169 * explicitly run the delayed iputs here because
4170 * the commit_transaction would have woken up
4173 ret = btrfs_wait_on_delayed_iputs(fs_info);
4178 btrfs_end_transaction(trans);
4182 trace_btrfs_space_reservation(fs_info,
4183 "space_info:enospc",
4184 data_sinfo->flags, bytes, 1);
4187 update_bytes_may_use(fs_info, data_sinfo, bytes);
4188 trace_btrfs_space_reservation(fs_info, "space_info",
4189 data_sinfo->flags, bytes, 1);
4190 spin_unlock(&data_sinfo->lock);
4195 int btrfs_check_data_free_space(struct inode *inode,
4196 struct extent_changeset **reserved, u64 start, u64 len)
4198 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4201 /* align the range */
4202 len = round_up(start + len, fs_info->sectorsize) -
4203 round_down(start, fs_info->sectorsize);
4204 start = round_down(start, fs_info->sectorsize);
4206 ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode), len);
4210 /* Use new btrfs_qgroup_reserve_data to reserve precious data space. */
4211 ret = btrfs_qgroup_reserve_data(inode, reserved, start, len);
4213 btrfs_free_reserved_data_space_noquota(inode, start, len);
4220 * Called if we need to clear a data reservation for this inode
4221 * Normally in a error case.
4223 * This one will *NOT* use accurate qgroup reserved space API, just for case
4224 * which we can't sleep and is sure it won't affect qgroup reserved space.
4225 * Like clear_bit_hook().
4227 void btrfs_free_reserved_data_space_noquota(struct inode *inode, u64 start,
4230 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4231 struct btrfs_space_info *data_sinfo;
4233 /* Make sure the range is aligned to sectorsize */
4234 len = round_up(start + len, fs_info->sectorsize) -
4235 round_down(start, fs_info->sectorsize);
4236 start = round_down(start, fs_info->sectorsize);
4238 data_sinfo = fs_info->data_sinfo;
4239 spin_lock(&data_sinfo->lock);
4240 update_bytes_may_use(fs_info, data_sinfo, -len);
4241 trace_btrfs_space_reservation(fs_info, "space_info",
4242 data_sinfo->flags, len, 0);
4243 spin_unlock(&data_sinfo->lock);
4247 * Called if we need to clear a data reservation for this inode
4248 * Normally in a error case.
4250 * This one will handle the per-inode data rsv map for accurate reserved
4253 void btrfs_free_reserved_data_space(struct inode *inode,
4254 struct extent_changeset *reserved, u64 start, u64 len)
4256 struct btrfs_root *root = BTRFS_I(inode)->root;
4258 /* Make sure the range is aligned to sectorsize */
4259 len = round_up(start + len, root->fs_info->sectorsize) -
4260 round_down(start, root->fs_info->sectorsize);
4261 start = round_down(start, root->fs_info->sectorsize);
4263 btrfs_free_reserved_data_space_noquota(inode, start, len);
4264 btrfs_qgroup_free_data(inode, reserved, start, len);
4267 static void force_metadata_allocation(struct btrfs_fs_info *info)
4269 struct list_head *head = &info->space_info;
4270 struct btrfs_space_info *found;
4273 list_for_each_entry_rcu(found, head, list) {
4274 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
4275 found->force_alloc = CHUNK_ALLOC_FORCE;
4280 static inline u64 calc_global_rsv_need_space(struct btrfs_block_rsv *global)
4282 return (global->size << 1);
4285 static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
4286 struct btrfs_space_info *sinfo, int force)
4288 u64 bytes_used = btrfs_space_info_used(sinfo, false);
4291 if (force == CHUNK_ALLOC_FORCE)
4295 * in limited mode, we want to have some free space up to
4296 * about 1% of the FS size.
4298 if (force == CHUNK_ALLOC_LIMITED) {
4299 thresh = btrfs_super_total_bytes(fs_info->super_copy);
4300 thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
4302 if (sinfo->total_bytes - bytes_used < thresh)
4306 if (bytes_used + SZ_2M < div_factor(sinfo->total_bytes, 8))
4311 static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
4315 num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
4317 num_dev = fs_info->fs_devices->rw_devices;
4323 * If @is_allocation is true, reserve space in the system space info necessary
4324 * for allocating a chunk, otherwise if it's false, reserve space necessary for
4327 void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
4329 struct btrfs_fs_info *fs_info = trans->fs_info;
4330 struct btrfs_space_info *info;
4337 * Needed because we can end up allocating a system chunk and for an
4338 * atomic and race free space reservation in the chunk block reserve.
4340 lockdep_assert_held(&fs_info->chunk_mutex);
4342 info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4343 spin_lock(&info->lock);
4344 left = info->total_bytes - btrfs_space_info_used(info, true);
4345 spin_unlock(&info->lock);
4347 num_devs = get_profile_num_devs(fs_info, type);
4349 /* num_devs device items to update and 1 chunk item to add or remove */
4350 thresh = btrfs_calc_trunc_metadata_size(fs_info, num_devs) +
4351 btrfs_calc_trans_metadata_size(fs_info, 1);
4353 if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
4354 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
4355 left, thresh, type);
4356 dump_space_info(fs_info, info, 0, 0);
4359 if (left < thresh) {
4360 u64 flags = btrfs_system_alloc_profile(fs_info);
4363 * Ignore failure to create system chunk. We might end up not
4364 * needing it, as we might not need to COW all nodes/leafs from
4365 * the paths we visit in the chunk tree (they were already COWed
4366 * or created in the current transaction for example).
4368 ret = btrfs_alloc_chunk(trans, flags);
4372 ret = btrfs_block_rsv_add(fs_info->chunk_root,
4373 &fs_info->chunk_block_rsv,
4374 thresh, BTRFS_RESERVE_NO_FLUSH);
4376 trans->chunk_bytes_reserved += thresh;
4381 * If force is CHUNK_ALLOC_FORCE:
4382 * - return 1 if it successfully allocates a chunk,
4383 * - return errors including -ENOSPC otherwise.
4384 * If force is NOT CHUNK_ALLOC_FORCE:
4385 * - return 0 if it doesn't need to allocate a new chunk,
4386 * - return 1 if it successfully allocates a chunk,
4387 * - return errors including -ENOSPC otherwise.
4389 int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
4390 enum btrfs_chunk_alloc_enum force)
4392 struct btrfs_fs_info *fs_info = trans->fs_info;
4393 struct btrfs_space_info *space_info;
4394 bool wait_for_alloc = false;
4395 bool should_alloc = false;
4398 /* Don't re-enter if we're already allocating a chunk */
4399 if (trans->allocating_chunk)
4402 space_info = __find_space_info(fs_info, flags);
4406 spin_lock(&space_info->lock);
4407 if (force < space_info->force_alloc)
4408 force = space_info->force_alloc;
4409 should_alloc = should_alloc_chunk(fs_info, space_info, force);
4410 if (space_info->full) {
4411 /* No more free physical space */
4416 spin_unlock(&space_info->lock);
4418 } else if (!should_alloc) {
4419 spin_unlock(&space_info->lock);
4421 } else if (space_info->chunk_alloc) {
4423 * Someone is already allocating, so we need to block
4424 * until this someone is finished and then loop to
4425 * recheck if we should continue with our allocation
4428 wait_for_alloc = true;
4429 spin_unlock(&space_info->lock);
4430 mutex_lock(&fs_info->chunk_mutex);
4431 mutex_unlock(&fs_info->chunk_mutex);
4433 /* Proceed with allocation */
4434 space_info->chunk_alloc = 1;
4435 wait_for_alloc = false;
4436 spin_unlock(&space_info->lock);
4440 } while (wait_for_alloc);
4442 mutex_lock(&fs_info->chunk_mutex);
4443 trans->allocating_chunk = true;
4446 * If we have mixed data/metadata chunks we want to make sure we keep
4447 * allocating mixed chunks instead of individual chunks.
4449 if (btrfs_mixed_space_info(space_info))
4450 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
4453 * if we're doing a data chunk, go ahead and make sure that
4454 * we keep a reasonable number of metadata chunks allocated in the
4457 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
4458 fs_info->data_chunk_allocations++;
4459 if (!(fs_info->data_chunk_allocations %
4460 fs_info->metadata_ratio))
4461 force_metadata_allocation(fs_info);
4465 * Check if we have enough space in SYSTEM chunk because we may need
4466 * to update devices.
4468 check_system_chunk(trans, flags);
4470 ret = btrfs_alloc_chunk(trans, flags);
4471 trans->allocating_chunk = false;
4473 spin_lock(&space_info->lock);
4476 space_info->full = 1;
4481 space_info->max_extent_size = 0;
4484 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
4486 space_info->chunk_alloc = 0;
4487 spin_unlock(&space_info->lock);
4488 mutex_unlock(&fs_info->chunk_mutex);
4490 * When we allocate a new chunk we reserve space in the chunk block
4491 * reserve to make sure we can COW nodes/leafs in the chunk tree or
4492 * add new nodes/leafs to it if we end up needing to do it when
4493 * inserting the chunk item and updating device items as part of the
4494 * second phase of chunk allocation, performed by
4495 * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
4496 * large number of new block groups to create in our transaction
4497 * handle's new_bgs list to avoid exhausting the chunk block reserve
4498 * in extreme cases - like having a single transaction create many new
4499 * block groups when starting to write out the free space caches of all
4500 * the block groups that were made dirty during the lifetime of the
4503 if (trans->chunk_bytes_reserved >= (u64)SZ_2M)
4504 btrfs_create_pending_block_groups(trans);
4509 static int can_overcommit(struct btrfs_fs_info *fs_info,
4510 struct btrfs_space_info *space_info, u64 bytes,
4511 enum btrfs_reserve_flush_enum flush,
4514 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4521 /* Don't overcommit when in mixed mode. */
4522 if (space_info->flags & BTRFS_BLOCK_GROUP_DATA)
4526 profile = btrfs_system_alloc_profile(fs_info);
4528 profile = btrfs_metadata_alloc_profile(fs_info);
4530 used = btrfs_space_info_used(space_info, false);
4533 * We only want to allow over committing if we have lots of actual space
4534 * free, but if we don't have enough space to handle the global reserve
4535 * space then we could end up having a real enospc problem when trying
4536 * to allocate a chunk or some other such important allocation.
4538 spin_lock(&global_rsv->lock);
4539 space_size = calc_global_rsv_need_space(global_rsv);
4540 spin_unlock(&global_rsv->lock);
4541 if (used + space_size >= space_info->total_bytes)
4544 used += space_info->bytes_may_use;
4546 avail = atomic64_read(&fs_info->free_chunk_space);
4549 * If we have dup, raid1 or raid10 then only half of the free
4550 * space is actually usable. For raid56, the space info used
4551 * doesn't include the parity drive, so we don't have to
4554 factor = btrfs_bg_type_to_factor(profile);
4555 avail = div_u64(avail, factor);
4558 * If we aren't flushing all things, let us overcommit up to
4559 * 1/2th of the space. If we can flush, don't let us overcommit
4560 * too much, let it overcommit up to 1/8 of the space.
4562 if (flush == BTRFS_RESERVE_FLUSH_ALL)
4567 if (used + bytes < space_info->total_bytes + avail)
4572 static void btrfs_writeback_inodes_sb_nr(struct btrfs_fs_info *fs_info,
4573 unsigned long nr_pages, int nr_items)
4575 struct super_block *sb = fs_info->sb;
4577 if (down_read_trylock(&sb->s_umount)) {
4578 writeback_inodes_sb_nr(sb, nr_pages, WB_REASON_FS_FREE_SPACE);
4579 up_read(&sb->s_umount);
4582 * We needn't worry the filesystem going from r/w to r/o though
4583 * we don't acquire ->s_umount mutex, because the filesystem
4584 * should guarantee the delalloc inodes list be empty after
4585 * the filesystem is readonly(all dirty pages are written to
4588 btrfs_start_delalloc_roots(fs_info, nr_items);
4589 if (!current->journal_info)
4590 btrfs_wait_ordered_roots(fs_info, nr_items, 0, (u64)-1);
4594 static inline u64 calc_reclaim_items_nr(struct btrfs_fs_info *fs_info,
4600 bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
4601 nr = div64_u64(to_reclaim, bytes);
4607 #define EXTENT_SIZE_PER_ITEM SZ_256K
4610 * shrink metadata reservation for delalloc
4612 static void shrink_delalloc(struct btrfs_fs_info *fs_info, u64 to_reclaim,
4613 u64 orig, bool wait_ordered)
4615 struct btrfs_space_info *space_info;
4616 struct btrfs_trans_handle *trans;
4622 unsigned long nr_pages;
4625 /* Calc the number of the pages we need flush for space reservation */
4626 items = calc_reclaim_items_nr(fs_info, to_reclaim);
4627 to_reclaim = items * EXTENT_SIZE_PER_ITEM;
4629 trans = (struct btrfs_trans_handle *)current->journal_info;
4630 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4632 delalloc_bytes = percpu_counter_sum_positive(
4633 &fs_info->delalloc_bytes);
4634 dio_bytes = percpu_counter_sum_positive(&fs_info->dio_bytes);
4635 if (delalloc_bytes == 0 && dio_bytes == 0) {
4639 btrfs_wait_ordered_roots(fs_info, items, 0, (u64)-1);
4644 * If we are doing more ordered than delalloc we need to just wait on
4645 * ordered extents, otherwise we'll waste time trying to flush delalloc
4646 * that likely won't give us the space back we need.
4648 if (dio_bytes > delalloc_bytes)
4649 wait_ordered = true;
4652 while ((delalloc_bytes || dio_bytes) && loops < 3) {
4653 nr_pages = min(delalloc_bytes, to_reclaim) >> PAGE_SHIFT;
4656 * Triggers inode writeback for up to nr_pages. This will invoke
4657 * ->writepages callback and trigger delalloc filling
4658 * (btrfs_run_delalloc_range()).
4660 btrfs_writeback_inodes_sb_nr(fs_info, nr_pages, items);
4663 * We need to wait for the compressed pages to start before
4666 async_pages = atomic_read(&fs_info->async_delalloc_pages);
4671 * Calculate how many compressed pages we want to be written
4672 * before we continue. I.e if there are more async pages than we
4673 * require wait_event will wait until nr_pages are written.
4675 if (async_pages <= nr_pages)
4678 async_pages -= nr_pages;
4680 wait_event(fs_info->async_submit_wait,
4681 atomic_read(&fs_info->async_delalloc_pages) <=
4684 spin_lock(&space_info->lock);
4685 if (list_empty(&space_info->tickets) &&
4686 list_empty(&space_info->priority_tickets)) {
4687 spin_unlock(&space_info->lock);
4690 spin_unlock(&space_info->lock);
4693 if (wait_ordered && !trans) {
4694 btrfs_wait_ordered_roots(fs_info, items, 0, (u64)-1);
4696 time_left = schedule_timeout_killable(1);
4700 delalloc_bytes = percpu_counter_sum_positive(
4701 &fs_info->delalloc_bytes);
4702 dio_bytes = percpu_counter_sum_positive(&fs_info->dio_bytes);
4706 struct reserve_ticket {
4710 struct list_head list;
4711 wait_queue_head_t wait;
4715 * maybe_commit_transaction - possibly commit the transaction if its ok to
4716 * @root - the root we're allocating for
4717 * @bytes - the number of bytes we want to reserve
4718 * @force - force the commit
4720 * This will check to make sure that committing the transaction will actually
4721 * get us somewhere and then commit the transaction if it does. Otherwise it
4722 * will return -ENOSPC.
4724 static int may_commit_transaction(struct btrfs_fs_info *fs_info,
4725 struct btrfs_space_info *space_info)
4727 struct reserve_ticket *ticket = NULL;
4728 struct btrfs_block_rsv *delayed_rsv = &fs_info->delayed_block_rsv;
4729 struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
4730 struct btrfs_trans_handle *trans;
4732 u64 reclaim_bytes = 0;
4734 trans = (struct btrfs_trans_handle *)current->journal_info;
4738 spin_lock(&space_info->lock);
4739 if (!list_empty(&space_info->priority_tickets))
4740 ticket = list_first_entry(&space_info->priority_tickets,
4741 struct reserve_ticket, list);
4742 else if (!list_empty(&space_info->tickets))
4743 ticket = list_first_entry(&space_info->tickets,
4744 struct reserve_ticket, list);
4745 bytes_needed = (ticket) ? ticket->bytes : 0;
4746 spin_unlock(&space_info->lock);
4751 trans = btrfs_join_transaction(fs_info->extent_root);
4753 return PTR_ERR(trans);
4756 * See if there is enough pinned space to make this reservation, or if
4757 * we have block groups that are going to be freed, allowing us to
4758 * possibly do a chunk allocation the next loop through.
4760 if (test_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags) ||
4761 __percpu_counter_compare(&space_info->total_bytes_pinned,
4763 BTRFS_TOTAL_BYTES_PINNED_BATCH) >= 0)
4767 * See if there is some space in the delayed insertion reservation for
4770 if (space_info != delayed_rsv->space_info)
4773 spin_lock(&delayed_rsv->lock);
4774 reclaim_bytes += delayed_rsv->reserved;
4775 spin_unlock(&delayed_rsv->lock);
4777 spin_lock(&delayed_refs_rsv->lock);
4778 reclaim_bytes += delayed_refs_rsv->reserved;
4779 spin_unlock(&delayed_refs_rsv->lock);
4780 if (reclaim_bytes >= bytes_needed)
4782 bytes_needed -= reclaim_bytes;
4784 if (__percpu_counter_compare(&space_info->total_bytes_pinned,
4786 BTRFS_TOTAL_BYTES_PINNED_BATCH) < 0)
4790 return btrfs_commit_transaction(trans);
4792 btrfs_end_transaction(trans);
4797 * Try to flush some data based on policy set by @state. This is only advisory
4798 * and may fail for various reasons. The caller is supposed to examine the
4799 * state of @space_info to detect the outcome.
4801 static void flush_space(struct btrfs_fs_info *fs_info,
4802 struct btrfs_space_info *space_info, u64 num_bytes,
4805 struct btrfs_root *root = fs_info->extent_root;
4806 struct btrfs_trans_handle *trans;
4811 case FLUSH_DELAYED_ITEMS_NR:
4812 case FLUSH_DELAYED_ITEMS:
4813 if (state == FLUSH_DELAYED_ITEMS_NR)
4814 nr = calc_reclaim_items_nr(fs_info, num_bytes) * 2;
4818 trans = btrfs_join_transaction(root);
4819 if (IS_ERR(trans)) {
4820 ret = PTR_ERR(trans);
4823 ret = btrfs_run_delayed_items_nr(trans, nr);
4824 btrfs_end_transaction(trans);
4826 case FLUSH_DELALLOC:
4827 case FLUSH_DELALLOC_WAIT:
4828 shrink_delalloc(fs_info, num_bytes * 2, num_bytes,
4829 state == FLUSH_DELALLOC_WAIT);
4831 case FLUSH_DELAYED_REFS_NR:
4832 case FLUSH_DELAYED_REFS:
4833 trans = btrfs_join_transaction(root);
4834 if (IS_ERR(trans)) {
4835 ret = PTR_ERR(trans);
4838 if (state == FLUSH_DELAYED_REFS_NR)
4839 nr = calc_reclaim_items_nr(fs_info, num_bytes);
4842 btrfs_run_delayed_refs(trans, nr);
4843 btrfs_end_transaction(trans);
4846 case ALLOC_CHUNK_FORCE:
4847 trans = btrfs_join_transaction(root);
4848 if (IS_ERR(trans)) {
4849 ret = PTR_ERR(trans);
4852 ret = btrfs_chunk_alloc(trans,
4853 btrfs_metadata_alloc_profile(fs_info),
4854 (state == ALLOC_CHUNK) ? CHUNK_ALLOC_NO_FORCE :
4856 btrfs_end_transaction(trans);
4857 if (ret > 0 || ret == -ENOSPC)
4862 * If we have pending delayed iputs then we could free up a
4863 * bunch of pinned space, so make sure we run the iputs before
4864 * we do our pinned bytes check below.
4866 btrfs_run_delayed_iputs(fs_info);
4867 btrfs_wait_on_delayed_iputs(fs_info);
4869 ret = may_commit_transaction(fs_info, space_info);
4876 trace_btrfs_flush_space(fs_info, space_info->flags, num_bytes, state,
4882 btrfs_calc_reclaim_metadata_size(struct btrfs_fs_info *fs_info,
4883 struct btrfs_space_info *space_info,
4886 struct reserve_ticket *ticket;
4891 list_for_each_entry(ticket, &space_info->tickets, list)
4892 to_reclaim += ticket->bytes;
4893 list_for_each_entry(ticket, &space_info->priority_tickets, list)
4894 to_reclaim += ticket->bytes;
4898 to_reclaim = min_t(u64, num_online_cpus() * SZ_1M, SZ_16M);
4899 if (can_overcommit(fs_info, space_info, to_reclaim,
4900 BTRFS_RESERVE_FLUSH_ALL, system_chunk))
4903 used = btrfs_space_info_used(space_info, true);
4905 if (can_overcommit(fs_info, space_info, SZ_1M,
4906 BTRFS_RESERVE_FLUSH_ALL, system_chunk))
4907 expected = div_factor_fine(space_info->total_bytes, 95);
4909 expected = div_factor_fine(space_info->total_bytes, 90);
4911 if (used > expected)
4912 to_reclaim = used - expected;
4915 to_reclaim = min(to_reclaim, space_info->bytes_may_use +
4916 space_info->bytes_reserved);
4920 static inline int need_do_async_reclaim(struct btrfs_fs_info *fs_info,
4921 struct btrfs_space_info *space_info,
4922 u64 used, bool system_chunk)
4924 u64 thresh = div_factor_fine(space_info->total_bytes, 98);
4926 /* If we're just plain full then async reclaim just slows us down. */
4927 if ((space_info->bytes_used + space_info->bytes_reserved) >= thresh)
4930 if (!btrfs_calc_reclaim_metadata_size(fs_info, space_info,
4934 return (used >= thresh && !btrfs_fs_closing(fs_info) &&
4935 !test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state));
4938 static bool wake_all_tickets(struct list_head *head)
4940 struct reserve_ticket *ticket;
4942 while (!list_empty(head)) {
4943 ticket = list_first_entry(head, struct reserve_ticket, list);
4944 list_del_init(&ticket->list);
4945 ticket->error = -ENOSPC;
4946 wake_up(&ticket->wait);
4947 if (ticket->bytes != ticket->orig_bytes)
4954 * This is for normal flushers, we can wait all goddamned day if we want to. We
4955 * will loop and continuously try to flush as long as we are making progress.
4956 * We count progress as clearing off tickets each time we have to loop.
4958 static void btrfs_async_reclaim_metadata_space(struct work_struct *work)
4960 struct btrfs_fs_info *fs_info;
4961 struct btrfs_space_info *space_info;
4964 int commit_cycles = 0;
4965 u64 last_tickets_id;
4967 fs_info = container_of(work, struct btrfs_fs_info, async_reclaim_work);
4968 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4970 spin_lock(&space_info->lock);
4971 to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info, space_info,
4974 space_info->flush = 0;
4975 spin_unlock(&space_info->lock);
4978 last_tickets_id = space_info->tickets_id;
4979 spin_unlock(&space_info->lock);
4981 flush_state = FLUSH_DELAYED_ITEMS_NR;
4983 flush_space(fs_info, space_info, to_reclaim, flush_state);
4984 spin_lock(&space_info->lock);
4985 if (list_empty(&space_info->tickets)) {
4986 space_info->flush = 0;
4987 spin_unlock(&space_info->lock);
4990 to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info,
4993 if (last_tickets_id == space_info->tickets_id) {
4996 last_tickets_id = space_info->tickets_id;
4997 flush_state = FLUSH_DELAYED_ITEMS_NR;
5003 * We don't want to force a chunk allocation until we've tried
5004 * pretty hard to reclaim space. Think of the case where we
5005 * freed up a bunch of space and so have a lot of pinned space
5006 * to reclaim. We would rather use that than possibly create a
5007 * underutilized metadata chunk. So if this is our first run
5008 * through the flushing state machine skip ALLOC_CHUNK_FORCE and
5009 * commit the transaction. If nothing has changed the next go
5010 * around then we can force a chunk allocation.
5012 if (flush_state == ALLOC_CHUNK_FORCE && !commit_cycles)
5015 if (flush_state > COMMIT_TRANS) {
5017 if (commit_cycles > 2) {
5018 if (wake_all_tickets(&space_info->tickets)) {
5019 flush_state = FLUSH_DELAYED_ITEMS_NR;
5022 space_info->flush = 0;
5025 flush_state = FLUSH_DELAYED_ITEMS_NR;
5028 spin_unlock(&space_info->lock);
5029 } while (flush_state <= COMMIT_TRANS);
5032 void btrfs_init_async_reclaim_work(struct work_struct *work)
5034 INIT_WORK(work, btrfs_async_reclaim_metadata_space);
5037 static const enum btrfs_flush_state priority_flush_states[] = {
5038 FLUSH_DELAYED_ITEMS_NR,
5039 FLUSH_DELAYED_ITEMS,
5043 static void priority_reclaim_metadata_space(struct btrfs_fs_info *fs_info,
5044 struct btrfs_space_info *space_info,
5045 struct reserve_ticket *ticket)
5050 spin_lock(&space_info->lock);
5051 to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info, space_info,
5054 spin_unlock(&space_info->lock);
5057 spin_unlock(&space_info->lock);
5061 flush_space(fs_info, space_info, to_reclaim,
5062 priority_flush_states[flush_state]);
5064 spin_lock(&space_info->lock);
5065 if (ticket->bytes == 0) {
5066 spin_unlock(&space_info->lock);
5069 spin_unlock(&space_info->lock);
5070 } while (flush_state < ARRAY_SIZE(priority_flush_states));
5073 static int wait_reserve_ticket(struct btrfs_fs_info *fs_info,
5074 struct btrfs_space_info *space_info,
5075 struct reserve_ticket *ticket)
5079 u64 reclaim_bytes = 0;
5082 spin_lock(&space_info->lock);
5083 while (ticket->bytes > 0 && ticket->error == 0) {
5084 ret = prepare_to_wait_event(&ticket->wait, &wait, TASK_KILLABLE);
5089 spin_unlock(&space_info->lock);
5093 finish_wait(&ticket->wait, &wait);
5094 spin_lock(&space_info->lock);
5097 ret = ticket->error;
5098 if (!list_empty(&ticket->list))
5099 list_del_init(&ticket->list);
5100 if (ticket->bytes && ticket->bytes < ticket->orig_bytes)
5101 reclaim_bytes = ticket->orig_bytes - ticket->bytes;
5102 spin_unlock(&space_info->lock);
5105 btrfs_space_info_add_old_bytes(fs_info, space_info,
5111 * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
5112 * @root - the root we're allocating for
5113 * @space_info - the space info we want to allocate from
5114 * @orig_bytes - the number of bytes we want
5115 * @flush - whether or not we can flush to make our reservation
5117 * This will reserve orig_bytes number of bytes from the space info associated
5118 * with the block_rsv. If there is not enough space it will make an attempt to
5119 * flush out space to make room. It will do this by flushing delalloc if
5120 * possible or committing the transaction. If flush is 0 then no attempts to
5121 * regain reservations will be made and this will fail if there is not enough
5124 static int __reserve_metadata_bytes(struct btrfs_fs_info *fs_info,
5125 struct btrfs_space_info *space_info,
5127 enum btrfs_reserve_flush_enum flush,
5130 struct reserve_ticket ticket;
5132 u64 reclaim_bytes = 0;
5136 ASSERT(!current->journal_info || flush != BTRFS_RESERVE_FLUSH_ALL);
5138 spin_lock(&space_info->lock);
5140 used = btrfs_space_info_used(space_info, true);
5143 * If we have enough space then hooray, make our reservation and carry
5144 * on. If not see if we can overcommit, and if we can, hooray carry on.
5145 * If not things get more complicated.
5147 if (used + orig_bytes <= space_info->total_bytes) {
5148 update_bytes_may_use(fs_info, space_info, orig_bytes);
5149 trace_btrfs_space_reservation(fs_info, "space_info",
5150 space_info->flags, orig_bytes, 1);
5152 } else if (can_overcommit(fs_info, space_info, orig_bytes, flush,
5154 update_bytes_may_use(fs_info, space_info, orig_bytes);
5155 trace_btrfs_space_reservation(fs_info, "space_info",
5156 space_info->flags, orig_bytes, 1);
5161 * If we couldn't make a reservation then setup our reservation ticket
5162 * and kick the async worker if it's not already running.
5164 * If we are a priority flusher then we just need to add our ticket to
5165 * the list and we will do our own flushing further down.
5167 if (ret && flush != BTRFS_RESERVE_NO_FLUSH) {
5168 ticket.orig_bytes = orig_bytes;
5169 ticket.bytes = orig_bytes;
5171 init_waitqueue_head(&ticket.wait);
5172 if (flush == BTRFS_RESERVE_FLUSH_ALL) {
5173 list_add_tail(&ticket.list, &space_info->tickets);
5174 if (!space_info->flush) {
5175 space_info->flush = 1;
5176 trace_btrfs_trigger_flush(fs_info,
5180 queue_work(system_unbound_wq,
5181 &fs_info->async_reclaim_work);
5184 list_add_tail(&ticket.list,
5185 &space_info->priority_tickets);
5187 } else if (!ret && space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
5190 * We will do the space reservation dance during log replay,
5191 * which means we won't have fs_info->fs_root set, so don't do
5192 * the async reclaim as we will panic.
5194 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags) &&
5195 need_do_async_reclaim(fs_info, space_info,
5196 used, system_chunk) &&
5197 !work_busy(&fs_info->async_reclaim_work)) {
5198 trace_btrfs_trigger_flush(fs_info, space_info->flags,
5199 orig_bytes, flush, "preempt");
5200 queue_work(system_unbound_wq,
5201 &fs_info->async_reclaim_work);
5204 spin_unlock(&space_info->lock);
5205 if (!ret || flush == BTRFS_RESERVE_NO_FLUSH)
5208 if (flush == BTRFS_RESERVE_FLUSH_ALL)
5209 return wait_reserve_ticket(fs_info, space_info, &ticket);
5212 priority_reclaim_metadata_space(fs_info, space_info, &ticket);
5213 spin_lock(&space_info->lock);
5215 if (ticket.bytes < orig_bytes)
5216 reclaim_bytes = orig_bytes - ticket.bytes;
5217 list_del_init(&ticket.list);
5220 spin_unlock(&space_info->lock);
5223 btrfs_space_info_add_old_bytes(fs_info, space_info,
5225 ASSERT(list_empty(&ticket.list));
5230 * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
5231 * @root - the root we're allocating for
5232 * @block_rsv - the block_rsv we're allocating for
5233 * @orig_bytes - the number of bytes we want
5234 * @flush - whether or not we can flush to make our reservation
5236 * This will reserve orig_bytes number of bytes from the space info associated
5237 * with the block_rsv. If there is not enough space it will make an attempt to
5238 * flush out space to make room. It will do this by flushing delalloc if
5239 * possible or committing the transaction. If flush is 0 then no attempts to
5240 * regain reservations will be made and this will fail if there is not enough
5243 static int reserve_metadata_bytes(struct btrfs_root *root,
5244 struct btrfs_block_rsv *block_rsv,
5246 enum btrfs_reserve_flush_enum flush)
5248 struct btrfs_fs_info *fs_info = root->fs_info;
5249 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5251 bool system_chunk = (root == fs_info->chunk_root);
5253 ret = __reserve_metadata_bytes(fs_info, block_rsv->space_info,
5254 orig_bytes, flush, system_chunk);
5255 if (ret == -ENOSPC &&
5256 unlikely(root->orphan_cleanup_state == ORPHAN_CLEANUP_STARTED)) {
5257 if (block_rsv != global_rsv &&
5258 !block_rsv_use_bytes(global_rsv, orig_bytes))
5261 if (ret == -ENOSPC) {
5262 trace_btrfs_space_reservation(fs_info, "space_info:enospc",
5263 block_rsv->space_info->flags,
5266 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG))
5267 dump_space_info(fs_info, block_rsv->space_info,
5273 static struct btrfs_block_rsv *get_block_rsv(
5274 const struct btrfs_trans_handle *trans,
5275 const struct btrfs_root *root)
5277 struct btrfs_fs_info *fs_info = root->fs_info;
5278 struct btrfs_block_rsv *block_rsv = NULL;
5280 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
5281 (root == fs_info->csum_root && trans->adding_csums) ||
5282 (root == fs_info->uuid_root))
5283 block_rsv = trans->block_rsv;
5286 block_rsv = root->block_rsv;
5289 block_rsv = &fs_info->empty_block_rsv;
5294 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
5298 spin_lock(&block_rsv->lock);
5299 if (block_rsv->reserved >= num_bytes) {
5300 block_rsv->reserved -= num_bytes;
5301 if (block_rsv->reserved < block_rsv->size)
5302 block_rsv->full = 0;
5305 spin_unlock(&block_rsv->lock);
5309 static void block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv,
5310 u64 num_bytes, bool update_size)
5312 spin_lock(&block_rsv->lock);
5313 block_rsv->reserved += num_bytes;
5315 block_rsv->size += num_bytes;
5316 else if (block_rsv->reserved >= block_rsv->size)
5317 block_rsv->full = 1;
5318 spin_unlock(&block_rsv->lock);
5321 int btrfs_cond_migrate_bytes(struct btrfs_fs_info *fs_info,
5322 struct btrfs_block_rsv *dest, u64 num_bytes,
5325 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5328 if (global_rsv->space_info != dest->space_info)
5331 spin_lock(&global_rsv->lock);
5332 min_bytes = div_factor(global_rsv->size, min_factor);
5333 if (global_rsv->reserved < min_bytes + num_bytes) {
5334 spin_unlock(&global_rsv->lock);
5337 global_rsv->reserved -= num_bytes;
5338 if (global_rsv->reserved < global_rsv->size)
5339 global_rsv->full = 0;
5340 spin_unlock(&global_rsv->lock);
5342 block_rsv_add_bytes(dest, num_bytes, true);
5347 * btrfs_migrate_to_delayed_refs_rsv - transfer bytes to our delayed refs rsv.
5348 * @fs_info - the fs info for our fs.
5349 * @src - the source block rsv to transfer from.
5350 * @num_bytes - the number of bytes to transfer.
5352 * This transfers up to the num_bytes amount from the src rsv to the
5353 * delayed_refs_rsv. Any extra bytes are returned to the space info.
5355 void btrfs_migrate_to_delayed_refs_rsv(struct btrfs_fs_info *fs_info,
5356 struct btrfs_block_rsv *src,
5359 struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
5362 spin_lock(&src->lock);
5363 src->reserved -= num_bytes;
5364 src->size -= num_bytes;
5365 spin_unlock(&src->lock);
5367 spin_lock(&delayed_refs_rsv->lock);
5368 if (delayed_refs_rsv->size > delayed_refs_rsv->reserved) {
5369 u64 delta = delayed_refs_rsv->size -
5370 delayed_refs_rsv->reserved;
5371 if (num_bytes > delta) {
5372 to_free = num_bytes - delta;
5376 to_free = num_bytes;
5381 delayed_refs_rsv->reserved += num_bytes;
5382 if (delayed_refs_rsv->reserved >= delayed_refs_rsv->size)
5383 delayed_refs_rsv->full = 1;
5384 spin_unlock(&delayed_refs_rsv->lock);
5387 trace_btrfs_space_reservation(fs_info, "delayed_refs_rsv",
5390 btrfs_space_info_add_old_bytes(fs_info,
5391 delayed_refs_rsv->space_info, to_free);
5395 * btrfs_delayed_refs_rsv_refill - refill based on our delayed refs usage.
5396 * @fs_info - the fs_info for our fs.
5397 * @flush - control how we can flush for this reservation.
5399 * This will refill the delayed block_rsv up to 1 items size worth of space and
5400 * will return -ENOSPC if we can't make the reservation.
5402 int btrfs_delayed_refs_rsv_refill(struct btrfs_fs_info *fs_info,
5403 enum btrfs_reserve_flush_enum flush)
5405 struct btrfs_block_rsv *block_rsv = &fs_info->delayed_refs_rsv;
5406 u64 limit = btrfs_calc_trans_metadata_size(fs_info, 1);
5410 spin_lock(&block_rsv->lock);
5411 if (block_rsv->reserved < block_rsv->size) {
5412 num_bytes = block_rsv->size - block_rsv->reserved;
5413 num_bytes = min(num_bytes, limit);
5415 spin_unlock(&block_rsv->lock);
5420 ret = reserve_metadata_bytes(fs_info->extent_root, block_rsv,
5424 block_rsv_add_bytes(block_rsv, num_bytes, 0);
5425 trace_btrfs_space_reservation(fs_info, "delayed_refs_rsv",
5431 * This is for space we already have accounted in space_info->bytes_may_use, so
5432 * basically when we're returning space from block_rsv's.
5434 void btrfs_space_info_add_old_bytes(struct btrfs_fs_info *fs_info,
5435 struct btrfs_space_info *space_info,
5438 struct reserve_ticket *ticket;
5439 struct list_head *head;
5441 enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_NO_FLUSH;
5442 bool check_overcommit = false;
5444 spin_lock(&space_info->lock);
5445 head = &space_info->priority_tickets;
5448 * If we are over our limit then we need to check and see if we can
5449 * overcommit, and if we can't then we just need to free up our space
5450 * and not satisfy any requests.
5452 used = btrfs_space_info_used(space_info, true);
5453 if (used - num_bytes >= space_info->total_bytes)
5454 check_overcommit = true;
5456 while (!list_empty(head) && num_bytes) {
5457 ticket = list_first_entry(head, struct reserve_ticket,
5460 * We use 0 bytes because this space is already reserved, so
5461 * adding the ticket space would be a double count.
5463 if (check_overcommit &&
5464 !can_overcommit(fs_info, space_info, 0, flush, false))
5466 if (num_bytes >= ticket->bytes) {
5467 list_del_init(&ticket->list);
5468 num_bytes -= ticket->bytes;
5470 space_info->tickets_id++;
5471 wake_up(&ticket->wait);
5473 ticket->bytes -= num_bytes;
5478 if (num_bytes && head == &space_info->priority_tickets) {
5479 head = &space_info->tickets;
5480 flush = BTRFS_RESERVE_FLUSH_ALL;
5483 update_bytes_may_use(fs_info, space_info, -num_bytes);
5484 trace_btrfs_space_reservation(fs_info, "space_info",
5485 space_info->flags, num_bytes, 0);
5486 spin_unlock(&space_info->lock);
5490 * This is for newly allocated space that isn't accounted in
5491 * space_info->bytes_may_use yet. So if we allocate a chunk or unpin an extent
5492 * we use this helper.
5494 void btrfs_space_info_add_new_bytes(struct btrfs_fs_info *fs_info,
5495 struct btrfs_space_info *space_info,
5498 struct reserve_ticket *ticket;
5499 struct list_head *head = &space_info->priority_tickets;
5502 while (!list_empty(head) && num_bytes) {
5503 ticket = list_first_entry(head, struct reserve_ticket,
5505 if (num_bytes >= ticket->bytes) {
5506 trace_btrfs_space_reservation(fs_info, "space_info",
5509 list_del_init(&ticket->list);
5510 num_bytes -= ticket->bytes;
5511 update_bytes_may_use(fs_info, space_info,
5514 space_info->tickets_id++;
5515 wake_up(&ticket->wait);
5517 trace_btrfs_space_reservation(fs_info, "space_info",
5520 update_bytes_may_use(fs_info, space_info, num_bytes);
5521 ticket->bytes -= num_bytes;
5526 if (num_bytes && head == &space_info->priority_tickets) {
5527 head = &space_info->tickets;
5532 static u64 block_rsv_release_bytes(struct btrfs_fs_info *fs_info,
5533 struct btrfs_block_rsv *block_rsv,
5534 struct btrfs_block_rsv *dest, u64 num_bytes,
5535 u64 *qgroup_to_release_ret)
5537 struct btrfs_space_info *space_info = block_rsv->space_info;
5538 u64 qgroup_to_release = 0;
5541 spin_lock(&block_rsv->lock);
5542 if (num_bytes == (u64)-1) {
5543 num_bytes = block_rsv->size;
5544 qgroup_to_release = block_rsv->qgroup_rsv_size;
5546 block_rsv->size -= num_bytes;
5547 if (block_rsv->reserved >= block_rsv->size) {
5548 num_bytes = block_rsv->reserved - block_rsv->size;
5549 block_rsv->reserved = block_rsv->size;
5550 block_rsv->full = 1;
5554 if (block_rsv->qgroup_rsv_reserved >= block_rsv->qgroup_rsv_size) {
5555 qgroup_to_release = block_rsv->qgroup_rsv_reserved -
5556 block_rsv->qgroup_rsv_size;
5557 block_rsv->qgroup_rsv_reserved = block_rsv->qgroup_rsv_size;
5559 qgroup_to_release = 0;
5561 spin_unlock(&block_rsv->lock);
5564 if (num_bytes > 0) {
5566 spin_lock(&dest->lock);
5570 bytes_to_add = dest->size - dest->reserved;
5571 bytes_to_add = min(num_bytes, bytes_to_add);
5572 dest->reserved += bytes_to_add;
5573 if (dest->reserved >= dest->size)
5575 num_bytes -= bytes_to_add;
5577 spin_unlock(&dest->lock);
5580 btrfs_space_info_add_old_bytes(fs_info, space_info,
5583 if (qgroup_to_release_ret)
5584 *qgroup_to_release_ret = qgroup_to_release;
5588 int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src,
5589 struct btrfs_block_rsv *dst, u64 num_bytes,
5594 ret = block_rsv_use_bytes(src, num_bytes);
5598 block_rsv_add_bytes(dst, num_bytes, update_size);
5602 void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv, unsigned short type)
5604 memset(rsv, 0, sizeof(*rsv));
5605 spin_lock_init(&rsv->lock);
5609 void btrfs_init_metadata_block_rsv(struct btrfs_fs_info *fs_info,
5610 struct btrfs_block_rsv *rsv,
5611 unsigned short type)
5613 btrfs_init_block_rsv(rsv, type);
5614 rsv->space_info = __find_space_info(fs_info,
5615 BTRFS_BLOCK_GROUP_METADATA);
5618 struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_fs_info *fs_info,
5619 unsigned short type)
5621 struct btrfs_block_rsv *block_rsv;
5623 block_rsv = kmalloc(sizeof(*block_rsv), GFP_NOFS);
5627 btrfs_init_metadata_block_rsv(fs_info, block_rsv, type);
5631 void btrfs_free_block_rsv(struct btrfs_fs_info *fs_info,
5632 struct btrfs_block_rsv *rsv)
5636 btrfs_block_rsv_release(fs_info, rsv, (u64)-1);
5640 int btrfs_block_rsv_add(struct btrfs_root *root,
5641 struct btrfs_block_rsv *block_rsv, u64 num_bytes,
5642 enum btrfs_reserve_flush_enum flush)
5649 ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
5651 block_rsv_add_bytes(block_rsv, num_bytes, true);
5656 int btrfs_block_rsv_check(struct btrfs_block_rsv *block_rsv, int min_factor)
5664 spin_lock(&block_rsv->lock);
5665 num_bytes = div_factor(block_rsv->size, min_factor);
5666 if (block_rsv->reserved >= num_bytes)
5668 spin_unlock(&block_rsv->lock);
5673 int btrfs_block_rsv_refill(struct btrfs_root *root,
5674 struct btrfs_block_rsv *block_rsv, u64 min_reserved,
5675 enum btrfs_reserve_flush_enum flush)
5683 spin_lock(&block_rsv->lock);
5684 num_bytes = min_reserved;
5685 if (block_rsv->reserved >= num_bytes)
5688 num_bytes -= block_rsv->reserved;
5689 spin_unlock(&block_rsv->lock);
5694 ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
5696 block_rsv_add_bytes(block_rsv, num_bytes, false);
5703 static u64 __btrfs_block_rsv_release(struct btrfs_fs_info *fs_info,
5704 struct btrfs_block_rsv *block_rsv,
5705 u64 num_bytes, u64 *qgroup_to_release)
5707 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5708 struct btrfs_block_rsv *delayed_rsv = &fs_info->delayed_refs_rsv;
5709 struct btrfs_block_rsv *target = delayed_rsv;
5711 if (target->full || target == block_rsv)
5712 target = global_rsv;
5714 if (block_rsv->space_info != target->space_info)
5717 return block_rsv_release_bytes(fs_info, block_rsv, target, num_bytes,
5721 void btrfs_block_rsv_release(struct btrfs_fs_info *fs_info,
5722 struct btrfs_block_rsv *block_rsv,
5725 __btrfs_block_rsv_release(fs_info, block_rsv, num_bytes, NULL);
5729 * btrfs_inode_rsv_release - release any excessive reservation.
5730 * @inode - the inode we need to release from.
5731 * @qgroup_free - free or convert qgroup meta.
5732 * Unlike normal operation, qgroup meta reservation needs to know if we are
5733 * freeing qgroup reservation or just converting it into per-trans. Normally
5734 * @qgroup_free is true for error handling, and false for normal release.
5736 * This is the same as btrfs_block_rsv_release, except that it handles the
5737 * tracepoint for the reservation.
5739 static void btrfs_inode_rsv_release(struct btrfs_inode *inode, bool qgroup_free)
5741 struct btrfs_fs_info *fs_info = inode->root->fs_info;
5742 struct btrfs_block_rsv *block_rsv = &inode->block_rsv;
5744 u64 qgroup_to_release = 0;
5747 * Since we statically set the block_rsv->size we just want to say we
5748 * are releasing 0 bytes, and then we'll just get the reservation over
5751 released = __btrfs_block_rsv_release(fs_info, block_rsv, 0,
5752 &qgroup_to_release);
5754 trace_btrfs_space_reservation(fs_info, "delalloc",
5755 btrfs_ino(inode), released, 0);
5757 btrfs_qgroup_free_meta_prealloc(inode->root, qgroup_to_release);
5759 btrfs_qgroup_convert_reserved_meta(inode->root,
5764 * btrfs_delayed_refs_rsv_release - release a ref head's reservation.
5765 * @fs_info - the fs_info for our fs.
5766 * @nr - the number of items to drop.
5768 * This drops the delayed ref head's count from the delayed refs rsv and frees
5769 * any excess reservation we had.
5771 void btrfs_delayed_refs_rsv_release(struct btrfs_fs_info *fs_info, int nr)
5773 struct btrfs_block_rsv *block_rsv = &fs_info->delayed_refs_rsv;
5774 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5775 u64 num_bytes = btrfs_calc_trans_metadata_size(fs_info, nr);
5778 released = block_rsv_release_bytes(fs_info, block_rsv, global_rsv,
5781 trace_btrfs_space_reservation(fs_info, "delayed_refs_rsv",
5785 static void update_global_block_rsv(struct btrfs_fs_info *fs_info)
5787 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
5788 struct btrfs_space_info *sinfo = block_rsv->space_info;
5792 * The global block rsv is based on the size of the extent tree, the
5793 * checksum tree and the root tree. If the fs is empty we want to set
5794 * it to a minimal amount for safety.
5796 num_bytes = btrfs_root_used(&fs_info->extent_root->root_item) +
5797 btrfs_root_used(&fs_info->csum_root->root_item) +
5798 btrfs_root_used(&fs_info->tree_root->root_item);
5799 num_bytes = max_t(u64, num_bytes, SZ_16M);
5801 spin_lock(&sinfo->lock);
5802 spin_lock(&block_rsv->lock);
5804 block_rsv->size = min_t(u64, num_bytes, SZ_512M);
5806 if (block_rsv->reserved < block_rsv->size) {
5807 num_bytes = btrfs_space_info_used(sinfo, true);
5808 if (sinfo->total_bytes > num_bytes) {
5809 num_bytes = sinfo->total_bytes - num_bytes;
5810 num_bytes = min(num_bytes,
5811 block_rsv->size - block_rsv->reserved);
5812 block_rsv->reserved += num_bytes;
5813 update_bytes_may_use(fs_info, sinfo, num_bytes);
5814 trace_btrfs_space_reservation(fs_info, "space_info",
5815 sinfo->flags, num_bytes,
5818 } else if (block_rsv->reserved > block_rsv->size) {
5819 num_bytes = block_rsv->reserved - block_rsv->size;
5820 update_bytes_may_use(fs_info, sinfo, -num_bytes);
5821 trace_btrfs_space_reservation(fs_info, "space_info",
5822 sinfo->flags, num_bytes, 0);
5823 block_rsv->reserved = block_rsv->size;
5826 if (block_rsv->reserved == block_rsv->size)
5827 block_rsv->full = 1;
5829 block_rsv->full = 0;
5831 spin_unlock(&block_rsv->lock);
5832 spin_unlock(&sinfo->lock);
5835 static void init_global_block_rsv(struct btrfs_fs_info *fs_info)
5837 struct btrfs_space_info *space_info;
5839 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
5840 fs_info->chunk_block_rsv.space_info = space_info;
5842 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
5843 fs_info->global_block_rsv.space_info = space_info;
5844 fs_info->trans_block_rsv.space_info = space_info;
5845 fs_info->empty_block_rsv.space_info = space_info;
5846 fs_info->delayed_block_rsv.space_info = space_info;
5847 fs_info->delayed_refs_rsv.space_info = space_info;
5849 fs_info->extent_root->block_rsv = &fs_info->delayed_refs_rsv;
5850 fs_info->csum_root->block_rsv = &fs_info->delayed_refs_rsv;
5851 fs_info->dev_root->block_rsv = &fs_info->global_block_rsv;
5852 fs_info->tree_root->block_rsv = &fs_info->global_block_rsv;
5853 if (fs_info->quota_root)
5854 fs_info->quota_root->block_rsv = &fs_info->global_block_rsv;
5855 fs_info->chunk_root->block_rsv = &fs_info->chunk_block_rsv;
5857 update_global_block_rsv(fs_info);
5860 static void release_global_block_rsv(struct btrfs_fs_info *fs_info)
5862 block_rsv_release_bytes(fs_info, &fs_info->global_block_rsv, NULL,
5864 WARN_ON(fs_info->trans_block_rsv.size > 0);
5865 WARN_ON(fs_info->trans_block_rsv.reserved > 0);
5866 WARN_ON(fs_info->chunk_block_rsv.size > 0);
5867 WARN_ON(fs_info->chunk_block_rsv.reserved > 0);
5868 WARN_ON(fs_info->delayed_block_rsv.size > 0);
5869 WARN_ON(fs_info->delayed_block_rsv.reserved > 0);
5870 WARN_ON(fs_info->delayed_refs_rsv.reserved > 0);
5871 WARN_ON(fs_info->delayed_refs_rsv.size > 0);
5875 * btrfs_update_delayed_refs_rsv - adjust the size of the delayed refs rsv
5876 * @trans - the trans that may have generated delayed refs
5878 * This is to be called anytime we may have adjusted trans->delayed_ref_updates,
5879 * it'll calculate the additional size and add it to the delayed_refs_rsv.
5881 void btrfs_update_delayed_refs_rsv(struct btrfs_trans_handle *trans)
5883 struct btrfs_fs_info *fs_info = trans->fs_info;
5884 struct btrfs_block_rsv *delayed_rsv = &fs_info->delayed_refs_rsv;
5887 if (!trans->delayed_ref_updates)
5890 num_bytes = btrfs_calc_trans_metadata_size(fs_info,
5891 trans->delayed_ref_updates);
5892 spin_lock(&delayed_rsv->lock);
5893 delayed_rsv->size += num_bytes;
5894 delayed_rsv->full = 0;
5895 spin_unlock(&delayed_rsv->lock);
5896 trans->delayed_ref_updates = 0;
5900 * To be called after all the new block groups attached to the transaction
5901 * handle have been created (btrfs_create_pending_block_groups()).
5903 void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
5905 struct btrfs_fs_info *fs_info = trans->fs_info;
5907 if (!trans->chunk_bytes_reserved)
5910 WARN_ON_ONCE(!list_empty(&trans->new_bgs));
5912 block_rsv_release_bytes(fs_info, &fs_info->chunk_block_rsv, NULL,
5913 trans->chunk_bytes_reserved, NULL);
5914 trans->chunk_bytes_reserved = 0;
5918 * btrfs_subvolume_reserve_metadata() - reserve space for subvolume operation
5919 * root: the root of the parent directory
5920 * rsv: block reservation
5921 * items: the number of items that we need do reservation
5922 * use_global_rsv: allow fallback to the global block reservation
5924 * This function is used to reserve the space for snapshot/subvolume
5925 * creation and deletion. Those operations are different with the
5926 * common file/directory operations, they change two fs/file trees
5927 * and root tree, the number of items that the qgroup reserves is
5928 * different with the free space reservation. So we can not use
5929 * the space reservation mechanism in start_transaction().
5931 int btrfs_subvolume_reserve_metadata(struct btrfs_root *root,
5932 struct btrfs_block_rsv *rsv, int items,
5933 bool use_global_rsv)
5935 u64 qgroup_num_bytes = 0;
5938 struct btrfs_fs_info *fs_info = root->fs_info;
5939 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5941 if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
5942 /* One for parent inode, two for dir entries */
5943 qgroup_num_bytes = 3 * fs_info->nodesize;
5944 ret = btrfs_qgroup_reserve_meta_prealloc(root,
5945 qgroup_num_bytes, true);
5950 num_bytes = btrfs_calc_trans_metadata_size(fs_info, items);
5951 rsv->space_info = __find_space_info(fs_info,
5952 BTRFS_BLOCK_GROUP_METADATA);
5953 ret = btrfs_block_rsv_add(root, rsv, num_bytes,
5954 BTRFS_RESERVE_FLUSH_ALL);
5956 if (ret == -ENOSPC && use_global_rsv)
5957 ret = btrfs_block_rsv_migrate(global_rsv, rsv, num_bytes, true);
5959 if (ret && qgroup_num_bytes)
5960 btrfs_qgroup_free_meta_prealloc(root, qgroup_num_bytes);
5965 void btrfs_subvolume_release_metadata(struct btrfs_fs_info *fs_info,
5966 struct btrfs_block_rsv *rsv)
5968 btrfs_block_rsv_release(fs_info, rsv, (u64)-1);
5971 static void btrfs_calculate_inode_block_rsv_size(struct btrfs_fs_info *fs_info,
5972 struct btrfs_inode *inode)
5974 struct btrfs_block_rsv *block_rsv = &inode->block_rsv;
5975 u64 reserve_size = 0;
5976 u64 qgroup_rsv_size = 0;
5978 unsigned outstanding_extents;
5980 lockdep_assert_held(&inode->lock);
5981 outstanding_extents = inode->outstanding_extents;
5982 if (outstanding_extents)
5983 reserve_size = btrfs_calc_trans_metadata_size(fs_info,
5984 outstanding_extents + 1);
5985 csum_leaves = btrfs_csum_bytes_to_leaves(fs_info,
5987 reserve_size += btrfs_calc_trans_metadata_size(fs_info,
5990 * For qgroup rsv, the calculation is very simple:
5991 * account one nodesize for each outstanding extent
5993 * This is overestimating in most cases.
5995 qgroup_rsv_size = (u64)outstanding_extents * fs_info->nodesize;
5997 spin_lock(&block_rsv->lock);
5998 block_rsv->size = reserve_size;
5999 block_rsv->qgroup_rsv_size = qgroup_rsv_size;
6000 spin_unlock(&block_rsv->lock);
6003 static void calc_inode_reservations(struct btrfs_fs_info *fs_info,
6004 u64 num_bytes, u64 *meta_reserve,
6005 u64 *qgroup_reserve)
6007 u64 nr_extents = count_max_extents(num_bytes);
6008 u64 csum_leaves = btrfs_csum_bytes_to_leaves(fs_info, num_bytes);
6010 /* We add one for the inode update at finish ordered time */
6011 *meta_reserve = btrfs_calc_trans_metadata_size(fs_info,
6012 nr_extents + csum_leaves + 1);
6013 *qgroup_reserve = nr_extents * fs_info->nodesize;
6016 int btrfs_delalloc_reserve_metadata(struct btrfs_inode *inode, u64 num_bytes)
6018 struct btrfs_root *root = inode->root;
6019 struct btrfs_fs_info *fs_info = root->fs_info;
6020 struct btrfs_block_rsv *block_rsv = &inode->block_rsv;
6021 u64 meta_reserve, qgroup_reserve;
6022 unsigned nr_extents;
6023 enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_FLUSH_ALL;
6025 bool delalloc_lock = true;
6027 /* If we are a free space inode we need to not flush since we will be in
6028 * the middle of a transaction commit. We also don't need the delalloc
6029 * mutex since we won't race with anybody. We need this mostly to make
6030 * lockdep shut its filthy mouth.
6032 * If we have a transaction open (can happen if we call truncate_block
6033 * from truncate), then we need FLUSH_LIMIT so we don't deadlock.
6035 if (btrfs_is_free_space_inode(inode)) {
6036 flush = BTRFS_RESERVE_NO_FLUSH;
6037 delalloc_lock = false;
6039 if (current->journal_info)
6040 flush = BTRFS_RESERVE_FLUSH_LIMIT;
6042 if (btrfs_transaction_in_commit(fs_info))
6043 schedule_timeout(1);
6047 mutex_lock(&inode->delalloc_mutex);
6049 num_bytes = ALIGN(num_bytes, fs_info->sectorsize);
6052 * We always want to do it this way, every other way is wrong and ends
6053 * in tears. Pre-reserving the amount we are going to add will always
6054 * be the right way, because otherwise if we have enough parallelism we
6055 * could end up with thousands of inodes all holding little bits of
6056 * reservations they were able to make previously and the only way to
6057 * reclaim that space is to ENOSPC out the operations and clear
6058 * everything out and try again, which is bad. This way we just
6059 * over-reserve slightly, and clean up the mess when we are done.
6061 calc_inode_reservations(fs_info, num_bytes, &meta_reserve,
6063 ret = btrfs_qgroup_reserve_meta_prealloc(root, qgroup_reserve, true);
6066 ret = reserve_metadata_bytes(root, block_rsv, meta_reserve, flush);
6071 * Now we need to update our outstanding extents and csum bytes _first_
6072 * and then add the reservation to the block_rsv. This keeps us from
6073 * racing with an ordered completion or some such that would think it
6074 * needs to free the reservation we just made.
6076 spin_lock(&inode->lock);
6077 nr_extents = count_max_extents(num_bytes);
6078 btrfs_mod_outstanding_extents(inode, nr_extents);
6079 inode->csum_bytes += num_bytes;
6080 btrfs_calculate_inode_block_rsv_size(fs_info, inode);
6081 spin_unlock(&inode->lock);
6083 /* Now we can safely add our space to our block rsv */
6084 block_rsv_add_bytes(block_rsv, meta_reserve, false);
6085 trace_btrfs_space_reservation(root->fs_info, "delalloc",
6086 btrfs_ino(inode), meta_reserve, 1);
6088 spin_lock(&block_rsv->lock);
6089 block_rsv->qgroup_rsv_reserved += qgroup_reserve;
6090 spin_unlock(&block_rsv->lock);
6093 mutex_unlock(&inode->delalloc_mutex);
6096 btrfs_qgroup_free_meta_prealloc(root, qgroup_reserve);
6098 btrfs_inode_rsv_release(inode, true);
6100 mutex_unlock(&inode->delalloc_mutex);
6105 * btrfs_delalloc_release_metadata - release a metadata reservation for an inode
6106 * @inode: the inode to release the reservation for.
6107 * @num_bytes: the number of bytes we are releasing.
6108 * @qgroup_free: free qgroup reservation or convert it to per-trans reservation
6110 * This will release the metadata reservation for an inode. This can be called
6111 * once we complete IO for a given set of bytes to release their metadata
6112 * reservations, or on error for the same reason.
6114 void btrfs_delalloc_release_metadata(struct btrfs_inode *inode, u64 num_bytes,
6117 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6119 num_bytes = ALIGN(num_bytes, fs_info->sectorsize);
6120 spin_lock(&inode->lock);
6121 inode->csum_bytes -= num_bytes;
6122 btrfs_calculate_inode_block_rsv_size(fs_info, inode);
6123 spin_unlock(&inode->lock);
6125 if (btrfs_is_testing(fs_info))
6128 btrfs_inode_rsv_release(inode, qgroup_free);
6132 * btrfs_delalloc_release_extents - release our outstanding_extents
6133 * @inode: the inode to balance the reservation for.
6134 * @num_bytes: the number of bytes we originally reserved with
6135 * @qgroup_free: do we need to free qgroup meta reservation or convert them.
6137 * When we reserve space we increase outstanding_extents for the extents we may
6138 * add. Once we've set the range as delalloc or created our ordered extents we
6139 * have outstanding_extents to track the real usage, so we use this to free our
6140 * temporarily tracked outstanding_extents. This _must_ be used in conjunction
6141 * with btrfs_delalloc_reserve_metadata.
6143 void btrfs_delalloc_release_extents(struct btrfs_inode *inode, u64 num_bytes,
6146 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6147 unsigned num_extents;
6149 spin_lock(&inode->lock);
6150 num_extents = count_max_extents(num_bytes);
6151 btrfs_mod_outstanding_extents(inode, -num_extents);
6152 btrfs_calculate_inode_block_rsv_size(fs_info, inode);
6153 spin_unlock(&inode->lock);
6155 if (btrfs_is_testing(fs_info))
6158 btrfs_inode_rsv_release(inode, qgroup_free);
6162 * btrfs_delalloc_reserve_space - reserve data and metadata space for
6164 * @inode: inode we're writing to
6165 * @start: start range we are writing to
6166 * @len: how long the range we are writing to
6167 * @reserved: mandatory parameter, record actually reserved qgroup ranges of
6168 * current reservation.
6170 * This will do the following things
6172 * o reserve space in data space info for num bytes
6173 * and reserve precious corresponding qgroup space
6174 * (Done in check_data_free_space)
6176 * o reserve space for metadata space, based on the number of outstanding
6177 * extents and how much csums will be needed
6178 * also reserve metadata space in a per root over-reserve method.
6179 * o add to the inodes->delalloc_bytes
6180 * o add it to the fs_info's delalloc inodes list.
6181 * (Above 3 all done in delalloc_reserve_metadata)
6183 * Return 0 for success
6184 * Return <0 for error(-ENOSPC or -EQUOT)
6186 int btrfs_delalloc_reserve_space(struct inode *inode,
6187 struct extent_changeset **reserved, u64 start, u64 len)
6191 ret = btrfs_check_data_free_space(inode, reserved, start, len);
6194 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len);
6196 btrfs_free_reserved_data_space(inode, *reserved, start, len);
6201 * btrfs_delalloc_release_space - release data and metadata space for delalloc
6202 * @inode: inode we're releasing space for
6203 * @start: start position of the space already reserved
6204 * @len: the len of the space already reserved
6205 * @release_bytes: the len of the space we consumed or didn't use
6207 * This function will release the metadata space that was not used and will
6208 * decrement ->delalloc_bytes and remove it from the fs_info delalloc_inodes
6209 * list if there are no delalloc bytes left.
6210 * Also it will handle the qgroup reserved space.
6212 void btrfs_delalloc_release_space(struct inode *inode,
6213 struct extent_changeset *reserved,
6214 u64 start, u64 len, bool qgroup_free)
6216 btrfs_delalloc_release_metadata(BTRFS_I(inode), len, qgroup_free);
6217 btrfs_free_reserved_data_space(inode, reserved, start, len);
6220 static int update_block_group(struct btrfs_trans_handle *trans,
6221 u64 bytenr, u64 num_bytes, int alloc)
6223 struct btrfs_fs_info *info = trans->fs_info;
6224 struct btrfs_block_group_cache *cache = NULL;
6225 u64 total = num_bytes;
6231 /* block accounting for super block */
6232 spin_lock(&info->delalloc_root_lock);
6233 old_val = btrfs_super_bytes_used(info->super_copy);
6235 old_val += num_bytes;
6237 old_val -= num_bytes;
6238 btrfs_set_super_bytes_used(info->super_copy, old_val);
6239 spin_unlock(&info->delalloc_root_lock);
6242 cache = btrfs_lookup_block_group(info, bytenr);
6247 factor = btrfs_bg_type_to_factor(cache->flags);
6250 * If this block group has free space cache written out, we
6251 * need to make sure to load it if we are removing space. This
6252 * is because we need the unpinning stage to actually add the
6253 * space back to the block group, otherwise we will leak space.
6255 if (!alloc && cache->cached == BTRFS_CACHE_NO)
6256 cache_block_group(cache, 1);
6258 byte_in_group = bytenr - cache->key.objectid;
6259 WARN_ON(byte_in_group > cache->key.offset);
6261 spin_lock(&cache->space_info->lock);
6262 spin_lock(&cache->lock);
6264 if (btrfs_test_opt(info, SPACE_CACHE) &&
6265 cache->disk_cache_state < BTRFS_DC_CLEAR)
6266 cache->disk_cache_state = BTRFS_DC_CLEAR;
6268 old_val = btrfs_block_group_used(&cache->item);
6269 num_bytes = min(total, cache->key.offset - byte_in_group);
6271 old_val += num_bytes;
6272 btrfs_set_block_group_used(&cache->item, old_val);
6273 cache->reserved -= num_bytes;
6274 cache->space_info->bytes_reserved -= num_bytes;
6275 cache->space_info->bytes_used += num_bytes;
6276 cache->space_info->disk_used += num_bytes * factor;
6277 spin_unlock(&cache->lock);
6278 spin_unlock(&cache->space_info->lock);
6280 old_val -= num_bytes;
6281 btrfs_set_block_group_used(&cache->item, old_val);
6282 cache->pinned += num_bytes;
6283 update_bytes_pinned(info, cache->space_info, num_bytes);
6284 cache->space_info->bytes_used -= num_bytes;
6285 cache->space_info->disk_used -= num_bytes * factor;
6286 spin_unlock(&cache->lock);
6287 spin_unlock(&cache->space_info->lock);
6289 trace_btrfs_space_reservation(info, "pinned",
6290 cache->space_info->flags,
6292 percpu_counter_add_batch(&cache->space_info->total_bytes_pinned,
6294 BTRFS_TOTAL_BYTES_PINNED_BATCH);
6295 set_extent_dirty(info->pinned_extents,
6296 bytenr, bytenr + num_bytes - 1,
6297 GFP_NOFS | __GFP_NOFAIL);
6300 spin_lock(&trans->transaction->dirty_bgs_lock);
6301 if (list_empty(&cache->dirty_list)) {
6302 list_add_tail(&cache->dirty_list,
6303 &trans->transaction->dirty_bgs);
6304 trans->delayed_ref_updates++;
6305 btrfs_get_block_group(cache);
6307 spin_unlock(&trans->transaction->dirty_bgs_lock);
6310 * No longer have used bytes in this block group, queue it for
6311 * deletion. We do this after adding the block group to the
6312 * dirty list to avoid races between cleaner kthread and space
6315 if (!alloc && old_val == 0)
6316 btrfs_mark_bg_unused(cache);
6318 btrfs_put_block_group(cache);
6320 bytenr += num_bytes;
6323 /* Modified block groups are accounted for in the delayed_refs_rsv. */
6324 btrfs_update_delayed_refs_rsv(trans);
6328 static u64 first_logical_byte(struct btrfs_fs_info *fs_info, u64 search_start)
6330 struct btrfs_block_group_cache *cache;
6333 spin_lock(&fs_info->block_group_cache_lock);
6334 bytenr = fs_info->first_logical_byte;
6335 spin_unlock(&fs_info->block_group_cache_lock);
6337 if (bytenr < (u64)-1)
6340 cache = btrfs_lookup_first_block_group(fs_info, search_start);
6344 bytenr = cache->key.objectid;
6345 btrfs_put_block_group(cache);
6350 static int pin_down_extent(struct btrfs_block_group_cache *cache,
6351 u64 bytenr, u64 num_bytes, int reserved)
6353 struct btrfs_fs_info *fs_info = cache->fs_info;
6355 spin_lock(&cache->space_info->lock);
6356 spin_lock(&cache->lock);
6357 cache->pinned += num_bytes;
6358 update_bytes_pinned(fs_info, cache->space_info, num_bytes);
6360 cache->reserved -= num_bytes;
6361 cache->space_info->bytes_reserved -= num_bytes;
6363 spin_unlock(&cache->lock);
6364 spin_unlock(&cache->space_info->lock);
6366 trace_btrfs_space_reservation(fs_info, "pinned",
6367 cache->space_info->flags, num_bytes, 1);
6368 percpu_counter_add_batch(&cache->space_info->total_bytes_pinned,
6369 num_bytes, BTRFS_TOTAL_BYTES_PINNED_BATCH);
6370 set_extent_dirty(fs_info->pinned_extents, bytenr,
6371 bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
6376 * this function must be called within transaction
6378 int btrfs_pin_extent(struct btrfs_fs_info *fs_info,
6379 u64 bytenr, u64 num_bytes, int reserved)
6381 struct btrfs_block_group_cache *cache;
6383 cache = btrfs_lookup_block_group(fs_info, bytenr);
6384 BUG_ON(!cache); /* Logic error */
6386 pin_down_extent(cache, bytenr, num_bytes, reserved);
6388 btrfs_put_block_group(cache);
6393 * this function must be called within transaction
6395 int btrfs_pin_extent_for_log_replay(struct btrfs_fs_info *fs_info,
6396 u64 bytenr, u64 num_bytes)
6398 struct btrfs_block_group_cache *cache;
6401 cache = btrfs_lookup_block_group(fs_info, bytenr);
6406 * pull in the free space cache (if any) so that our pin
6407 * removes the free space from the cache. We have load_only set
6408 * to one because the slow code to read in the free extents does check
6409 * the pinned extents.
6411 cache_block_group(cache, 1);
6413 pin_down_extent(cache, bytenr, num_bytes, 0);
6415 /* remove us from the free space cache (if we're there at all) */
6416 ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
6417 btrfs_put_block_group(cache);
6421 static int __exclude_logged_extent(struct btrfs_fs_info *fs_info,
6422 u64 start, u64 num_bytes)
6425 struct btrfs_block_group_cache *block_group;
6426 struct btrfs_caching_control *caching_ctl;
6428 block_group = btrfs_lookup_block_group(fs_info, start);
6432 cache_block_group(block_group, 0);
6433 caching_ctl = get_caching_control(block_group);
6437 BUG_ON(!block_group_cache_done(block_group));
6438 ret = btrfs_remove_free_space(block_group, start, num_bytes);
6440 mutex_lock(&caching_ctl->mutex);
6442 if (start >= caching_ctl->progress) {
6443 ret = add_excluded_extent(fs_info, start, num_bytes);
6444 } else if (start + num_bytes <= caching_ctl->progress) {
6445 ret = btrfs_remove_free_space(block_group,
6448 num_bytes = caching_ctl->progress - start;
6449 ret = btrfs_remove_free_space(block_group,
6454 num_bytes = (start + num_bytes) -
6455 caching_ctl->progress;
6456 start = caching_ctl->progress;
6457 ret = add_excluded_extent(fs_info, start, num_bytes);
6460 mutex_unlock(&caching_ctl->mutex);
6461 put_caching_control(caching_ctl);
6463 btrfs_put_block_group(block_group);
6467 int btrfs_exclude_logged_extents(struct extent_buffer *eb)
6469 struct btrfs_fs_info *fs_info = eb->fs_info;
6470 struct btrfs_file_extent_item *item;
6471 struct btrfs_key key;
6476 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS))
6479 for (i = 0; i < btrfs_header_nritems(eb); i++) {
6480 btrfs_item_key_to_cpu(eb, &key, i);
6481 if (key.type != BTRFS_EXTENT_DATA_KEY)
6483 item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
6484 found_type = btrfs_file_extent_type(eb, item);
6485 if (found_type == BTRFS_FILE_EXTENT_INLINE)
6487 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
6489 key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
6490 key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
6491 ret = __exclude_logged_extent(fs_info, key.objectid, key.offset);
6500 btrfs_inc_block_group_reservations(struct btrfs_block_group_cache *bg)
6502 atomic_inc(&bg->reservations);
6505 void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
6508 struct btrfs_block_group_cache *bg;
6510 bg = btrfs_lookup_block_group(fs_info, start);
6512 if (atomic_dec_and_test(&bg->reservations))
6513 wake_up_var(&bg->reservations);
6514 btrfs_put_block_group(bg);
6517 void btrfs_wait_block_group_reservations(struct btrfs_block_group_cache *bg)
6519 struct btrfs_space_info *space_info = bg->space_info;
6523 if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
6527 * Our block group is read only but before we set it to read only,
6528 * some task might have had allocated an extent from it already, but it
6529 * has not yet created a respective ordered extent (and added it to a
6530 * root's list of ordered extents).
6531 * Therefore wait for any task currently allocating extents, since the
6532 * block group's reservations counter is incremented while a read lock
6533 * on the groups' semaphore is held and decremented after releasing
6534 * the read access on that semaphore and creating the ordered extent.
6536 down_write(&space_info->groups_sem);
6537 up_write(&space_info->groups_sem);
6539 wait_var_event(&bg->reservations, !atomic_read(&bg->reservations));
6543 * btrfs_add_reserved_bytes - update the block_group and space info counters
6544 * @cache: The cache we are manipulating
6545 * @ram_bytes: The number of bytes of file content, and will be same to
6546 * @num_bytes except for the compress path.
6547 * @num_bytes: The number of bytes in question
6548 * @delalloc: The blocks are allocated for the delalloc write
6550 * This is called by the allocator when it reserves space. If this is a
6551 * reservation and the block group has become read only we cannot make the
6552 * reservation and return -EAGAIN, otherwise this function always succeeds.
6554 static int btrfs_add_reserved_bytes(struct btrfs_block_group_cache *cache,
6555 u64 ram_bytes, u64 num_bytes, int delalloc)
6557 struct btrfs_space_info *space_info = cache->space_info;
6560 spin_lock(&space_info->lock);
6561 spin_lock(&cache->lock);
6565 cache->reserved += num_bytes;
6566 space_info->bytes_reserved += num_bytes;
6567 update_bytes_may_use(cache->fs_info, space_info, -ram_bytes);
6569 cache->delalloc_bytes += num_bytes;
6571 spin_unlock(&cache->lock);
6572 spin_unlock(&space_info->lock);
6577 * btrfs_free_reserved_bytes - update the block_group and space info counters
6578 * @cache: The cache we are manipulating
6579 * @num_bytes: The number of bytes in question
6580 * @delalloc: The blocks are allocated for the delalloc write
6582 * This is called by somebody who is freeing space that was never actually used
6583 * on disk. For example if you reserve some space for a new leaf in transaction
6584 * A and before transaction A commits you free that leaf, you call this with
6585 * reserve set to 0 in order to clear the reservation.
6588 static void btrfs_free_reserved_bytes(struct btrfs_block_group_cache *cache,
6589 u64 num_bytes, int delalloc)
6591 struct btrfs_space_info *space_info = cache->space_info;
6593 spin_lock(&space_info->lock);
6594 spin_lock(&cache->lock);
6596 space_info->bytes_readonly += num_bytes;
6597 cache->reserved -= num_bytes;
6598 space_info->bytes_reserved -= num_bytes;
6599 space_info->max_extent_size = 0;
6602 cache->delalloc_bytes -= num_bytes;
6603 spin_unlock(&cache->lock);
6604 spin_unlock(&space_info->lock);
6606 void btrfs_prepare_extent_commit(struct btrfs_fs_info *fs_info)
6608 struct btrfs_caching_control *next;
6609 struct btrfs_caching_control *caching_ctl;
6610 struct btrfs_block_group_cache *cache;
6612 down_write(&fs_info->commit_root_sem);
6614 list_for_each_entry_safe(caching_ctl, next,
6615 &fs_info->caching_block_groups, list) {
6616 cache = caching_ctl->block_group;
6617 if (block_group_cache_done(cache)) {
6618 cache->last_byte_to_unpin = (u64)-1;
6619 list_del_init(&caching_ctl->list);
6620 put_caching_control(caching_ctl);
6622 cache->last_byte_to_unpin = caching_ctl->progress;
6626 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
6627 fs_info->pinned_extents = &fs_info->freed_extents[1];
6629 fs_info->pinned_extents = &fs_info->freed_extents[0];
6631 up_write(&fs_info->commit_root_sem);
6633 update_global_block_rsv(fs_info);
6637 * Returns the free cluster for the given space info and sets empty_cluster to
6638 * what it should be based on the mount options.
6640 static struct btrfs_free_cluster *
6641 fetch_cluster_info(struct btrfs_fs_info *fs_info,
6642 struct btrfs_space_info *space_info, u64 *empty_cluster)
6644 struct btrfs_free_cluster *ret = NULL;
6647 if (btrfs_mixed_space_info(space_info))
6650 if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
6651 ret = &fs_info->meta_alloc_cluster;
6652 if (btrfs_test_opt(fs_info, SSD))
6653 *empty_cluster = SZ_2M;
6655 *empty_cluster = SZ_64K;
6656 } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) &&
6657 btrfs_test_opt(fs_info, SSD_SPREAD)) {
6658 *empty_cluster = SZ_2M;
6659 ret = &fs_info->data_alloc_cluster;
6665 static int unpin_extent_range(struct btrfs_fs_info *fs_info,
6667 const bool return_free_space)
6669 struct btrfs_block_group_cache *cache = NULL;
6670 struct btrfs_space_info *space_info;
6671 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
6672 struct btrfs_free_cluster *cluster = NULL;
6674 u64 total_unpinned = 0;
6675 u64 empty_cluster = 0;
6678 while (start <= end) {
6681 start >= cache->key.objectid + cache->key.offset) {
6683 btrfs_put_block_group(cache);
6685 cache = btrfs_lookup_block_group(fs_info, start);
6686 BUG_ON(!cache); /* Logic error */
6688 cluster = fetch_cluster_info(fs_info,
6691 empty_cluster <<= 1;
6694 len = cache->key.objectid + cache->key.offset - start;
6695 len = min(len, end + 1 - start);
6697 if (start < cache->last_byte_to_unpin) {
6698 len = min(len, cache->last_byte_to_unpin - start);
6699 if (return_free_space)
6700 btrfs_add_free_space(cache, start, len);
6704 total_unpinned += len;
6705 space_info = cache->space_info;
6708 * If this space cluster has been marked as fragmented and we've
6709 * unpinned enough in this block group to potentially allow a
6710 * cluster to be created inside of it go ahead and clear the
6713 if (cluster && cluster->fragmented &&
6714 total_unpinned > empty_cluster) {
6715 spin_lock(&cluster->lock);
6716 cluster->fragmented = 0;
6717 spin_unlock(&cluster->lock);
6720 spin_lock(&space_info->lock);
6721 spin_lock(&cache->lock);
6722 cache->pinned -= len;
6723 update_bytes_pinned(fs_info, space_info, -len);
6725 trace_btrfs_space_reservation(fs_info, "pinned",
6726 space_info->flags, len, 0);
6727 space_info->max_extent_size = 0;
6728 percpu_counter_add_batch(&space_info->total_bytes_pinned,
6729 -len, BTRFS_TOTAL_BYTES_PINNED_BATCH);
6731 space_info->bytes_readonly += len;
6734 spin_unlock(&cache->lock);
6735 if (!readonly && return_free_space &&
6736 global_rsv->space_info == space_info) {
6739 spin_lock(&global_rsv->lock);
6740 if (!global_rsv->full) {
6741 to_add = min(len, global_rsv->size -
6742 global_rsv->reserved);
6743 global_rsv->reserved += to_add;
6744 update_bytes_may_use(fs_info, space_info,
6746 if (global_rsv->reserved >= global_rsv->size)
6747 global_rsv->full = 1;
6748 trace_btrfs_space_reservation(fs_info,
6754 spin_unlock(&global_rsv->lock);
6755 /* Add to any tickets we may have */
6757 btrfs_space_info_add_new_bytes(fs_info,
6760 spin_unlock(&space_info->lock);
6764 btrfs_put_block_group(cache);
6768 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans)
6770 struct btrfs_fs_info *fs_info = trans->fs_info;
6771 struct btrfs_block_group_cache *block_group, *tmp;
6772 struct list_head *deleted_bgs;
6773 struct extent_io_tree *unpin;
6778 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
6779 unpin = &fs_info->freed_extents[1];
6781 unpin = &fs_info->freed_extents[0];
6783 while (!trans->aborted) {
6784 struct extent_state *cached_state = NULL;
6786 mutex_lock(&fs_info->unused_bg_unpin_mutex);
6787 ret = find_first_extent_bit(unpin, 0, &start, &end,
6788 EXTENT_DIRTY, &cached_state);
6790 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
6794 if (btrfs_test_opt(fs_info, DISCARD))
6795 ret = btrfs_discard_extent(fs_info, start,
6796 end + 1 - start, NULL);
6798 clear_extent_dirty(unpin, start, end, &cached_state);
6799 unpin_extent_range(fs_info, start, end, true);
6800 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
6801 free_extent_state(cached_state);
6806 * Transaction is finished. We don't need the lock anymore. We
6807 * do need to clean up the block groups in case of a transaction
6810 deleted_bgs = &trans->transaction->deleted_bgs;
6811 list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
6815 if (!trans->aborted)
6816 ret = btrfs_discard_extent(fs_info,
6817 block_group->key.objectid,
6818 block_group->key.offset,
6821 list_del_init(&block_group->bg_list);
6822 btrfs_put_block_group_trimming(block_group);
6823 btrfs_put_block_group(block_group);
6826 const char *errstr = btrfs_decode_error(ret);
6828 "discard failed while removing blockgroup: errno=%d %s",
6836 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
6837 struct btrfs_delayed_ref_node *node, u64 parent,
6838 u64 root_objectid, u64 owner_objectid,
6839 u64 owner_offset, int refs_to_drop,
6840 struct btrfs_delayed_extent_op *extent_op)
6842 struct btrfs_fs_info *info = trans->fs_info;
6843 struct btrfs_key key;
6844 struct btrfs_path *path;
6845 struct btrfs_root *extent_root = info->extent_root;
6846 struct extent_buffer *leaf;
6847 struct btrfs_extent_item *ei;
6848 struct btrfs_extent_inline_ref *iref;
6851 int extent_slot = 0;
6852 int found_extent = 0;
6856 u64 bytenr = node->bytenr;
6857 u64 num_bytes = node->num_bytes;
6859 bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA);
6861 path = btrfs_alloc_path();
6865 path->reada = READA_FORWARD;
6866 path->leave_spinning = 1;
6868 is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
6869 BUG_ON(!is_data && refs_to_drop != 1);
6872 skinny_metadata = false;
6874 ret = lookup_extent_backref(trans, path, &iref, bytenr, num_bytes,
6875 parent, root_objectid, owner_objectid,
6878 extent_slot = path->slots[0];
6879 while (extent_slot >= 0) {
6880 btrfs_item_key_to_cpu(path->nodes[0], &key,
6882 if (key.objectid != bytenr)
6884 if (key.type == BTRFS_EXTENT_ITEM_KEY &&
6885 key.offset == num_bytes) {
6889 if (key.type == BTRFS_METADATA_ITEM_KEY &&
6890 key.offset == owner_objectid) {
6894 if (path->slots[0] - extent_slot > 5)
6899 if (!found_extent) {
6901 ret = remove_extent_backref(trans, path, NULL,
6903 is_data, &last_ref);
6905 btrfs_abort_transaction(trans, ret);
6908 btrfs_release_path(path);
6909 path->leave_spinning = 1;
6911 key.objectid = bytenr;
6912 key.type = BTRFS_EXTENT_ITEM_KEY;
6913 key.offset = num_bytes;
6915 if (!is_data && skinny_metadata) {
6916 key.type = BTRFS_METADATA_ITEM_KEY;
6917 key.offset = owner_objectid;
6920 ret = btrfs_search_slot(trans, extent_root,
6922 if (ret > 0 && skinny_metadata && path->slots[0]) {
6924 * Couldn't find our skinny metadata item,
6925 * see if we have ye olde extent item.
6928 btrfs_item_key_to_cpu(path->nodes[0], &key,
6930 if (key.objectid == bytenr &&
6931 key.type == BTRFS_EXTENT_ITEM_KEY &&
6932 key.offset == num_bytes)
6936 if (ret > 0 && skinny_metadata) {
6937 skinny_metadata = false;
6938 key.objectid = bytenr;
6939 key.type = BTRFS_EXTENT_ITEM_KEY;
6940 key.offset = num_bytes;
6941 btrfs_release_path(path);
6942 ret = btrfs_search_slot(trans, extent_root,
6948 "umm, got %d back from search, was looking for %llu",
6951 btrfs_print_leaf(path->nodes[0]);
6954 btrfs_abort_transaction(trans, ret);
6957 extent_slot = path->slots[0];
6959 } else if (WARN_ON(ret == -ENOENT)) {
6960 btrfs_print_leaf(path->nodes[0]);
6962 "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu",
6963 bytenr, parent, root_objectid, owner_objectid,
6965 btrfs_abort_transaction(trans, ret);
6968 btrfs_abort_transaction(trans, ret);
6972 leaf = path->nodes[0];
6973 item_size = btrfs_item_size_nr(leaf, extent_slot);
6974 if (unlikely(item_size < sizeof(*ei))) {
6976 btrfs_print_v0_err(info);
6977 btrfs_abort_transaction(trans, ret);
6980 ei = btrfs_item_ptr(leaf, extent_slot,
6981 struct btrfs_extent_item);
6982 if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
6983 key.type == BTRFS_EXTENT_ITEM_KEY) {
6984 struct btrfs_tree_block_info *bi;
6985 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
6986 bi = (struct btrfs_tree_block_info *)(ei + 1);
6987 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
6990 refs = btrfs_extent_refs(leaf, ei);
6991 if (refs < refs_to_drop) {
6993 "trying to drop %d refs but we only have %Lu for bytenr %Lu",
6994 refs_to_drop, refs, bytenr);
6996 btrfs_abort_transaction(trans, ret);
6999 refs -= refs_to_drop;
7003 __run_delayed_extent_op(extent_op, leaf, ei);
7005 * In the case of inline back ref, reference count will
7006 * be updated by remove_extent_backref
7009 BUG_ON(!found_extent);
7011 btrfs_set_extent_refs(leaf, ei, refs);
7012 btrfs_mark_buffer_dirty(leaf);
7015 ret = remove_extent_backref(trans, path, iref,
7016 refs_to_drop, is_data,
7019 btrfs_abort_transaction(trans, ret);
7025 BUG_ON(is_data && refs_to_drop !=
7026 extent_data_ref_count(path, iref));
7028 BUG_ON(path->slots[0] != extent_slot);
7030 BUG_ON(path->slots[0] != extent_slot + 1);
7031 path->slots[0] = extent_slot;
7037 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
7040 btrfs_abort_transaction(trans, ret);
7043 btrfs_release_path(path);
7046 ret = btrfs_del_csums(trans, info, bytenr, num_bytes);
7048 btrfs_abort_transaction(trans, ret);
7053 ret = add_to_free_space_tree(trans, bytenr, num_bytes);
7055 btrfs_abort_transaction(trans, ret);
7059 ret = update_block_group(trans, bytenr, num_bytes, 0);
7061 btrfs_abort_transaction(trans, ret);
7065 btrfs_release_path(path);
7068 btrfs_free_path(path);
7073 * when we free an block, it is possible (and likely) that we free the last
7074 * delayed ref for that extent as well. This searches the delayed ref tree for
7075 * a given extent, and if there are no other delayed refs to be processed, it
7076 * removes it from the tree.
7078 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
7081 struct btrfs_delayed_ref_head *head;
7082 struct btrfs_delayed_ref_root *delayed_refs;
7085 delayed_refs = &trans->transaction->delayed_refs;
7086 spin_lock(&delayed_refs->lock);
7087 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
7089 goto out_delayed_unlock;
7091 spin_lock(&head->lock);
7092 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root))
7095 if (cleanup_extent_op(head) != NULL)
7099 * waiting for the lock here would deadlock. If someone else has it
7100 * locked they are already in the process of dropping it anyway
7102 if (!mutex_trylock(&head->mutex))
7105 btrfs_delete_ref_head(delayed_refs, head);
7106 head->processing = 0;
7108 spin_unlock(&head->lock);
7109 spin_unlock(&delayed_refs->lock);
7111 BUG_ON(head->extent_op);
7112 if (head->must_insert_reserved)
7115 btrfs_cleanup_ref_head_accounting(trans->fs_info, delayed_refs, head);
7116 mutex_unlock(&head->mutex);
7117 btrfs_put_delayed_ref_head(head);
7120 spin_unlock(&head->lock);
7123 spin_unlock(&delayed_refs->lock);
7127 void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
7128 struct btrfs_root *root,
7129 struct extent_buffer *buf,
7130 u64 parent, int last_ref)
7132 struct btrfs_fs_info *fs_info = root->fs_info;
7133 struct btrfs_ref generic_ref = { 0 };
7137 btrfs_init_generic_ref(&generic_ref, BTRFS_DROP_DELAYED_REF,
7138 buf->start, buf->len, parent);
7139 btrfs_init_tree_ref(&generic_ref, btrfs_header_level(buf),
7140 root->root_key.objectid);
7142 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
7143 int old_ref_mod, new_ref_mod;
7145 btrfs_ref_tree_mod(fs_info, &generic_ref);
7146 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, NULL,
7147 &old_ref_mod, &new_ref_mod);
7148 BUG_ON(ret); /* -ENOMEM */
7149 pin = old_ref_mod >= 0 && new_ref_mod < 0;
7152 if (last_ref && btrfs_header_generation(buf) == trans->transid) {
7153 struct btrfs_block_group_cache *cache;
7155 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
7156 ret = check_ref_cleanup(trans, buf->start);
7162 cache = btrfs_lookup_block_group(fs_info, buf->start);
7164 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
7165 pin_down_extent(cache, buf->start, buf->len, 1);
7166 btrfs_put_block_group(cache);
7170 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
7172 btrfs_add_free_space(cache, buf->start, buf->len);
7173 btrfs_free_reserved_bytes(cache, buf->len, 0);
7174 btrfs_put_block_group(cache);
7175 trace_btrfs_reserved_extent_free(fs_info, buf->start, buf->len);
7179 add_pinned_bytes(fs_info, &generic_ref);
7183 * Deleting the buffer, clear the corrupt flag since it doesn't
7186 clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
7190 /* Can return -ENOMEM */
7191 int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_ref *ref)
7193 struct btrfs_fs_info *fs_info = trans->fs_info;
7194 int old_ref_mod, new_ref_mod;
7197 if (btrfs_is_testing(fs_info))
7201 * tree log blocks never actually go into the extent allocation
7202 * tree, just update pinning info and exit early.
7204 if ((ref->type == BTRFS_REF_METADATA &&
7205 ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID) ||
7206 (ref->type == BTRFS_REF_DATA &&
7207 ref->data_ref.ref_root == BTRFS_TREE_LOG_OBJECTID)) {
7208 /* unlocks the pinned mutex */
7209 btrfs_pin_extent(fs_info, ref->bytenr, ref->len, 1);
7210 old_ref_mod = new_ref_mod = 0;
7212 } else if (ref->type == BTRFS_REF_METADATA) {
7213 ret = btrfs_add_delayed_tree_ref(trans, ref, NULL,
7214 &old_ref_mod, &new_ref_mod);
7216 ret = btrfs_add_delayed_data_ref(trans, ref, 0,
7217 &old_ref_mod, &new_ref_mod);
7220 if (!((ref->type == BTRFS_REF_METADATA &&
7221 ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID) ||
7222 (ref->type == BTRFS_REF_DATA &&
7223 ref->data_ref.ref_root == BTRFS_TREE_LOG_OBJECTID)))
7224 btrfs_ref_tree_mod(fs_info, ref);
7226 if (ret == 0 && old_ref_mod >= 0 && new_ref_mod < 0)
7227 add_pinned_bytes(fs_info, ref);
7233 * when we wait for progress in the block group caching, its because
7234 * our allocation attempt failed at least once. So, we must sleep
7235 * and let some progress happen before we try again.
7237 * This function will sleep at least once waiting for new free space to
7238 * show up, and then it will check the block group free space numbers
7239 * for our min num_bytes. Another option is to have it go ahead
7240 * and look in the rbtree for a free extent of a given size, but this
7243 * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
7244 * any of the information in this block group.
7246 static noinline void
7247 wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
7250 struct btrfs_caching_control *caching_ctl;
7252 caching_ctl = get_caching_control(cache);
7256 wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
7257 (cache->free_space_ctl->free_space >= num_bytes));
7259 put_caching_control(caching_ctl);
7263 wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
7265 struct btrfs_caching_control *caching_ctl;
7268 caching_ctl = get_caching_control(cache);
7270 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
7272 wait_event(caching_ctl->wait, block_group_cache_done(cache));
7273 if (cache->cached == BTRFS_CACHE_ERROR)
7275 put_caching_control(caching_ctl);
7279 enum btrfs_loop_type {
7280 LOOP_CACHING_NOWAIT,
7287 btrfs_lock_block_group(struct btrfs_block_group_cache *cache,
7291 down_read(&cache->data_rwsem);
7295 btrfs_grab_block_group(struct btrfs_block_group_cache *cache,
7298 btrfs_get_block_group(cache);
7300 down_read(&cache->data_rwsem);
7303 static struct btrfs_block_group_cache *
7304 btrfs_lock_cluster(struct btrfs_block_group_cache *block_group,
7305 struct btrfs_free_cluster *cluster,
7308 struct btrfs_block_group_cache *used_bg = NULL;
7310 spin_lock(&cluster->refill_lock);
7312 used_bg = cluster->block_group;
7316 if (used_bg == block_group)
7319 btrfs_get_block_group(used_bg);
7324 if (down_read_trylock(&used_bg->data_rwsem))
7327 spin_unlock(&cluster->refill_lock);
7329 /* We should only have one-level nested. */
7330 down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING);
7332 spin_lock(&cluster->refill_lock);
7333 if (used_bg == cluster->block_group)
7336 up_read(&used_bg->data_rwsem);
7337 btrfs_put_block_group(used_bg);
7342 btrfs_release_block_group(struct btrfs_block_group_cache *cache,
7346 up_read(&cache->data_rwsem);
7347 btrfs_put_block_group(cache);
7351 * Structure used internally for find_free_extent() function. Wraps needed
7354 struct find_free_extent_ctl {
7355 /* Basic allocation info */
7362 /* Where to start the search inside the bg */
7365 /* For clustered allocation */
7368 bool have_caching_bg;
7369 bool orig_have_caching_bg;
7371 /* RAID index, converted from flags */
7375 * Current loop number, check find_free_extent_update_loop() for details
7380 * Whether we're refilling a cluster, if true we need to re-search
7381 * current block group but don't try to refill the cluster again.
7383 bool retry_clustered;
7386 * Whether we're updating free space cache, if true we need to re-search
7387 * current block group but don't try updating free space cache again.
7389 bool retry_unclustered;
7391 /* If current block group is cached */
7394 /* Max contiguous hole found */
7395 u64 max_extent_size;
7397 /* Total free space from free space cache, not always contiguous */
7398 u64 total_free_space;
7406 * Helper function for find_free_extent().
7408 * Return -ENOENT to inform caller that we need fallback to unclustered mode.
7409 * Return -EAGAIN to inform caller that we need to re-search this block group
7410 * Return >0 to inform caller that we find nothing
7411 * Return 0 means we have found a location and set ffe_ctl->found_offset.
7413 static int find_free_extent_clustered(struct btrfs_block_group_cache *bg,
7414 struct btrfs_free_cluster *last_ptr,
7415 struct find_free_extent_ctl *ffe_ctl,
7416 struct btrfs_block_group_cache **cluster_bg_ret)
7418 struct btrfs_block_group_cache *cluster_bg;
7419 u64 aligned_cluster;
7423 cluster_bg = btrfs_lock_cluster(bg, last_ptr, ffe_ctl->delalloc);
7425 goto refill_cluster;
7426 if (cluster_bg != bg && (cluster_bg->ro ||
7427 !block_group_bits(cluster_bg, ffe_ctl->flags)))
7428 goto release_cluster;
7430 offset = btrfs_alloc_from_cluster(cluster_bg, last_ptr,
7431 ffe_ctl->num_bytes, cluster_bg->key.objectid,
7432 &ffe_ctl->max_extent_size);
7434 /* We have a block, we're done */
7435 spin_unlock(&last_ptr->refill_lock);
7436 trace_btrfs_reserve_extent_cluster(cluster_bg,
7437 ffe_ctl->search_start, ffe_ctl->num_bytes);
7438 *cluster_bg_ret = cluster_bg;
7439 ffe_ctl->found_offset = offset;
7442 WARN_ON(last_ptr->block_group != cluster_bg);
7446 * If we are on LOOP_NO_EMPTY_SIZE, we can't set up a new clusters, so
7447 * lets just skip it and let the allocator find whatever block it can
7448 * find. If we reach this point, we will have tried the cluster
7449 * allocator plenty of times and not have found anything, so we are
7450 * likely way too fragmented for the clustering stuff to find anything.
7452 * However, if the cluster is taken from the current block group,
7453 * release the cluster first, so that we stand a better chance of
7454 * succeeding in the unclustered allocation.
7456 if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE && cluster_bg != bg) {
7457 spin_unlock(&last_ptr->refill_lock);
7458 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
7462 /* This cluster didn't work out, free it and start over */
7463 btrfs_return_cluster_to_free_space(NULL, last_ptr);
7465 if (cluster_bg != bg)
7466 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
7469 if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE) {
7470 spin_unlock(&last_ptr->refill_lock);
7474 aligned_cluster = max_t(u64,
7475 ffe_ctl->empty_cluster + ffe_ctl->empty_size,
7476 bg->full_stripe_len);
7477 ret = btrfs_find_space_cluster(bg, last_ptr, ffe_ctl->search_start,
7478 ffe_ctl->num_bytes, aligned_cluster);
7480 /* Now pull our allocation out of this cluster */
7481 offset = btrfs_alloc_from_cluster(bg, last_ptr,
7482 ffe_ctl->num_bytes, ffe_ctl->search_start,
7483 &ffe_ctl->max_extent_size);
7485 /* We found one, proceed */
7486 spin_unlock(&last_ptr->refill_lock);
7487 trace_btrfs_reserve_extent_cluster(bg,
7488 ffe_ctl->search_start,
7489 ffe_ctl->num_bytes);
7490 ffe_ctl->found_offset = offset;
7493 } else if (!ffe_ctl->cached && ffe_ctl->loop > LOOP_CACHING_NOWAIT &&
7494 !ffe_ctl->retry_clustered) {
7495 spin_unlock(&last_ptr->refill_lock);
7497 ffe_ctl->retry_clustered = true;
7498 wait_block_group_cache_progress(bg, ffe_ctl->num_bytes +
7499 ffe_ctl->empty_cluster + ffe_ctl->empty_size);
7503 * At this point we either didn't find a cluster or we weren't able to
7504 * allocate a block from our cluster. Free the cluster we've been
7505 * trying to use, and go to the next block group.
7507 btrfs_return_cluster_to_free_space(NULL, last_ptr);
7508 spin_unlock(&last_ptr->refill_lock);
7513 * Return >0 to inform caller that we find nothing
7514 * Return 0 when we found an free extent and set ffe_ctrl->found_offset
7515 * Return -EAGAIN to inform caller that we need to re-search this block group
7517 static int find_free_extent_unclustered(struct btrfs_block_group_cache *bg,
7518 struct btrfs_free_cluster *last_ptr,
7519 struct find_free_extent_ctl *ffe_ctl)
7524 * We are doing an unclustered allocation, set the fragmented flag so
7525 * we don't bother trying to setup a cluster again until we get more
7528 if (unlikely(last_ptr)) {
7529 spin_lock(&last_ptr->lock);
7530 last_ptr->fragmented = 1;
7531 spin_unlock(&last_ptr->lock);
7533 if (ffe_ctl->cached) {
7534 struct btrfs_free_space_ctl *free_space_ctl;
7536 free_space_ctl = bg->free_space_ctl;
7537 spin_lock(&free_space_ctl->tree_lock);
7538 if (free_space_ctl->free_space <
7539 ffe_ctl->num_bytes + ffe_ctl->empty_cluster +
7540 ffe_ctl->empty_size) {
7541 ffe_ctl->total_free_space = max_t(u64,
7542 ffe_ctl->total_free_space,
7543 free_space_ctl->free_space);
7544 spin_unlock(&free_space_ctl->tree_lock);
7547 spin_unlock(&free_space_ctl->tree_lock);
7550 offset = btrfs_find_space_for_alloc(bg, ffe_ctl->search_start,
7551 ffe_ctl->num_bytes, ffe_ctl->empty_size,
7552 &ffe_ctl->max_extent_size);
7555 * If we didn't find a chunk, and we haven't failed on this block group
7556 * before, and this block group is in the middle of caching and we are
7557 * ok with waiting, then go ahead and wait for progress to be made, and
7558 * set @retry_unclustered to true.
7560 * If @retry_unclustered is true then we've already waited on this
7561 * block group once and should move on to the next block group.
7563 if (!offset && !ffe_ctl->retry_unclustered && !ffe_ctl->cached &&
7564 ffe_ctl->loop > LOOP_CACHING_NOWAIT) {
7565 wait_block_group_cache_progress(bg, ffe_ctl->num_bytes +
7566 ffe_ctl->empty_size);
7567 ffe_ctl->retry_unclustered = true;
7569 } else if (!offset) {
7572 ffe_ctl->found_offset = offset;
7577 * Return >0 means caller needs to re-search for free extent
7578 * Return 0 means we have the needed free extent.
7579 * Return <0 means we failed to locate any free extent.
7581 static int find_free_extent_update_loop(struct btrfs_fs_info *fs_info,
7582 struct btrfs_free_cluster *last_ptr,
7583 struct btrfs_key *ins,
7584 struct find_free_extent_ctl *ffe_ctl,
7585 int full_search, bool use_cluster)
7587 struct btrfs_root *root = fs_info->extent_root;
7590 if ((ffe_ctl->loop == LOOP_CACHING_NOWAIT) &&
7591 ffe_ctl->have_caching_bg && !ffe_ctl->orig_have_caching_bg)
7592 ffe_ctl->orig_have_caching_bg = true;
7594 if (!ins->objectid && ffe_ctl->loop >= LOOP_CACHING_WAIT &&
7595 ffe_ctl->have_caching_bg)
7598 if (!ins->objectid && ++(ffe_ctl->index) < BTRFS_NR_RAID_TYPES)
7601 if (ins->objectid) {
7602 if (!use_cluster && last_ptr) {
7603 spin_lock(&last_ptr->lock);
7604 last_ptr->window_start = ins->objectid;
7605 spin_unlock(&last_ptr->lock);
7611 * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
7612 * caching kthreads as we move along
7613 * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
7614 * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
7615 * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
7618 if (ffe_ctl->loop < LOOP_NO_EMPTY_SIZE) {
7620 if (ffe_ctl->loop == LOOP_CACHING_NOWAIT) {
7622 * We want to skip the LOOP_CACHING_WAIT step if we
7623 * don't have any uncached bgs and we've already done a
7624 * full search through.
7626 if (ffe_ctl->orig_have_caching_bg || !full_search)
7627 ffe_ctl->loop = LOOP_CACHING_WAIT;
7629 ffe_ctl->loop = LOOP_ALLOC_CHUNK;
7634 if (ffe_ctl->loop == LOOP_ALLOC_CHUNK) {
7635 struct btrfs_trans_handle *trans;
7638 trans = current->journal_info;
7642 trans = btrfs_join_transaction(root);
7644 if (IS_ERR(trans)) {
7645 ret = PTR_ERR(trans);
7649 ret = btrfs_chunk_alloc(trans, ffe_ctl->flags,
7653 * If we can't allocate a new chunk we've already looped
7654 * through at least once, move on to the NO_EMPTY_SIZE
7658 ffe_ctl->loop = LOOP_NO_EMPTY_SIZE;
7660 /* Do not bail out on ENOSPC since we can do more. */
7661 if (ret < 0 && ret != -ENOSPC)
7662 btrfs_abort_transaction(trans, ret);
7666 btrfs_end_transaction(trans);
7671 if (ffe_ctl->loop == LOOP_NO_EMPTY_SIZE) {
7673 * Don't loop again if we already have no empty_size and
7676 if (ffe_ctl->empty_size == 0 &&
7677 ffe_ctl->empty_cluster == 0)
7679 ffe_ctl->empty_size = 0;
7680 ffe_ctl->empty_cluster = 0;
7688 * walks the btree of allocated extents and find a hole of a given size.
7689 * The key ins is changed to record the hole:
7690 * ins->objectid == start position
7691 * ins->flags = BTRFS_EXTENT_ITEM_KEY
7692 * ins->offset == the size of the hole.
7693 * Any available blocks before search_start are skipped.
7695 * If there is no suitable free space, we will record the max size of
7696 * the free space extent currently.
7698 * The overall logic and call chain:
7700 * find_free_extent()
7701 * |- Iterate through all block groups
7702 * | |- Get a valid block group
7703 * | |- Try to do clustered allocation in that block group
7704 * | |- Try to do unclustered allocation in that block group
7705 * | |- Check if the result is valid
7706 * | | |- If valid, then exit
7707 * | |- Jump to next block group
7709 * |- Push harder to find free extents
7710 * |- If not found, re-iterate all block groups
7712 static noinline int find_free_extent(struct btrfs_fs_info *fs_info,
7713 u64 ram_bytes, u64 num_bytes, u64 empty_size,
7714 u64 hint_byte, struct btrfs_key *ins,
7715 u64 flags, int delalloc)
7718 struct btrfs_free_cluster *last_ptr = NULL;
7719 struct btrfs_block_group_cache *block_group = NULL;
7720 struct find_free_extent_ctl ffe_ctl = {0};
7721 struct btrfs_space_info *space_info;
7722 bool use_cluster = true;
7723 bool full_search = false;
7725 WARN_ON(num_bytes < fs_info->sectorsize);
7727 ffe_ctl.ram_bytes = ram_bytes;
7728 ffe_ctl.num_bytes = num_bytes;
7729 ffe_ctl.empty_size = empty_size;
7730 ffe_ctl.flags = flags;
7731 ffe_ctl.search_start = 0;
7732 ffe_ctl.retry_clustered = false;
7733 ffe_ctl.retry_unclustered = false;
7734 ffe_ctl.delalloc = delalloc;
7735 ffe_ctl.index = btrfs_bg_flags_to_raid_index(flags);
7736 ffe_ctl.have_caching_bg = false;
7737 ffe_ctl.orig_have_caching_bg = false;
7738 ffe_ctl.found_offset = 0;
7740 ins->type = BTRFS_EXTENT_ITEM_KEY;
7744 trace_find_free_extent(fs_info, num_bytes, empty_size, flags);
7746 space_info = __find_space_info(fs_info, flags);
7748 btrfs_err(fs_info, "No space info for %llu", flags);
7753 * If our free space is heavily fragmented we may not be able to make
7754 * big contiguous allocations, so instead of doing the expensive search
7755 * for free space, simply return ENOSPC with our max_extent_size so we
7756 * can go ahead and search for a more manageable chunk.
7758 * If our max_extent_size is large enough for our allocation simply
7759 * disable clustering since we will likely not be able to find enough
7760 * space to create a cluster and induce latency trying.
7762 if (unlikely(space_info->max_extent_size)) {
7763 spin_lock(&space_info->lock);
7764 if (space_info->max_extent_size &&
7765 num_bytes > space_info->max_extent_size) {
7766 ins->offset = space_info->max_extent_size;
7767 spin_unlock(&space_info->lock);
7769 } else if (space_info->max_extent_size) {
7770 use_cluster = false;
7772 spin_unlock(&space_info->lock);
7775 last_ptr = fetch_cluster_info(fs_info, space_info,
7776 &ffe_ctl.empty_cluster);
7778 spin_lock(&last_ptr->lock);
7779 if (last_ptr->block_group)
7780 hint_byte = last_ptr->window_start;
7781 if (last_ptr->fragmented) {
7783 * We still set window_start so we can keep track of the
7784 * last place we found an allocation to try and save
7787 hint_byte = last_ptr->window_start;
7788 use_cluster = false;
7790 spin_unlock(&last_ptr->lock);
7793 ffe_ctl.search_start = max(ffe_ctl.search_start,
7794 first_logical_byte(fs_info, 0));
7795 ffe_ctl.search_start = max(ffe_ctl.search_start, hint_byte);
7796 if (ffe_ctl.search_start == hint_byte) {
7797 block_group = btrfs_lookup_block_group(fs_info,
7798 ffe_ctl.search_start);
7800 * we don't want to use the block group if it doesn't match our
7801 * allocation bits, or if its not cached.
7803 * However if we are re-searching with an ideal block group
7804 * picked out then we don't care that the block group is cached.
7806 if (block_group && block_group_bits(block_group, flags) &&
7807 block_group->cached != BTRFS_CACHE_NO) {
7808 down_read(&space_info->groups_sem);
7809 if (list_empty(&block_group->list) ||
7812 * someone is removing this block group,
7813 * we can't jump into the have_block_group
7814 * target because our list pointers are not
7817 btrfs_put_block_group(block_group);
7818 up_read(&space_info->groups_sem);
7820 ffe_ctl.index = btrfs_bg_flags_to_raid_index(
7821 block_group->flags);
7822 btrfs_lock_block_group(block_group, delalloc);
7823 goto have_block_group;
7825 } else if (block_group) {
7826 btrfs_put_block_group(block_group);
7830 ffe_ctl.have_caching_bg = false;
7831 if (ffe_ctl.index == btrfs_bg_flags_to_raid_index(flags) ||
7834 down_read(&space_info->groups_sem);
7835 list_for_each_entry(block_group,
7836 &space_info->block_groups[ffe_ctl.index], list) {
7837 /* If the block group is read-only, we can skip it entirely. */
7838 if (unlikely(block_group->ro))
7841 btrfs_grab_block_group(block_group, delalloc);
7842 ffe_ctl.search_start = block_group->key.objectid;
7845 * this can happen if we end up cycling through all the
7846 * raid types, but we want to make sure we only allocate
7847 * for the proper type.
7849 if (!block_group_bits(block_group, flags)) {
7850 u64 extra = BTRFS_BLOCK_GROUP_DUP |
7851 BTRFS_BLOCK_GROUP_RAID1_MASK |
7852 BTRFS_BLOCK_GROUP_RAID56_MASK |
7853 BTRFS_BLOCK_GROUP_RAID10;
7856 * if they asked for extra copies and this block group
7857 * doesn't provide them, bail. This does allow us to
7858 * fill raid0 from raid1.
7860 if ((flags & extra) && !(block_group->flags & extra))
7865 ffe_ctl.cached = block_group_cache_done(block_group);
7866 if (unlikely(!ffe_ctl.cached)) {
7867 ffe_ctl.have_caching_bg = true;
7868 ret = cache_block_group(block_group, 0);
7873 if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
7877 * Ok we want to try and use the cluster allocator, so
7880 if (last_ptr && use_cluster) {
7881 struct btrfs_block_group_cache *cluster_bg = NULL;
7883 ret = find_free_extent_clustered(block_group, last_ptr,
7884 &ffe_ctl, &cluster_bg);
7887 if (cluster_bg && cluster_bg != block_group) {
7888 btrfs_release_block_group(block_group,
7890 block_group = cluster_bg;
7893 } else if (ret == -EAGAIN) {
7894 goto have_block_group;
7895 } else if (ret > 0) {
7898 /* ret == -ENOENT case falls through */
7901 ret = find_free_extent_unclustered(block_group, last_ptr,
7904 goto have_block_group;
7907 /* ret == 0 case falls through */
7909 ffe_ctl.search_start = round_up(ffe_ctl.found_offset,
7910 fs_info->stripesize);
7912 /* move on to the next group */
7913 if (ffe_ctl.search_start + num_bytes >
7914 block_group->key.objectid + block_group->key.offset) {
7915 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
7920 if (ffe_ctl.found_offset < ffe_ctl.search_start)
7921 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
7922 ffe_ctl.search_start - ffe_ctl.found_offset);
7924 ret = btrfs_add_reserved_bytes(block_group, ram_bytes,
7925 num_bytes, delalloc);
7926 if (ret == -EAGAIN) {
7927 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
7931 btrfs_inc_block_group_reservations(block_group);
7933 /* we are all good, lets return */
7934 ins->objectid = ffe_ctl.search_start;
7935 ins->offset = num_bytes;
7937 trace_btrfs_reserve_extent(block_group, ffe_ctl.search_start,
7939 btrfs_release_block_group(block_group, delalloc);
7942 ffe_ctl.retry_clustered = false;
7943 ffe_ctl.retry_unclustered = false;
7944 BUG_ON(btrfs_bg_flags_to_raid_index(block_group->flags) !=
7946 btrfs_release_block_group(block_group, delalloc);
7949 up_read(&space_info->groups_sem);
7951 ret = find_free_extent_update_loop(fs_info, last_ptr, ins, &ffe_ctl,
7952 full_search, use_cluster);
7956 if (ret == -ENOSPC) {
7958 * Use ffe_ctl->total_free_space as fallback if we can't find
7959 * any contiguous hole.
7961 if (!ffe_ctl.max_extent_size)
7962 ffe_ctl.max_extent_size = ffe_ctl.total_free_space;
7963 spin_lock(&space_info->lock);
7964 space_info->max_extent_size = ffe_ctl.max_extent_size;
7965 spin_unlock(&space_info->lock);
7966 ins->offset = ffe_ctl.max_extent_size;
7971 #define DUMP_BLOCK_RSV(fs_info, rsv_name) \
7973 struct btrfs_block_rsv *__rsv = &(fs_info)->rsv_name; \
7974 spin_lock(&__rsv->lock); \
7975 btrfs_info(fs_info, #rsv_name ": size %llu reserved %llu", \
7976 __rsv->size, __rsv->reserved); \
7977 spin_unlock(&__rsv->lock); \
7980 static void dump_space_info(struct btrfs_fs_info *fs_info,
7981 struct btrfs_space_info *info, u64 bytes,
7982 int dump_block_groups)
7984 struct btrfs_block_group_cache *cache;
7987 spin_lock(&info->lock);
7988 btrfs_info(fs_info, "space_info %llu has %llu free, is %sfull",
7990 info->total_bytes - btrfs_space_info_used(info, true),
7991 info->full ? "" : "not ");
7993 "space_info total=%llu, used=%llu, pinned=%llu, reserved=%llu, may_use=%llu, readonly=%llu",
7994 info->total_bytes, info->bytes_used, info->bytes_pinned,
7995 info->bytes_reserved, info->bytes_may_use,
7996 info->bytes_readonly);
7997 spin_unlock(&info->lock);
7999 DUMP_BLOCK_RSV(fs_info, global_block_rsv);
8000 DUMP_BLOCK_RSV(fs_info, trans_block_rsv);
8001 DUMP_BLOCK_RSV(fs_info, chunk_block_rsv);
8002 DUMP_BLOCK_RSV(fs_info, delayed_block_rsv);
8003 DUMP_BLOCK_RSV(fs_info, delayed_refs_rsv);
8005 if (!dump_block_groups)
8008 down_read(&info->groups_sem);
8010 list_for_each_entry(cache, &info->block_groups[index], list) {
8011 spin_lock(&cache->lock);
8013 "block group %llu has %llu bytes, %llu used %llu pinned %llu reserved %s",
8014 cache->key.objectid, cache->key.offset,
8015 btrfs_block_group_used(&cache->item), cache->pinned,
8016 cache->reserved, cache->ro ? "[readonly]" : "");
8017 btrfs_dump_free_space(cache, bytes);
8018 spin_unlock(&cache->lock);
8020 if (++index < BTRFS_NR_RAID_TYPES)
8022 up_read(&info->groups_sem);
8026 * btrfs_reserve_extent - entry point to the extent allocator. Tries to find a
8027 * hole that is at least as big as @num_bytes.
8029 * @root - The root that will contain this extent
8031 * @ram_bytes - The amount of space in ram that @num_bytes take. This
8032 * is used for accounting purposes. This value differs
8033 * from @num_bytes only in the case of compressed extents.
8035 * @num_bytes - Number of bytes to allocate on-disk.
8037 * @min_alloc_size - Indicates the minimum amount of space that the
8038 * allocator should try to satisfy. In some cases
8039 * @num_bytes may be larger than what is required and if
8040 * the filesystem is fragmented then allocation fails.
8041 * However, the presence of @min_alloc_size gives a
8042 * chance to try and satisfy the smaller allocation.
8044 * @empty_size - A hint that you plan on doing more COW. This is the
8045 * size in bytes the allocator should try to find free
8046 * next to the block it returns. This is just a hint and
8047 * may be ignored by the allocator.
8049 * @hint_byte - Hint to the allocator to start searching above the byte
8050 * address passed. It might be ignored.
8052 * @ins - This key is modified to record the found hole. It will
8053 * have the following values:
8054 * ins->objectid == start position
8055 * ins->flags = BTRFS_EXTENT_ITEM_KEY
8056 * ins->offset == the size of the hole.
8058 * @is_data - Boolean flag indicating whether an extent is
8059 * allocated for data (true) or metadata (false)
8061 * @delalloc - Boolean flag indicating whether this allocation is for
8062 * delalloc or not. If 'true' data_rwsem of block groups
8063 * is going to be acquired.
8066 * Returns 0 when an allocation succeeded or < 0 when an error occurred. In
8067 * case -ENOSPC is returned then @ins->offset will contain the size of the
8068 * largest available hole the allocator managed to find.
8070 int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
8071 u64 num_bytes, u64 min_alloc_size,
8072 u64 empty_size, u64 hint_byte,
8073 struct btrfs_key *ins, int is_data, int delalloc)
8075 struct btrfs_fs_info *fs_info = root->fs_info;
8076 bool final_tried = num_bytes == min_alloc_size;
8080 flags = get_alloc_profile_by_root(root, is_data);
8082 WARN_ON(num_bytes < fs_info->sectorsize);
8083 ret = find_free_extent(fs_info, ram_bytes, num_bytes, empty_size,
8084 hint_byte, ins, flags, delalloc);
8085 if (!ret && !is_data) {
8086 btrfs_dec_block_group_reservations(fs_info, ins->objectid);
8087 } else if (ret == -ENOSPC) {
8088 if (!final_tried && ins->offset) {
8089 num_bytes = min(num_bytes >> 1, ins->offset);
8090 num_bytes = round_down(num_bytes,
8091 fs_info->sectorsize);
8092 num_bytes = max(num_bytes, min_alloc_size);
8093 ram_bytes = num_bytes;
8094 if (num_bytes == min_alloc_size)
8097 } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
8098 struct btrfs_space_info *sinfo;
8100 sinfo = __find_space_info(fs_info, flags);
8102 "allocation failed flags %llu, wanted %llu",
8105 dump_space_info(fs_info, sinfo, num_bytes, 1);
8112 static int __btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
8114 int pin, int delalloc)
8116 struct btrfs_block_group_cache *cache;
8119 cache = btrfs_lookup_block_group(fs_info, start);
8121 btrfs_err(fs_info, "Unable to find block group for %llu",
8127 pin_down_extent(cache, start, len, 1);
8129 if (btrfs_test_opt(fs_info, DISCARD))
8130 ret = btrfs_discard_extent(fs_info, start, len, NULL);
8131 btrfs_add_free_space(cache, start, len);
8132 btrfs_free_reserved_bytes(cache, len, delalloc);
8133 trace_btrfs_reserved_extent_free(fs_info, start, len);
8136 btrfs_put_block_group(cache);
8140 int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
8141 u64 start, u64 len, int delalloc)
8143 return __btrfs_free_reserved_extent(fs_info, start, len, 0, delalloc);
8146 int btrfs_free_and_pin_reserved_extent(struct btrfs_fs_info *fs_info,
8149 return __btrfs_free_reserved_extent(fs_info, start, len, 1, 0);
8152 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
8153 u64 parent, u64 root_objectid,
8154 u64 flags, u64 owner, u64 offset,
8155 struct btrfs_key *ins, int ref_mod)
8157 struct btrfs_fs_info *fs_info = trans->fs_info;
8159 struct btrfs_extent_item *extent_item;
8160 struct btrfs_extent_inline_ref *iref;
8161 struct btrfs_path *path;
8162 struct extent_buffer *leaf;
8167 type = BTRFS_SHARED_DATA_REF_KEY;
8169 type = BTRFS_EXTENT_DATA_REF_KEY;
8171 size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
8173 path = btrfs_alloc_path();
8177 path->leave_spinning = 1;
8178 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
8181 btrfs_free_path(path);
8185 leaf = path->nodes[0];
8186 extent_item = btrfs_item_ptr(leaf, path->slots[0],
8187 struct btrfs_extent_item);
8188 btrfs_set_extent_refs(leaf, extent_item, ref_mod);
8189 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
8190 btrfs_set_extent_flags(leaf, extent_item,
8191 flags | BTRFS_EXTENT_FLAG_DATA);
8193 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
8194 btrfs_set_extent_inline_ref_type(leaf, iref, type);
8196 struct btrfs_shared_data_ref *ref;
8197 ref = (struct btrfs_shared_data_ref *)(iref + 1);
8198 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
8199 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
8201 struct btrfs_extent_data_ref *ref;
8202 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
8203 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
8204 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
8205 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
8206 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
8209 btrfs_mark_buffer_dirty(path->nodes[0]);
8210 btrfs_free_path(path);
8212 ret = remove_from_free_space_tree(trans, ins->objectid, ins->offset);
8216 ret = update_block_group(trans, ins->objectid, ins->offset, 1);
8217 if (ret) { /* -ENOENT, logic error */
8218 btrfs_err(fs_info, "update block group failed for %llu %llu",
8219 ins->objectid, ins->offset);
8222 trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid, ins->offset);
8226 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
8227 struct btrfs_delayed_ref_node *node,
8228 struct btrfs_delayed_extent_op *extent_op)
8230 struct btrfs_fs_info *fs_info = trans->fs_info;
8232 struct btrfs_extent_item *extent_item;
8233 struct btrfs_key extent_key;
8234 struct btrfs_tree_block_info *block_info;
8235 struct btrfs_extent_inline_ref *iref;
8236 struct btrfs_path *path;
8237 struct extent_buffer *leaf;
8238 struct btrfs_delayed_tree_ref *ref;
8239 u32 size = sizeof(*extent_item) + sizeof(*iref);
8241 u64 flags = extent_op->flags_to_set;
8242 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
8244 ref = btrfs_delayed_node_to_tree_ref(node);
8246 extent_key.objectid = node->bytenr;
8247 if (skinny_metadata) {
8248 extent_key.offset = ref->level;
8249 extent_key.type = BTRFS_METADATA_ITEM_KEY;
8250 num_bytes = fs_info->nodesize;
8252 extent_key.offset = node->num_bytes;
8253 extent_key.type = BTRFS_EXTENT_ITEM_KEY;
8254 size += sizeof(*block_info);
8255 num_bytes = node->num_bytes;
8258 path = btrfs_alloc_path();
8262 path->leave_spinning = 1;
8263 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
8266 btrfs_free_path(path);
8270 leaf = path->nodes[0];
8271 extent_item = btrfs_item_ptr(leaf, path->slots[0],
8272 struct btrfs_extent_item);
8273 btrfs_set_extent_refs(leaf, extent_item, 1);
8274 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
8275 btrfs_set_extent_flags(leaf, extent_item,
8276 flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
8278 if (skinny_metadata) {
8279 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
8281 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
8282 btrfs_set_tree_block_key(leaf, block_info, &extent_op->key);
8283 btrfs_set_tree_block_level(leaf, block_info, ref->level);
8284 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
8287 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY) {
8288 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
8289 btrfs_set_extent_inline_ref_type(leaf, iref,
8290 BTRFS_SHARED_BLOCK_REF_KEY);
8291 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->parent);
8293 btrfs_set_extent_inline_ref_type(leaf, iref,
8294 BTRFS_TREE_BLOCK_REF_KEY);
8295 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->root);
8298 btrfs_mark_buffer_dirty(leaf);
8299 btrfs_free_path(path);
8301 ret = remove_from_free_space_tree(trans, extent_key.objectid,
8306 ret = update_block_group(trans, extent_key.objectid,
8307 fs_info->nodesize, 1);
8308 if (ret) { /* -ENOENT, logic error */
8309 btrfs_err(fs_info, "update block group failed for %llu %llu",
8310 extent_key.objectid, extent_key.offset);
8314 trace_btrfs_reserved_extent_alloc(fs_info, extent_key.objectid,
8319 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
8320 struct btrfs_root *root, u64 owner,
8321 u64 offset, u64 ram_bytes,
8322 struct btrfs_key *ins)
8324 struct btrfs_ref generic_ref = { 0 };
8327 BUG_ON(root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
8329 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
8330 ins->objectid, ins->offset, 0);
8331 btrfs_init_data_ref(&generic_ref, root->root_key.objectid, owner, offset);
8332 btrfs_ref_tree_mod(root->fs_info, &generic_ref);
8333 ret = btrfs_add_delayed_data_ref(trans, &generic_ref,
8334 ram_bytes, NULL, NULL);
8339 * this is used by the tree logging recovery code. It records that
8340 * an extent has been allocated and makes sure to clear the free
8341 * space cache bits as well
8343 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
8344 u64 root_objectid, u64 owner, u64 offset,
8345 struct btrfs_key *ins)
8347 struct btrfs_fs_info *fs_info = trans->fs_info;
8349 struct btrfs_block_group_cache *block_group;
8350 struct btrfs_space_info *space_info;
8353 * Mixed block groups will exclude before processing the log so we only
8354 * need to do the exclude dance if this fs isn't mixed.
8356 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
8357 ret = __exclude_logged_extent(fs_info, ins->objectid,
8363 block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
8367 space_info = block_group->space_info;
8368 spin_lock(&space_info->lock);
8369 spin_lock(&block_group->lock);
8370 space_info->bytes_reserved += ins->offset;
8371 block_group->reserved += ins->offset;
8372 spin_unlock(&block_group->lock);
8373 spin_unlock(&space_info->lock);
8375 ret = alloc_reserved_file_extent(trans, 0, root_objectid, 0, owner,
8377 btrfs_put_block_group(block_group);
8381 static struct extent_buffer *
8382 btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
8383 u64 bytenr, int level, u64 owner)
8385 struct btrfs_fs_info *fs_info = root->fs_info;
8386 struct extent_buffer *buf;
8388 buf = btrfs_find_create_tree_block(fs_info, bytenr);
8393 * Extra safety check in case the extent tree is corrupted and extent
8394 * allocator chooses to use a tree block which is already used and
8397 if (buf->lock_owner == current->pid) {
8398 btrfs_err_rl(fs_info,
8399 "tree block %llu owner %llu already locked by pid=%d, extent tree corruption detected",
8400 buf->start, btrfs_header_owner(buf), current->pid);
8401 free_extent_buffer(buf);
8402 return ERR_PTR(-EUCLEAN);
8405 btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
8406 btrfs_tree_lock(buf);
8407 btrfs_clean_tree_block(buf);
8408 clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
8410 btrfs_set_lock_blocking_write(buf);
8411 set_extent_buffer_uptodate(buf);
8413 memzero_extent_buffer(buf, 0, sizeof(struct btrfs_header));
8414 btrfs_set_header_level(buf, level);
8415 btrfs_set_header_bytenr(buf, buf->start);
8416 btrfs_set_header_generation(buf, trans->transid);
8417 btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
8418 btrfs_set_header_owner(buf, owner);
8419 write_extent_buffer_fsid(buf, fs_info->fs_devices->metadata_uuid);
8420 write_extent_buffer_chunk_tree_uuid(buf, fs_info->chunk_tree_uuid);
8421 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
8422 buf->log_index = root->log_transid % 2;
8424 * we allow two log transactions at a time, use different
8425 * EXTENT bit to differentiate dirty pages.
8427 if (buf->log_index == 0)
8428 set_extent_dirty(&root->dirty_log_pages, buf->start,
8429 buf->start + buf->len - 1, GFP_NOFS);
8431 set_extent_new(&root->dirty_log_pages, buf->start,
8432 buf->start + buf->len - 1);
8434 buf->log_index = -1;
8435 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
8436 buf->start + buf->len - 1, GFP_NOFS);
8438 trans->dirty = true;
8439 /* this returns a buffer locked for blocking */
8443 static struct btrfs_block_rsv *
8444 use_block_rsv(struct btrfs_trans_handle *trans,
8445 struct btrfs_root *root, u32 blocksize)
8447 struct btrfs_fs_info *fs_info = root->fs_info;
8448 struct btrfs_block_rsv *block_rsv;
8449 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
8451 bool global_updated = false;
8453 block_rsv = get_block_rsv(trans, root);
8455 if (unlikely(block_rsv->size == 0))
8458 ret = block_rsv_use_bytes(block_rsv, blocksize);
8462 if (block_rsv->failfast)
8463 return ERR_PTR(ret);
8465 if (block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL && !global_updated) {
8466 global_updated = true;
8467 update_global_block_rsv(fs_info);
8472 * The global reserve still exists to save us from ourselves, so don't
8473 * warn_on if we are short on our delayed refs reserve.
8475 if (block_rsv->type != BTRFS_BLOCK_RSV_DELREFS &&
8476 btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
8477 static DEFINE_RATELIMIT_STATE(_rs,
8478 DEFAULT_RATELIMIT_INTERVAL * 10,
8479 /*DEFAULT_RATELIMIT_BURST*/ 1);
8480 if (__ratelimit(&_rs))
8482 "BTRFS: block rsv returned %d\n", ret);
8485 ret = reserve_metadata_bytes(root, block_rsv, blocksize,
8486 BTRFS_RESERVE_NO_FLUSH);
8490 * If we couldn't reserve metadata bytes try and use some from
8491 * the global reserve if its space type is the same as the global
8494 if (block_rsv->type != BTRFS_BLOCK_RSV_GLOBAL &&
8495 block_rsv->space_info == global_rsv->space_info) {
8496 ret = block_rsv_use_bytes(global_rsv, blocksize);
8500 return ERR_PTR(ret);
8503 static void unuse_block_rsv(struct btrfs_fs_info *fs_info,
8504 struct btrfs_block_rsv *block_rsv, u32 blocksize)
8506 block_rsv_add_bytes(block_rsv, blocksize, false);
8507 block_rsv_release_bytes(fs_info, block_rsv, NULL, 0, NULL);
8511 * finds a free extent and does all the dirty work required for allocation
8512 * returns the tree buffer or an ERR_PTR on error.
8514 struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
8515 struct btrfs_root *root,
8516 u64 parent, u64 root_objectid,
8517 const struct btrfs_disk_key *key,
8518 int level, u64 hint,
8521 struct btrfs_fs_info *fs_info = root->fs_info;
8522 struct btrfs_key ins;
8523 struct btrfs_block_rsv *block_rsv;
8524 struct extent_buffer *buf;
8525 struct btrfs_delayed_extent_op *extent_op;
8526 struct btrfs_ref generic_ref = { 0 };
8529 u32 blocksize = fs_info->nodesize;
8530 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
8532 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8533 if (btrfs_is_testing(fs_info)) {
8534 buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
8535 level, root_objectid);
8537 root->alloc_bytenr += blocksize;
8542 block_rsv = use_block_rsv(trans, root, blocksize);
8543 if (IS_ERR(block_rsv))
8544 return ERR_CAST(block_rsv);
8546 ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
8547 empty_size, hint, &ins, 0, 0);
8551 buf = btrfs_init_new_buffer(trans, root, ins.objectid, level,
8555 goto out_free_reserved;
8558 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
8560 parent = ins.objectid;
8561 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
8565 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
8566 extent_op = btrfs_alloc_delayed_extent_op();
8572 memcpy(&extent_op->key, key, sizeof(extent_op->key));
8574 memset(&extent_op->key, 0, sizeof(extent_op->key));
8575 extent_op->flags_to_set = flags;
8576 extent_op->update_key = skinny_metadata ? false : true;
8577 extent_op->update_flags = true;
8578 extent_op->is_data = false;
8579 extent_op->level = level;
8581 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
8582 ins.objectid, ins.offset, parent);
8583 generic_ref.real_root = root->root_key.objectid;
8584 btrfs_init_tree_ref(&generic_ref, level, root_objectid);
8585 btrfs_ref_tree_mod(fs_info, &generic_ref);
8586 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref,
8587 extent_op, NULL, NULL);
8589 goto out_free_delayed;
8594 btrfs_free_delayed_extent_op(extent_op);
8596 free_extent_buffer(buf);
8598 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 0);
8600 unuse_block_rsv(fs_info, block_rsv, blocksize);
8601 return ERR_PTR(ret);
8604 struct walk_control {
8605 u64 refs[BTRFS_MAX_LEVEL];
8606 u64 flags[BTRFS_MAX_LEVEL];
8607 struct btrfs_key update_progress;
8608 struct btrfs_key drop_progress;
8620 #define DROP_REFERENCE 1
8621 #define UPDATE_BACKREF 2
8623 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
8624 struct btrfs_root *root,
8625 struct walk_control *wc,
8626 struct btrfs_path *path)
8628 struct btrfs_fs_info *fs_info = root->fs_info;
8634 struct btrfs_key key;
8635 struct extent_buffer *eb;
8640 if (path->slots[wc->level] < wc->reada_slot) {
8641 wc->reada_count = wc->reada_count * 2 / 3;
8642 wc->reada_count = max(wc->reada_count, 2);
8644 wc->reada_count = wc->reada_count * 3 / 2;
8645 wc->reada_count = min_t(int, wc->reada_count,
8646 BTRFS_NODEPTRS_PER_BLOCK(fs_info));
8649 eb = path->nodes[wc->level];
8650 nritems = btrfs_header_nritems(eb);
8652 for (slot = path->slots[wc->level]; slot < nritems; slot++) {
8653 if (nread >= wc->reada_count)
8657 bytenr = btrfs_node_blockptr(eb, slot);
8658 generation = btrfs_node_ptr_generation(eb, slot);
8660 if (slot == path->slots[wc->level])
8663 if (wc->stage == UPDATE_BACKREF &&
8664 generation <= root->root_key.offset)
8667 /* We don't lock the tree block, it's OK to be racy here */
8668 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr,
8669 wc->level - 1, 1, &refs,
8671 /* We don't care about errors in readahead. */
8676 if (wc->stage == DROP_REFERENCE) {
8680 if (wc->level == 1 &&
8681 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8683 if (!wc->update_ref ||
8684 generation <= root->root_key.offset)
8686 btrfs_node_key_to_cpu(eb, &key, slot);
8687 ret = btrfs_comp_cpu_keys(&key,
8688 &wc->update_progress);
8692 if (wc->level == 1 &&
8693 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8697 readahead_tree_block(fs_info, bytenr);
8700 wc->reada_slot = slot;
8704 * helper to process tree block while walking down the tree.
8706 * when wc->stage == UPDATE_BACKREF, this function updates
8707 * back refs for pointers in the block.
8709 * NOTE: return value 1 means we should stop walking down.
8711 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
8712 struct btrfs_root *root,
8713 struct btrfs_path *path,
8714 struct walk_control *wc, int lookup_info)
8716 struct btrfs_fs_info *fs_info = root->fs_info;
8717 int level = wc->level;
8718 struct extent_buffer *eb = path->nodes[level];
8719 u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
8722 if (wc->stage == UPDATE_BACKREF &&
8723 btrfs_header_owner(eb) != root->root_key.objectid)
8727 * when reference count of tree block is 1, it won't increase
8728 * again. once full backref flag is set, we never clear it.
8731 ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
8732 (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
8733 BUG_ON(!path->locks[level]);
8734 ret = btrfs_lookup_extent_info(trans, fs_info,
8735 eb->start, level, 1,
8738 BUG_ON(ret == -ENOMEM);
8741 BUG_ON(wc->refs[level] == 0);
8744 if (wc->stage == DROP_REFERENCE) {
8745 if (wc->refs[level] > 1)
8748 if (path->locks[level] && !wc->keep_locks) {
8749 btrfs_tree_unlock_rw(eb, path->locks[level]);
8750 path->locks[level] = 0;
8755 /* wc->stage == UPDATE_BACKREF */
8756 if (!(wc->flags[level] & flag)) {
8757 BUG_ON(!path->locks[level]);
8758 ret = btrfs_inc_ref(trans, root, eb, 1);
8759 BUG_ON(ret); /* -ENOMEM */
8760 ret = btrfs_dec_ref(trans, root, eb, 0);
8761 BUG_ON(ret); /* -ENOMEM */
8762 ret = btrfs_set_disk_extent_flags(trans, eb->start,
8764 btrfs_header_level(eb), 0);
8765 BUG_ON(ret); /* -ENOMEM */
8766 wc->flags[level] |= flag;
8770 * the block is shared by multiple trees, so it's not good to
8771 * keep the tree lock
8773 if (path->locks[level] && level > 0) {
8774 btrfs_tree_unlock_rw(eb, path->locks[level]);
8775 path->locks[level] = 0;
8781 * This is used to verify a ref exists for this root to deal with a bug where we
8782 * would have a drop_progress key that hadn't been updated properly.
8784 static int check_ref_exists(struct btrfs_trans_handle *trans,
8785 struct btrfs_root *root, u64 bytenr, u64 parent,
8788 struct btrfs_path *path;
8789 struct btrfs_extent_inline_ref *iref;
8792 path = btrfs_alloc_path();
8796 ret = lookup_extent_backref(trans, path, &iref, bytenr,
8797 root->fs_info->nodesize, parent,
8798 root->root_key.objectid, level, 0);
8799 btrfs_free_path(path);
8808 * helper to process tree block pointer.
8810 * when wc->stage == DROP_REFERENCE, this function checks
8811 * reference count of the block pointed to. if the block
8812 * is shared and we need update back refs for the subtree
8813 * rooted at the block, this function changes wc->stage to
8814 * UPDATE_BACKREF. if the block is shared and there is no
8815 * need to update back, this function drops the reference
8818 * NOTE: return value 1 means we should stop walking down.
8820 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
8821 struct btrfs_root *root,
8822 struct btrfs_path *path,
8823 struct walk_control *wc, int *lookup_info)
8825 struct btrfs_fs_info *fs_info = root->fs_info;
8829 struct btrfs_key key;
8830 struct btrfs_key first_key;
8831 struct btrfs_ref ref = { 0 };
8832 struct extent_buffer *next;
8833 int level = wc->level;
8836 bool need_account = false;
8838 generation = btrfs_node_ptr_generation(path->nodes[level],
8839 path->slots[level]);
8841 * if the lower level block was created before the snapshot
8842 * was created, we know there is no need to update back refs
8845 if (wc->stage == UPDATE_BACKREF &&
8846 generation <= root->root_key.offset) {
8851 bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
8852 btrfs_node_key_to_cpu(path->nodes[level], &first_key,
8853 path->slots[level]);
8855 next = find_extent_buffer(fs_info, bytenr);
8857 next = btrfs_find_create_tree_block(fs_info, bytenr);
8859 return PTR_ERR(next);
8861 btrfs_set_buffer_lockdep_class(root->root_key.objectid, next,
8865 btrfs_tree_lock(next);
8866 btrfs_set_lock_blocking_write(next);
8868 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1,
8869 &wc->refs[level - 1],
8870 &wc->flags[level - 1]);
8874 if (unlikely(wc->refs[level - 1] == 0)) {
8875 btrfs_err(fs_info, "Missing references.");
8881 if (wc->stage == DROP_REFERENCE) {
8882 if (wc->refs[level - 1] > 1) {
8883 need_account = true;
8885 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8888 if (!wc->update_ref ||
8889 generation <= root->root_key.offset)
8892 btrfs_node_key_to_cpu(path->nodes[level], &key,
8893 path->slots[level]);
8894 ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
8898 wc->stage = UPDATE_BACKREF;
8899 wc->shared_level = level - 1;
8903 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8907 if (!btrfs_buffer_uptodate(next, generation, 0)) {
8908 btrfs_tree_unlock(next);
8909 free_extent_buffer(next);
8915 if (reada && level == 1)
8916 reada_walk_down(trans, root, wc, path);
8917 next = read_tree_block(fs_info, bytenr, generation, level - 1,
8920 return PTR_ERR(next);
8921 } else if (!extent_buffer_uptodate(next)) {
8922 free_extent_buffer(next);
8925 btrfs_tree_lock(next);
8926 btrfs_set_lock_blocking_write(next);
8930 ASSERT(level == btrfs_header_level(next));
8931 if (level != btrfs_header_level(next)) {
8932 btrfs_err(root->fs_info, "mismatched level");
8936 path->nodes[level] = next;
8937 path->slots[level] = 0;
8938 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8944 wc->refs[level - 1] = 0;
8945 wc->flags[level - 1] = 0;
8946 if (wc->stage == DROP_REFERENCE) {
8947 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
8948 parent = path->nodes[level]->start;
8950 ASSERT(root->root_key.objectid ==
8951 btrfs_header_owner(path->nodes[level]));
8952 if (root->root_key.objectid !=
8953 btrfs_header_owner(path->nodes[level])) {
8954 btrfs_err(root->fs_info,
8955 "mismatched block owner");
8963 * If we had a drop_progress we need to verify the refs are set
8964 * as expected. If we find our ref then we know that from here
8965 * on out everything should be correct, and we can clear the
8968 if (wc->restarted) {
8969 ret = check_ref_exists(trans, root, bytenr, parent,
8980 * Reloc tree doesn't contribute to qgroup numbers, and we have
8981 * already accounted them at merge time (replace_path),
8982 * thus we could skip expensive subtree trace here.
8984 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
8986 ret = btrfs_qgroup_trace_subtree(trans, next,
8987 generation, level - 1);
8989 btrfs_err_rl(fs_info,
8990 "Error %d accounting shared subtree. Quota is out of sync, rescan required.",
8996 * We need to update the next key in our walk control so we can
8997 * update the drop_progress key accordingly. We don't care if
8998 * find_next_key doesn't find a key because that means we're at
8999 * the end and are going to clean up now.
9001 wc->drop_level = level;
9002 find_next_key(path, level, &wc->drop_progress);
9004 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, bytenr,
9005 fs_info->nodesize, parent);
9006 btrfs_init_tree_ref(&ref, level - 1, root->root_key.objectid);
9007 ret = btrfs_free_extent(trans, &ref);
9016 btrfs_tree_unlock(next);
9017 free_extent_buffer(next);
9023 * helper to process tree block while walking up the tree.
9025 * when wc->stage == DROP_REFERENCE, this function drops
9026 * reference count on the block.
9028 * when wc->stage == UPDATE_BACKREF, this function changes
9029 * wc->stage back to DROP_REFERENCE if we changed wc->stage
9030 * to UPDATE_BACKREF previously while processing the block.
9032 * NOTE: return value 1 means we should stop walking up.
9034 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
9035 struct btrfs_root *root,
9036 struct btrfs_path *path,
9037 struct walk_control *wc)
9039 struct btrfs_fs_info *fs_info = root->fs_info;
9041 int level = wc->level;
9042 struct extent_buffer *eb = path->nodes[level];
9045 if (wc->stage == UPDATE_BACKREF) {
9046 BUG_ON(wc->shared_level < level);
9047 if (level < wc->shared_level)
9050 ret = find_next_key(path, level + 1, &wc->update_progress);
9054 wc->stage = DROP_REFERENCE;
9055 wc->shared_level = -1;
9056 path->slots[level] = 0;
9059 * check reference count again if the block isn't locked.
9060 * we should start walking down the tree again if reference
9063 if (!path->locks[level]) {
9065 btrfs_tree_lock(eb);
9066 btrfs_set_lock_blocking_write(eb);
9067 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9069 ret = btrfs_lookup_extent_info(trans, fs_info,
9070 eb->start, level, 1,
9074 btrfs_tree_unlock_rw(eb, path->locks[level]);
9075 path->locks[level] = 0;
9078 BUG_ON(wc->refs[level] == 0);
9079 if (wc->refs[level] == 1) {
9080 btrfs_tree_unlock_rw(eb, path->locks[level]);
9081 path->locks[level] = 0;
9087 /* wc->stage == DROP_REFERENCE */
9088 BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
9090 if (wc->refs[level] == 1) {
9092 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
9093 ret = btrfs_dec_ref(trans, root, eb, 1);
9095 ret = btrfs_dec_ref(trans, root, eb, 0);
9096 BUG_ON(ret); /* -ENOMEM */
9097 if (is_fstree(root->root_key.objectid)) {
9098 ret = btrfs_qgroup_trace_leaf_items(trans, eb);
9100 btrfs_err_rl(fs_info,
9101 "error %d accounting leaf items, quota is out of sync, rescan required",
9106 /* make block locked assertion in btrfs_clean_tree_block happy */
9107 if (!path->locks[level] &&
9108 btrfs_header_generation(eb) == trans->transid) {
9109 btrfs_tree_lock(eb);
9110 btrfs_set_lock_blocking_write(eb);
9111 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9113 btrfs_clean_tree_block(eb);
9116 if (eb == root->node) {
9117 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
9119 else if (root->root_key.objectid != btrfs_header_owner(eb))
9120 goto owner_mismatch;
9122 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
9123 parent = path->nodes[level + 1]->start;
9124 else if (root->root_key.objectid !=
9125 btrfs_header_owner(path->nodes[level + 1]))
9126 goto owner_mismatch;
9129 btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
9131 wc->refs[level] = 0;
9132 wc->flags[level] = 0;
9136 btrfs_err_rl(fs_info, "unexpected tree owner, have %llu expect %llu",
9137 btrfs_header_owner(eb), root->root_key.objectid);
9141 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
9142 struct btrfs_root *root,
9143 struct btrfs_path *path,
9144 struct walk_control *wc)
9146 int level = wc->level;
9147 int lookup_info = 1;
9150 while (level >= 0) {
9151 ret = walk_down_proc(trans, root, path, wc, lookup_info);
9158 if (path->slots[level] >=
9159 btrfs_header_nritems(path->nodes[level]))
9162 ret = do_walk_down(trans, root, path, wc, &lookup_info);
9164 path->slots[level]++;
9173 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
9174 struct btrfs_root *root,
9175 struct btrfs_path *path,
9176 struct walk_control *wc, int max_level)
9178 int level = wc->level;
9181 path->slots[level] = btrfs_header_nritems(path->nodes[level]);
9182 while (level < max_level && path->nodes[level]) {
9184 if (path->slots[level] + 1 <
9185 btrfs_header_nritems(path->nodes[level])) {
9186 path->slots[level]++;
9189 ret = walk_up_proc(trans, root, path, wc);
9195 if (path->locks[level]) {
9196 btrfs_tree_unlock_rw(path->nodes[level],
9197 path->locks[level]);
9198 path->locks[level] = 0;
9200 free_extent_buffer(path->nodes[level]);
9201 path->nodes[level] = NULL;
9209 * drop a subvolume tree.
9211 * this function traverses the tree freeing any blocks that only
9212 * referenced by the tree.
9214 * when a shared tree block is found. this function decreases its
9215 * reference count by one. if update_ref is true, this function
9216 * also make sure backrefs for the shared block and all lower level
9217 * blocks are properly updated.
9219 * If called with for_reloc == 0, may exit early with -EAGAIN
9221 int btrfs_drop_snapshot(struct btrfs_root *root,
9222 struct btrfs_block_rsv *block_rsv, int update_ref,
9225 struct btrfs_fs_info *fs_info = root->fs_info;
9226 struct btrfs_path *path;
9227 struct btrfs_trans_handle *trans;
9228 struct btrfs_root *tree_root = fs_info->tree_root;
9229 struct btrfs_root_item *root_item = &root->root_item;
9230 struct walk_control *wc;
9231 struct btrfs_key key;
9235 bool root_dropped = false;
9237 btrfs_debug(fs_info, "Drop subvolume %llu", root->root_key.objectid);
9239 path = btrfs_alloc_path();
9245 wc = kzalloc(sizeof(*wc), GFP_NOFS);
9247 btrfs_free_path(path);
9252 trans = btrfs_start_transaction(tree_root, 0);
9253 if (IS_ERR(trans)) {
9254 err = PTR_ERR(trans);
9258 err = btrfs_run_delayed_items(trans);
9263 trans->block_rsv = block_rsv;
9266 * This will help us catch people modifying the fs tree while we're
9267 * dropping it. It is unsafe to mess with the fs tree while it's being
9268 * dropped as we unlock the root node and parent nodes as we walk down
9269 * the tree, assuming nothing will change. If something does change
9270 * then we'll have stale information and drop references to blocks we've
9273 set_bit(BTRFS_ROOT_DELETING, &root->state);
9274 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
9275 level = btrfs_header_level(root->node);
9276 path->nodes[level] = btrfs_lock_root_node(root);
9277 btrfs_set_lock_blocking_write(path->nodes[level]);
9278 path->slots[level] = 0;
9279 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9280 memset(&wc->update_progress, 0,
9281 sizeof(wc->update_progress));
9283 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
9284 memcpy(&wc->update_progress, &key,
9285 sizeof(wc->update_progress));
9287 level = root_item->drop_level;
9289 path->lowest_level = level;
9290 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
9291 path->lowest_level = 0;
9299 * unlock our path, this is safe because only this
9300 * function is allowed to delete this snapshot
9302 btrfs_unlock_up_safe(path, 0);
9304 level = btrfs_header_level(root->node);
9306 btrfs_tree_lock(path->nodes[level]);
9307 btrfs_set_lock_blocking_write(path->nodes[level]);
9308 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9310 ret = btrfs_lookup_extent_info(trans, fs_info,
9311 path->nodes[level]->start,
9312 level, 1, &wc->refs[level],
9318 BUG_ON(wc->refs[level] == 0);
9320 if (level == root_item->drop_level)
9323 btrfs_tree_unlock(path->nodes[level]);
9324 path->locks[level] = 0;
9325 WARN_ON(wc->refs[level] != 1);
9330 wc->restarted = test_bit(BTRFS_ROOT_DEAD_TREE, &root->state);
9332 wc->shared_level = -1;
9333 wc->stage = DROP_REFERENCE;
9334 wc->update_ref = update_ref;
9336 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
9340 ret = walk_down_tree(trans, root, path, wc);
9346 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
9353 BUG_ON(wc->stage != DROP_REFERENCE);
9357 if (wc->stage == DROP_REFERENCE) {
9358 wc->drop_level = wc->level;
9359 btrfs_node_key_to_cpu(path->nodes[wc->drop_level],
9361 path->slots[wc->drop_level]);
9363 btrfs_cpu_key_to_disk(&root_item->drop_progress,
9364 &wc->drop_progress);
9365 root_item->drop_level = wc->drop_level;
9367 BUG_ON(wc->level == 0);
9368 if (btrfs_should_end_transaction(trans) ||
9369 (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) {
9370 ret = btrfs_update_root(trans, tree_root,
9374 btrfs_abort_transaction(trans, ret);
9379 btrfs_end_transaction_throttle(trans);
9380 if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) {
9381 btrfs_debug(fs_info,
9382 "drop snapshot early exit");
9387 trans = btrfs_start_transaction(tree_root, 0);
9388 if (IS_ERR(trans)) {
9389 err = PTR_ERR(trans);
9393 trans->block_rsv = block_rsv;
9396 btrfs_release_path(path);
9400 ret = btrfs_del_root(trans, &root->root_key);
9402 btrfs_abort_transaction(trans, ret);
9407 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
9408 ret = btrfs_find_root(tree_root, &root->root_key, path,
9411 btrfs_abort_transaction(trans, ret);
9414 } else if (ret > 0) {
9415 /* if we fail to delete the orphan item this time
9416 * around, it'll get picked up the next time.
9418 * The most common failure here is just -ENOENT.
9420 btrfs_del_orphan_item(trans, tree_root,
9421 root->root_key.objectid);
9425 if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state)) {
9426 btrfs_add_dropped_root(trans, root);
9428 free_extent_buffer(root->node);
9429 free_extent_buffer(root->commit_root);
9430 btrfs_put_fs_root(root);
9432 root_dropped = true;
9434 btrfs_end_transaction_throttle(trans);
9437 btrfs_free_path(path);
9440 * So if we need to stop dropping the snapshot for whatever reason we
9441 * need to make sure to add it back to the dead root list so that we
9442 * keep trying to do the work later. This also cleans up roots if we
9443 * don't have it in the radix (like when we recover after a power fail
9444 * or unmount) so we don't leak memory.
9446 if (!for_reloc && !root_dropped)
9447 btrfs_add_dead_root(root);
9448 if (err && err != -EAGAIN)
9449 btrfs_handle_fs_error(fs_info, err, NULL);
9454 * drop subtree rooted at tree block 'node'.
9456 * NOTE: this function will unlock and release tree block 'node'
9457 * only used by relocation code
9459 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
9460 struct btrfs_root *root,
9461 struct extent_buffer *node,
9462 struct extent_buffer *parent)
9464 struct btrfs_fs_info *fs_info = root->fs_info;
9465 struct btrfs_path *path;
9466 struct walk_control *wc;
9472 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
9474 path = btrfs_alloc_path();
9478 wc = kzalloc(sizeof(*wc), GFP_NOFS);
9480 btrfs_free_path(path);
9484 btrfs_assert_tree_locked(parent);
9485 parent_level = btrfs_header_level(parent);
9486 extent_buffer_get(parent);
9487 path->nodes[parent_level] = parent;
9488 path->slots[parent_level] = btrfs_header_nritems(parent);
9490 btrfs_assert_tree_locked(node);
9491 level = btrfs_header_level(node);
9492 path->nodes[level] = node;
9493 path->slots[level] = 0;
9494 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9496 wc->refs[parent_level] = 1;
9497 wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
9499 wc->shared_level = -1;
9500 wc->stage = DROP_REFERENCE;
9503 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
9506 wret = walk_down_tree(trans, root, path, wc);
9512 wret = walk_up_tree(trans, root, path, wc, parent_level);
9520 btrfs_free_path(path);
9524 static u64 update_block_group_flags(struct btrfs_fs_info *fs_info, u64 flags)
9530 * if restripe for this chunk_type is on pick target profile and
9531 * return, otherwise do the usual balance
9533 stripped = get_restripe_target(fs_info, flags);
9535 return extended_to_chunk(stripped);
9537 num_devices = fs_info->fs_devices->rw_devices;
9539 stripped = BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID56_MASK |
9540 BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10;
9542 if (num_devices == 1) {
9543 stripped |= BTRFS_BLOCK_GROUP_DUP;
9544 stripped = flags & ~stripped;
9546 /* turn raid0 into single device chunks */
9547 if (flags & BTRFS_BLOCK_GROUP_RAID0)
9550 /* turn mirroring into duplication */
9551 if (flags & (BTRFS_BLOCK_GROUP_RAID1_MASK |
9552 BTRFS_BLOCK_GROUP_RAID10))
9553 return stripped | BTRFS_BLOCK_GROUP_DUP;
9555 /* they already had raid on here, just return */
9556 if (flags & stripped)
9559 stripped |= BTRFS_BLOCK_GROUP_DUP;
9560 stripped = flags & ~stripped;
9562 /* switch duplicated blocks with raid1 */
9563 if (flags & BTRFS_BLOCK_GROUP_DUP)
9564 return stripped | BTRFS_BLOCK_GROUP_RAID1;
9566 /* this is drive concat, leave it alone */
9572 static int inc_block_group_ro(struct btrfs_block_group_cache *cache, int force)
9574 struct btrfs_space_info *sinfo = cache->space_info;
9577 u64 min_allocable_bytes;
9581 * We need some metadata space and system metadata space for
9582 * allocating chunks in some corner cases until we force to set
9583 * it to be readonly.
9586 (BTRFS_BLOCK_GROUP_SYSTEM | BTRFS_BLOCK_GROUP_METADATA)) &&
9588 min_allocable_bytes = SZ_1M;
9590 min_allocable_bytes = 0;
9592 spin_lock(&sinfo->lock);
9593 spin_lock(&cache->lock);
9601 num_bytes = cache->key.offset - cache->reserved - cache->pinned -
9602 cache->bytes_super - btrfs_block_group_used(&cache->item);
9603 sinfo_used = btrfs_space_info_used(sinfo, true);
9605 if (sinfo_used + num_bytes + min_allocable_bytes <=
9606 sinfo->total_bytes) {
9607 sinfo->bytes_readonly += num_bytes;
9609 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
9613 spin_unlock(&cache->lock);
9614 spin_unlock(&sinfo->lock);
9615 if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
9616 btrfs_info(cache->fs_info,
9617 "unable to make block group %llu ro",
9618 cache->key.objectid);
9619 btrfs_info(cache->fs_info,
9620 "sinfo_used=%llu bg_num_bytes=%llu min_allocable=%llu",
9621 sinfo_used, num_bytes, min_allocable_bytes);
9622 dump_space_info(cache->fs_info, cache->space_info, 0, 0);
9627 int btrfs_inc_block_group_ro(struct btrfs_block_group_cache *cache)
9630 struct btrfs_fs_info *fs_info = cache->fs_info;
9631 struct btrfs_trans_handle *trans;
9636 trans = btrfs_join_transaction(fs_info->extent_root);
9638 return PTR_ERR(trans);
9641 * we're not allowed to set block groups readonly after the dirty
9642 * block groups cache has started writing. If it already started,
9643 * back off and let this transaction commit
9645 mutex_lock(&fs_info->ro_block_group_mutex);
9646 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
9647 u64 transid = trans->transid;
9649 mutex_unlock(&fs_info->ro_block_group_mutex);
9650 btrfs_end_transaction(trans);
9652 ret = btrfs_wait_for_commit(fs_info, transid);
9659 * if we are changing raid levels, try to allocate a corresponding
9660 * block group with the new raid level.
9662 alloc_flags = update_block_group_flags(fs_info, cache->flags);
9663 if (alloc_flags != cache->flags) {
9664 ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
9666 * ENOSPC is allowed here, we may have enough space
9667 * already allocated at the new raid level to
9676 ret = inc_block_group_ro(cache, 0);
9679 alloc_flags = get_alloc_profile(fs_info, cache->space_info->flags);
9680 ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
9683 ret = inc_block_group_ro(cache, 0);
9685 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
9686 alloc_flags = update_block_group_flags(fs_info, cache->flags);
9687 mutex_lock(&fs_info->chunk_mutex);
9688 check_system_chunk(trans, alloc_flags);
9689 mutex_unlock(&fs_info->chunk_mutex);
9691 mutex_unlock(&fs_info->ro_block_group_mutex);
9693 btrfs_end_transaction(trans);
9697 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
9699 u64 alloc_flags = get_alloc_profile(trans->fs_info, type);
9701 return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
9705 * helper to account the unused space of all the readonly block group in the
9706 * space_info. takes mirrors into account.
9708 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
9710 struct btrfs_block_group_cache *block_group;
9714 /* It's df, we don't care if it's racy */
9715 if (list_empty(&sinfo->ro_bgs))
9718 spin_lock(&sinfo->lock);
9719 list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
9720 spin_lock(&block_group->lock);
9722 if (!block_group->ro) {
9723 spin_unlock(&block_group->lock);
9727 factor = btrfs_bg_type_to_factor(block_group->flags);
9728 free_bytes += (block_group->key.offset -
9729 btrfs_block_group_used(&block_group->item)) *
9732 spin_unlock(&block_group->lock);
9734 spin_unlock(&sinfo->lock);
9739 void btrfs_dec_block_group_ro(struct btrfs_block_group_cache *cache)
9741 struct btrfs_space_info *sinfo = cache->space_info;
9746 spin_lock(&sinfo->lock);
9747 spin_lock(&cache->lock);
9749 num_bytes = cache->key.offset - cache->reserved -
9750 cache->pinned - cache->bytes_super -
9751 btrfs_block_group_used(&cache->item);
9752 sinfo->bytes_readonly -= num_bytes;
9753 list_del_init(&cache->ro_list);
9755 spin_unlock(&cache->lock);
9756 spin_unlock(&sinfo->lock);
9760 * Checks to see if it's even possible to relocate this block group.
9762 * @return - -1 if it's not a good idea to relocate this block group, 0 if its
9763 * ok to go ahead and try.
9765 int btrfs_can_relocate(struct btrfs_fs_info *fs_info, u64 bytenr)
9767 struct btrfs_block_group_cache *block_group;
9768 struct btrfs_space_info *space_info;
9769 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
9770 struct btrfs_device *device;
9780 debug = btrfs_test_opt(fs_info, ENOSPC_DEBUG);
9782 block_group = btrfs_lookup_block_group(fs_info, bytenr);
9784 /* odd, couldn't find the block group, leave it alone */
9788 "can't find block group for bytenr %llu",
9793 min_free = btrfs_block_group_used(&block_group->item);
9795 /* no bytes used, we're good */
9799 space_info = block_group->space_info;
9800 spin_lock(&space_info->lock);
9802 full = space_info->full;
9805 * if this is the last block group we have in this space, we can't
9806 * relocate it unless we're able to allocate a new chunk below.
9808 * Otherwise, we need to make sure we have room in the space to handle
9809 * all of the extents from this block group. If we can, we're good
9811 if ((space_info->total_bytes != block_group->key.offset) &&
9812 (btrfs_space_info_used(space_info, false) + min_free <
9813 space_info->total_bytes)) {
9814 spin_unlock(&space_info->lock);
9817 spin_unlock(&space_info->lock);
9820 * ok we don't have enough space, but maybe we have free space on our
9821 * devices to allocate new chunks for relocation, so loop through our
9822 * alloc devices and guess if we have enough space. if this block
9823 * group is going to be restriped, run checks against the target
9824 * profile instead of the current one.
9836 target = get_restripe_target(fs_info, block_group->flags);
9838 index = btrfs_bg_flags_to_raid_index(extended_to_chunk(target));
9841 * this is just a balance, so if we were marked as full
9842 * we know there is no space for a new chunk
9847 "no space to alloc new chunk for block group %llu",
9848 block_group->key.objectid);
9852 index = btrfs_bg_flags_to_raid_index(block_group->flags);
9855 if (index == BTRFS_RAID_RAID10) {
9859 } else if (index == BTRFS_RAID_RAID1) {
9861 } else if (index == BTRFS_RAID_DUP) {
9864 } else if (index == BTRFS_RAID_RAID0) {
9865 dev_min = fs_devices->rw_devices;
9866 min_free = div64_u64(min_free, dev_min);
9869 mutex_lock(&fs_info->chunk_mutex);
9870 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
9874 * check to make sure we can actually find a chunk with enough
9875 * space to fit our block group in.
9877 if (device->total_bytes > device->bytes_used + min_free &&
9878 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
9879 ret = find_free_dev_extent(device, min_free,
9884 if (dev_nr >= dev_min)
9890 if (debug && ret == -1)
9892 "no space to allocate a new chunk for block group %llu",
9893 block_group->key.objectid);
9894 mutex_unlock(&fs_info->chunk_mutex);
9896 btrfs_put_block_group(block_group);
9900 static int find_first_block_group(struct btrfs_fs_info *fs_info,
9901 struct btrfs_path *path,
9902 struct btrfs_key *key)
9904 struct btrfs_root *root = fs_info->extent_root;
9906 struct btrfs_key found_key;
9907 struct extent_buffer *leaf;
9908 struct btrfs_block_group_item bg;
9912 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
9917 slot = path->slots[0];
9918 leaf = path->nodes[0];
9919 if (slot >= btrfs_header_nritems(leaf)) {
9920 ret = btrfs_next_leaf(root, path);
9927 btrfs_item_key_to_cpu(leaf, &found_key, slot);
9929 if (found_key.objectid >= key->objectid &&
9930 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
9931 struct extent_map_tree *em_tree;
9932 struct extent_map *em;
9934 em_tree = &root->fs_info->mapping_tree;
9935 read_lock(&em_tree->lock);
9936 em = lookup_extent_mapping(em_tree, found_key.objectid,
9938 read_unlock(&em_tree->lock);
9941 "logical %llu len %llu found bg but no related chunk",
9942 found_key.objectid, found_key.offset);
9944 } else if (em->start != found_key.objectid ||
9945 em->len != found_key.offset) {
9947 "block group %llu len %llu mismatch with chunk %llu len %llu",
9948 found_key.objectid, found_key.offset,
9949 em->start, em->len);
9952 read_extent_buffer(leaf, &bg,
9953 btrfs_item_ptr_offset(leaf, slot),
9955 flags = btrfs_block_group_flags(&bg) &
9956 BTRFS_BLOCK_GROUP_TYPE_MASK;
9958 if (flags != (em->map_lookup->type &
9959 BTRFS_BLOCK_GROUP_TYPE_MASK)) {
9961 "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
9963 found_key.offset, flags,
9964 (BTRFS_BLOCK_GROUP_TYPE_MASK &
9965 em->map_lookup->type));
9971 free_extent_map(em);
9980 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
9982 struct btrfs_block_group_cache *block_group;
9986 struct inode *inode;
9988 block_group = btrfs_lookup_first_block_group(info, last);
9989 while (block_group) {
9990 wait_block_group_cache_done(block_group);
9991 spin_lock(&block_group->lock);
9992 if (block_group->iref)
9994 spin_unlock(&block_group->lock);
9995 block_group = next_block_group(block_group);
10004 inode = block_group->inode;
10005 block_group->iref = 0;
10006 block_group->inode = NULL;
10007 spin_unlock(&block_group->lock);
10008 ASSERT(block_group->io_ctl.inode == NULL);
10010 last = block_group->key.objectid + block_group->key.offset;
10011 btrfs_put_block_group(block_group);
10016 * Must be called only after stopping all workers, since we could have block
10017 * group caching kthreads running, and therefore they could race with us if we
10018 * freed the block groups before stopping them.
10020 int btrfs_free_block_groups(struct btrfs_fs_info *info)
10022 struct btrfs_block_group_cache *block_group;
10023 struct btrfs_space_info *space_info;
10024 struct btrfs_caching_control *caching_ctl;
10027 down_write(&info->commit_root_sem);
10028 while (!list_empty(&info->caching_block_groups)) {
10029 caching_ctl = list_entry(info->caching_block_groups.next,
10030 struct btrfs_caching_control, list);
10031 list_del(&caching_ctl->list);
10032 put_caching_control(caching_ctl);
10034 up_write(&info->commit_root_sem);
10036 spin_lock(&info->unused_bgs_lock);
10037 while (!list_empty(&info->unused_bgs)) {
10038 block_group = list_first_entry(&info->unused_bgs,
10039 struct btrfs_block_group_cache,
10041 list_del_init(&block_group->bg_list);
10042 btrfs_put_block_group(block_group);
10044 spin_unlock(&info->unused_bgs_lock);
10046 spin_lock(&info->block_group_cache_lock);
10047 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
10048 block_group = rb_entry(n, struct btrfs_block_group_cache,
10050 rb_erase(&block_group->cache_node,
10051 &info->block_group_cache_tree);
10052 RB_CLEAR_NODE(&block_group->cache_node);
10053 spin_unlock(&info->block_group_cache_lock);
10055 down_write(&block_group->space_info->groups_sem);
10056 list_del(&block_group->list);
10057 up_write(&block_group->space_info->groups_sem);
10060 * We haven't cached this block group, which means we could
10061 * possibly have excluded extents on this block group.
10063 if (block_group->cached == BTRFS_CACHE_NO ||
10064 block_group->cached == BTRFS_CACHE_ERROR)
10065 free_excluded_extents(block_group);
10067 btrfs_remove_free_space_cache(block_group);
10068 ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
10069 ASSERT(list_empty(&block_group->dirty_list));
10070 ASSERT(list_empty(&block_group->io_list));
10071 ASSERT(list_empty(&block_group->bg_list));
10072 ASSERT(atomic_read(&block_group->count) == 1);
10073 btrfs_put_block_group(block_group);
10075 spin_lock(&info->block_group_cache_lock);
10077 spin_unlock(&info->block_group_cache_lock);
10079 /* now that all the block groups are freed, go through and
10080 * free all the space_info structs. This is only called during
10081 * the final stages of unmount, and so we know nobody is
10082 * using them. We call synchronize_rcu() once before we start,
10083 * just to be on the safe side.
10087 release_global_block_rsv(info);
10089 while (!list_empty(&info->space_info)) {
10092 space_info = list_entry(info->space_info.next,
10093 struct btrfs_space_info,
10097 * Do not hide this behind enospc_debug, this is actually
10098 * important and indicates a real bug if this happens.
10100 if (WARN_ON(space_info->bytes_pinned > 0 ||
10101 space_info->bytes_reserved > 0 ||
10102 space_info->bytes_may_use > 0))
10103 dump_space_info(info, space_info, 0, 0);
10104 list_del(&space_info->list);
10105 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
10106 struct kobject *kobj;
10107 kobj = space_info->block_group_kobjs[i];
10108 space_info->block_group_kobjs[i] = NULL;
10114 kobject_del(&space_info->kobj);
10115 kobject_put(&space_info->kobj);
10120 /* link_block_group will queue up kobjects to add when we're reclaim-safe */
10121 void btrfs_add_raid_kobjects(struct btrfs_fs_info *fs_info)
10123 struct btrfs_space_info *space_info;
10124 struct raid_kobject *rkobj;
10128 spin_lock(&fs_info->pending_raid_kobjs_lock);
10129 list_splice_init(&fs_info->pending_raid_kobjs, &list);
10130 spin_unlock(&fs_info->pending_raid_kobjs_lock);
10132 list_for_each_entry(rkobj, &list, list) {
10133 space_info = __find_space_info(fs_info, rkobj->flags);
10135 ret = kobject_add(&rkobj->kobj, &space_info->kobj,
10136 "%s", btrfs_bg_type_to_raid_name(rkobj->flags));
10138 kobject_put(&rkobj->kobj);
10143 btrfs_warn(fs_info,
10144 "failed to add kobject for block cache, ignoring");
10147 static void link_block_group(struct btrfs_block_group_cache *cache)
10149 struct btrfs_space_info *space_info = cache->space_info;
10150 struct btrfs_fs_info *fs_info = cache->fs_info;
10151 int index = btrfs_bg_flags_to_raid_index(cache->flags);
10152 bool first = false;
10154 down_write(&space_info->groups_sem);
10155 if (list_empty(&space_info->block_groups[index]))
10157 list_add_tail(&cache->list, &space_info->block_groups[index]);
10158 up_write(&space_info->groups_sem);
10161 struct raid_kobject *rkobj = kzalloc(sizeof(*rkobj), GFP_NOFS);
10163 btrfs_warn(cache->fs_info,
10164 "couldn't alloc memory for raid level kobject");
10167 rkobj->flags = cache->flags;
10168 kobject_init(&rkobj->kobj, &btrfs_raid_ktype);
10170 spin_lock(&fs_info->pending_raid_kobjs_lock);
10171 list_add_tail(&rkobj->list, &fs_info->pending_raid_kobjs);
10172 spin_unlock(&fs_info->pending_raid_kobjs_lock);
10173 space_info->block_group_kobjs[index] = &rkobj->kobj;
10177 static struct btrfs_block_group_cache *
10178 btrfs_create_block_group_cache(struct btrfs_fs_info *fs_info,
10179 u64 start, u64 size)
10181 struct btrfs_block_group_cache *cache;
10183 cache = kzalloc(sizeof(*cache), GFP_NOFS);
10187 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
10189 if (!cache->free_space_ctl) {
10194 cache->key.objectid = start;
10195 cache->key.offset = size;
10196 cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
10198 cache->fs_info = fs_info;
10199 cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
10200 set_free_space_tree_thresholds(cache);
10202 atomic_set(&cache->count, 1);
10203 spin_lock_init(&cache->lock);
10204 init_rwsem(&cache->data_rwsem);
10205 INIT_LIST_HEAD(&cache->list);
10206 INIT_LIST_HEAD(&cache->cluster_list);
10207 INIT_LIST_HEAD(&cache->bg_list);
10208 INIT_LIST_HEAD(&cache->ro_list);
10209 INIT_LIST_HEAD(&cache->dirty_list);
10210 INIT_LIST_HEAD(&cache->io_list);
10211 btrfs_init_free_space_ctl(cache);
10212 atomic_set(&cache->trimming, 0);
10213 mutex_init(&cache->free_space_lock);
10214 btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root);
10221 * Iterate all chunks and verify that each of them has the corresponding block
10224 static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
10226 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
10227 struct extent_map *em;
10228 struct btrfs_block_group_cache *bg;
10233 read_lock(&map_tree->lock);
10235 * lookup_extent_mapping will return the first extent map
10236 * intersecting the range, so setting @len to 1 is enough to
10237 * get the first chunk.
10239 em = lookup_extent_mapping(map_tree, start, 1);
10240 read_unlock(&map_tree->lock);
10244 bg = btrfs_lookup_block_group(fs_info, em->start);
10247 "chunk start=%llu len=%llu doesn't have corresponding block group",
10248 em->start, em->len);
10250 free_extent_map(em);
10253 if (bg->key.objectid != em->start ||
10254 bg->key.offset != em->len ||
10255 (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
10256 (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
10258 "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
10259 em->start, em->len,
10260 em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
10261 bg->key.objectid, bg->key.offset,
10262 bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
10264 free_extent_map(em);
10265 btrfs_put_block_group(bg);
10268 start = em->start + em->len;
10269 free_extent_map(em);
10270 btrfs_put_block_group(bg);
10275 int btrfs_read_block_groups(struct btrfs_fs_info *info)
10277 struct btrfs_path *path;
10279 struct btrfs_block_group_cache *cache;
10280 struct btrfs_space_info *space_info;
10281 struct btrfs_key key;
10282 struct btrfs_key found_key;
10283 struct extent_buffer *leaf;
10284 int need_clear = 0;
10289 feature = btrfs_super_incompat_flags(info->super_copy);
10290 mixed = !!(feature & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS);
10294 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
10295 path = btrfs_alloc_path();
10298 path->reada = READA_FORWARD;
10300 cache_gen = btrfs_super_cache_generation(info->super_copy);
10301 if (btrfs_test_opt(info, SPACE_CACHE) &&
10302 btrfs_super_generation(info->super_copy) != cache_gen)
10304 if (btrfs_test_opt(info, CLEAR_CACHE))
10308 ret = find_first_block_group(info, path, &key);
10314 leaf = path->nodes[0];
10315 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
10317 cache = btrfs_create_block_group_cache(info, found_key.objectid,
10326 * When we mount with old space cache, we need to
10327 * set BTRFS_DC_CLEAR and set dirty flag.
10329 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
10330 * truncate the old free space cache inode and
10332 * b) Setting 'dirty flag' makes sure that we flush
10333 * the new space cache info onto disk.
10335 if (btrfs_test_opt(info, SPACE_CACHE))
10336 cache->disk_cache_state = BTRFS_DC_CLEAR;
10339 read_extent_buffer(leaf, &cache->item,
10340 btrfs_item_ptr_offset(leaf, path->slots[0]),
10341 sizeof(cache->item));
10342 cache->flags = btrfs_block_group_flags(&cache->item);
10344 ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
10345 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
10347 "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
10348 cache->key.objectid);
10353 key.objectid = found_key.objectid + found_key.offset;
10354 btrfs_release_path(path);
10357 * We need to exclude the super stripes now so that the space
10358 * info has super bytes accounted for, otherwise we'll think
10359 * we have more space than we actually do.
10361 ret = exclude_super_stripes(cache);
10364 * We may have excluded something, so call this just in
10367 free_excluded_extents(cache);
10368 btrfs_put_block_group(cache);
10373 * check for two cases, either we are full, and therefore
10374 * don't need to bother with the caching work since we won't
10375 * find any space, or we are empty, and we can just add all
10376 * the space in and be done with it. This saves us _a_lot_ of
10377 * time, particularly in the full case.
10379 if (found_key.offset == btrfs_block_group_used(&cache->item)) {
10380 cache->last_byte_to_unpin = (u64)-1;
10381 cache->cached = BTRFS_CACHE_FINISHED;
10382 free_excluded_extents(cache);
10383 } else if (btrfs_block_group_used(&cache->item) == 0) {
10384 cache->last_byte_to_unpin = (u64)-1;
10385 cache->cached = BTRFS_CACHE_FINISHED;
10386 add_new_free_space(cache, found_key.objectid,
10387 found_key.objectid +
10389 free_excluded_extents(cache);
10392 ret = btrfs_add_block_group_cache(info, cache);
10394 btrfs_remove_free_space_cache(cache);
10395 btrfs_put_block_group(cache);
10399 trace_btrfs_add_block_group(info, cache, 0);
10400 update_space_info(info, cache->flags, found_key.offset,
10401 btrfs_block_group_used(&cache->item),
10402 cache->bytes_super, &space_info);
10404 cache->space_info = space_info;
10406 link_block_group(cache);
10408 set_avail_alloc_bits(info, cache->flags);
10409 if (btrfs_chunk_readonly(info, cache->key.objectid)) {
10410 inc_block_group_ro(cache, 1);
10411 } else if (btrfs_block_group_used(&cache->item) == 0) {
10412 ASSERT(list_empty(&cache->bg_list));
10413 btrfs_mark_bg_unused(cache);
10417 list_for_each_entry_rcu(space_info, &info->space_info, list) {
10418 if (!(get_alloc_profile(info, space_info->flags) &
10419 (BTRFS_BLOCK_GROUP_RAID10 |
10420 BTRFS_BLOCK_GROUP_RAID1_MASK |
10421 BTRFS_BLOCK_GROUP_RAID56_MASK |
10422 BTRFS_BLOCK_GROUP_DUP)))
10425 * avoid allocating from un-mirrored block group if there are
10426 * mirrored block groups.
10428 list_for_each_entry(cache,
10429 &space_info->block_groups[BTRFS_RAID_RAID0],
10431 inc_block_group_ro(cache, 1);
10432 list_for_each_entry(cache,
10433 &space_info->block_groups[BTRFS_RAID_SINGLE],
10435 inc_block_group_ro(cache, 1);
10438 btrfs_add_raid_kobjects(info);
10439 init_global_block_rsv(info);
10440 ret = check_chunk_block_group_mappings(info);
10442 btrfs_free_path(path);
10446 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
10448 struct btrfs_fs_info *fs_info = trans->fs_info;
10449 struct btrfs_block_group_cache *block_group;
10450 struct btrfs_root *extent_root = fs_info->extent_root;
10451 struct btrfs_block_group_item item;
10452 struct btrfs_key key;
10455 if (!trans->can_flush_pending_bgs)
10458 while (!list_empty(&trans->new_bgs)) {
10459 block_group = list_first_entry(&trans->new_bgs,
10460 struct btrfs_block_group_cache,
10465 spin_lock(&block_group->lock);
10466 memcpy(&item, &block_group->item, sizeof(item));
10467 memcpy(&key, &block_group->key, sizeof(key));
10468 spin_unlock(&block_group->lock);
10470 ret = btrfs_insert_item(trans, extent_root, &key, &item,
10473 btrfs_abort_transaction(trans, ret);
10474 ret = btrfs_finish_chunk_alloc(trans, key.objectid, key.offset);
10476 btrfs_abort_transaction(trans, ret);
10477 add_block_group_free_space(trans, block_group);
10478 /* already aborted the transaction if it failed. */
10480 btrfs_delayed_refs_rsv_release(fs_info, 1);
10481 list_del_init(&block_group->bg_list);
10483 btrfs_trans_release_chunk_metadata(trans);
10486 int btrfs_make_block_group(struct btrfs_trans_handle *trans, u64 bytes_used,
10487 u64 type, u64 chunk_offset, u64 size)
10489 struct btrfs_fs_info *fs_info = trans->fs_info;
10490 struct btrfs_block_group_cache *cache;
10493 btrfs_set_log_full_commit(trans);
10495 cache = btrfs_create_block_group_cache(fs_info, chunk_offset, size);
10499 btrfs_set_block_group_used(&cache->item, bytes_used);
10500 btrfs_set_block_group_chunk_objectid(&cache->item,
10501 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
10502 btrfs_set_block_group_flags(&cache->item, type);
10504 cache->flags = type;
10505 cache->last_byte_to_unpin = (u64)-1;
10506 cache->cached = BTRFS_CACHE_FINISHED;
10507 cache->needs_free_space = 1;
10508 ret = exclude_super_stripes(cache);
10511 * We may have excluded something, so call this just in
10514 free_excluded_extents(cache);
10515 btrfs_put_block_group(cache);
10519 add_new_free_space(cache, chunk_offset, chunk_offset + size);
10521 free_excluded_extents(cache);
10523 #ifdef CONFIG_BTRFS_DEBUG
10524 if (btrfs_should_fragment_free_space(cache)) {
10525 u64 new_bytes_used = size - bytes_used;
10527 bytes_used += new_bytes_used >> 1;
10528 fragment_free_space(cache);
10532 * Ensure the corresponding space_info object is created and
10533 * assigned to our block group. We want our bg to be added to the rbtree
10534 * with its ->space_info set.
10536 cache->space_info = __find_space_info(fs_info, cache->flags);
10537 ASSERT(cache->space_info);
10539 ret = btrfs_add_block_group_cache(fs_info, cache);
10541 btrfs_remove_free_space_cache(cache);
10542 btrfs_put_block_group(cache);
10547 * Now that our block group has its ->space_info set and is inserted in
10548 * the rbtree, update the space info's counters.
10550 trace_btrfs_add_block_group(fs_info, cache, 1);
10551 update_space_info(fs_info, cache->flags, size, bytes_used,
10552 cache->bytes_super, &cache->space_info);
10553 update_global_block_rsv(fs_info);
10555 link_block_group(cache);
10557 list_add_tail(&cache->bg_list, &trans->new_bgs);
10558 trans->delayed_ref_updates++;
10559 btrfs_update_delayed_refs_rsv(trans);
10561 set_avail_alloc_bits(fs_info, type);
10565 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
10567 u64 extra_flags = chunk_to_extended(flags) &
10568 BTRFS_EXTENDED_PROFILE_MASK;
10570 write_seqlock(&fs_info->profiles_lock);
10571 if (flags & BTRFS_BLOCK_GROUP_DATA)
10572 fs_info->avail_data_alloc_bits &= ~extra_flags;
10573 if (flags & BTRFS_BLOCK_GROUP_METADATA)
10574 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
10575 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
10576 fs_info->avail_system_alloc_bits &= ~extra_flags;
10577 write_sequnlock(&fs_info->profiles_lock);
10581 * Clear incompat bits for the following feature(s):
10583 * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
10584 * in the whole filesystem
10586 static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
10588 if (flags & BTRFS_BLOCK_GROUP_RAID56_MASK) {
10589 struct list_head *head = &fs_info->space_info;
10590 struct btrfs_space_info *sinfo;
10592 list_for_each_entry_rcu(sinfo, head, list) {
10593 bool found = false;
10595 down_read(&sinfo->groups_sem);
10596 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
10598 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
10600 up_read(&sinfo->groups_sem);
10605 btrfs_clear_fs_incompat(fs_info, RAID56);
10609 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
10610 u64 group_start, struct extent_map *em)
10612 struct btrfs_fs_info *fs_info = trans->fs_info;
10613 struct btrfs_root *root = fs_info->extent_root;
10614 struct btrfs_path *path;
10615 struct btrfs_block_group_cache *block_group;
10616 struct btrfs_free_cluster *cluster;
10617 struct btrfs_root *tree_root = fs_info->tree_root;
10618 struct btrfs_key key;
10619 struct inode *inode;
10620 struct kobject *kobj = NULL;
10624 struct btrfs_caching_control *caching_ctl = NULL;
10626 bool remove_rsv = false;
10628 block_group = btrfs_lookup_block_group(fs_info, group_start);
10629 BUG_ON(!block_group);
10630 BUG_ON(!block_group->ro);
10632 trace_btrfs_remove_block_group(block_group);
10634 * Free the reserved super bytes from this block group before
10637 free_excluded_extents(block_group);
10638 btrfs_free_ref_tree_range(fs_info, block_group->key.objectid,
10639 block_group->key.offset);
10641 memcpy(&key, &block_group->key, sizeof(key));
10642 index = btrfs_bg_flags_to_raid_index(block_group->flags);
10643 factor = btrfs_bg_type_to_factor(block_group->flags);
10645 /* make sure this block group isn't part of an allocation cluster */
10646 cluster = &fs_info->data_alloc_cluster;
10647 spin_lock(&cluster->refill_lock);
10648 btrfs_return_cluster_to_free_space(block_group, cluster);
10649 spin_unlock(&cluster->refill_lock);
10652 * make sure this block group isn't part of a metadata
10653 * allocation cluster
10655 cluster = &fs_info->meta_alloc_cluster;
10656 spin_lock(&cluster->refill_lock);
10657 btrfs_return_cluster_to_free_space(block_group, cluster);
10658 spin_unlock(&cluster->refill_lock);
10660 path = btrfs_alloc_path();
10667 * get the inode first so any iput calls done for the io_list
10668 * aren't the final iput (no unlinks allowed now)
10670 inode = lookup_free_space_inode(block_group, path);
10672 mutex_lock(&trans->transaction->cache_write_mutex);
10674 * Make sure our free space cache IO is done before removing the
10677 spin_lock(&trans->transaction->dirty_bgs_lock);
10678 if (!list_empty(&block_group->io_list)) {
10679 list_del_init(&block_group->io_list);
10681 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
10683 spin_unlock(&trans->transaction->dirty_bgs_lock);
10684 btrfs_wait_cache_io(trans, block_group, path);
10685 btrfs_put_block_group(block_group);
10686 spin_lock(&trans->transaction->dirty_bgs_lock);
10689 if (!list_empty(&block_group->dirty_list)) {
10690 list_del_init(&block_group->dirty_list);
10692 btrfs_put_block_group(block_group);
10694 spin_unlock(&trans->transaction->dirty_bgs_lock);
10695 mutex_unlock(&trans->transaction->cache_write_mutex);
10697 if (!IS_ERR(inode)) {
10698 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10700 btrfs_add_delayed_iput(inode);
10703 clear_nlink(inode);
10704 /* One for the block groups ref */
10705 spin_lock(&block_group->lock);
10706 if (block_group->iref) {
10707 block_group->iref = 0;
10708 block_group->inode = NULL;
10709 spin_unlock(&block_group->lock);
10712 spin_unlock(&block_group->lock);
10714 /* One for our lookup ref */
10715 btrfs_add_delayed_iput(inode);
10718 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
10719 key.offset = block_group->key.objectid;
10722 ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
10726 btrfs_release_path(path);
10728 ret = btrfs_del_item(trans, tree_root, path);
10731 btrfs_release_path(path);
10734 spin_lock(&fs_info->block_group_cache_lock);
10735 rb_erase(&block_group->cache_node,
10736 &fs_info->block_group_cache_tree);
10737 RB_CLEAR_NODE(&block_group->cache_node);
10739 if (fs_info->first_logical_byte == block_group->key.objectid)
10740 fs_info->first_logical_byte = (u64)-1;
10741 spin_unlock(&fs_info->block_group_cache_lock);
10743 down_write(&block_group->space_info->groups_sem);
10745 * we must use list_del_init so people can check to see if they
10746 * are still on the list after taking the semaphore
10748 list_del_init(&block_group->list);
10749 if (list_empty(&block_group->space_info->block_groups[index])) {
10750 kobj = block_group->space_info->block_group_kobjs[index];
10751 block_group->space_info->block_group_kobjs[index] = NULL;
10752 clear_avail_alloc_bits(fs_info, block_group->flags);
10754 up_write(&block_group->space_info->groups_sem);
10755 clear_incompat_bg_bits(fs_info, block_group->flags);
10761 if (block_group->has_caching_ctl)
10762 caching_ctl = get_caching_control(block_group);
10763 if (block_group->cached == BTRFS_CACHE_STARTED)
10764 wait_block_group_cache_done(block_group);
10765 if (block_group->has_caching_ctl) {
10766 down_write(&fs_info->commit_root_sem);
10767 if (!caching_ctl) {
10768 struct btrfs_caching_control *ctl;
10770 list_for_each_entry(ctl,
10771 &fs_info->caching_block_groups, list)
10772 if (ctl->block_group == block_group) {
10774 refcount_inc(&caching_ctl->count);
10779 list_del_init(&caching_ctl->list);
10780 up_write(&fs_info->commit_root_sem);
10782 /* Once for the caching bgs list and once for us. */
10783 put_caching_control(caching_ctl);
10784 put_caching_control(caching_ctl);
10788 spin_lock(&trans->transaction->dirty_bgs_lock);
10789 WARN_ON(!list_empty(&block_group->dirty_list));
10790 WARN_ON(!list_empty(&block_group->io_list));
10791 spin_unlock(&trans->transaction->dirty_bgs_lock);
10793 btrfs_remove_free_space_cache(block_group);
10795 spin_lock(&block_group->space_info->lock);
10796 list_del_init(&block_group->ro_list);
10798 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
10799 WARN_ON(block_group->space_info->total_bytes
10800 < block_group->key.offset);
10801 WARN_ON(block_group->space_info->bytes_readonly
10802 < block_group->key.offset);
10803 WARN_ON(block_group->space_info->disk_total
10804 < block_group->key.offset * factor);
10806 block_group->space_info->total_bytes -= block_group->key.offset;
10807 block_group->space_info->bytes_readonly -= block_group->key.offset;
10808 block_group->space_info->disk_total -= block_group->key.offset * factor;
10810 spin_unlock(&block_group->space_info->lock);
10812 memcpy(&key, &block_group->key, sizeof(key));
10814 mutex_lock(&fs_info->chunk_mutex);
10815 spin_lock(&block_group->lock);
10816 block_group->removed = 1;
10818 * At this point trimming can't start on this block group, because we
10819 * removed the block group from the tree fs_info->block_group_cache_tree
10820 * so no one can't find it anymore and even if someone already got this
10821 * block group before we removed it from the rbtree, they have already
10822 * incremented block_group->trimming - if they didn't, they won't find
10823 * any free space entries because we already removed them all when we
10824 * called btrfs_remove_free_space_cache().
10826 * And we must not remove the extent map from the fs_info->mapping_tree
10827 * to prevent the same logical address range and physical device space
10828 * ranges from being reused for a new block group. This is because our
10829 * fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
10830 * completely transactionless, so while it is trimming a range the
10831 * currently running transaction might finish and a new one start,
10832 * allowing for new block groups to be created that can reuse the same
10833 * physical device locations unless we take this special care.
10835 * There may also be an implicit trim operation if the file system
10836 * is mounted with -odiscard. The same protections must remain
10837 * in place until the extents have been discarded completely when
10838 * the transaction commit has completed.
10840 remove_em = (atomic_read(&block_group->trimming) == 0);
10841 spin_unlock(&block_group->lock);
10843 mutex_unlock(&fs_info->chunk_mutex);
10845 ret = remove_block_group_free_space(trans, block_group);
10849 btrfs_put_block_group(block_group);
10850 btrfs_put_block_group(block_group);
10852 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
10858 ret = btrfs_del_item(trans, root, path);
10863 struct extent_map_tree *em_tree;
10865 em_tree = &fs_info->mapping_tree;
10866 write_lock(&em_tree->lock);
10867 remove_extent_mapping(em_tree, em);
10868 write_unlock(&em_tree->lock);
10869 /* once for the tree */
10870 free_extent_map(em);
10874 btrfs_delayed_refs_rsv_release(fs_info, 1);
10875 btrfs_free_path(path);
10879 struct btrfs_trans_handle *
10880 btrfs_start_trans_remove_block_group(struct btrfs_fs_info *fs_info,
10881 const u64 chunk_offset)
10883 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
10884 struct extent_map *em;
10885 struct map_lookup *map;
10886 unsigned int num_items;
10888 read_lock(&em_tree->lock);
10889 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
10890 read_unlock(&em_tree->lock);
10891 ASSERT(em && em->start == chunk_offset);
10894 * We need to reserve 3 + N units from the metadata space info in order
10895 * to remove a block group (done at btrfs_remove_chunk() and at
10896 * btrfs_remove_block_group()), which are used for:
10898 * 1 unit for adding the free space inode's orphan (located in the tree
10900 * 1 unit for deleting the block group item (located in the extent
10902 * 1 unit for deleting the free space item (located in tree of tree
10904 * N units for deleting N device extent items corresponding to each
10905 * stripe (located in the device tree).
10907 * In order to remove a block group we also need to reserve units in the
10908 * system space info in order to update the chunk tree (update one or
10909 * more device items and remove one chunk item), but this is done at
10910 * btrfs_remove_chunk() through a call to check_system_chunk().
10912 map = em->map_lookup;
10913 num_items = 3 + map->num_stripes;
10914 free_extent_map(em);
10916 return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
10921 * Process the unused_bgs list and remove any that don't have any allocated
10922 * space inside of them.
10924 void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
10926 struct btrfs_block_group_cache *block_group;
10927 struct btrfs_space_info *space_info;
10928 struct btrfs_trans_handle *trans;
10931 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
10934 spin_lock(&fs_info->unused_bgs_lock);
10935 while (!list_empty(&fs_info->unused_bgs)) {
10939 block_group = list_first_entry(&fs_info->unused_bgs,
10940 struct btrfs_block_group_cache,
10942 list_del_init(&block_group->bg_list);
10944 space_info = block_group->space_info;
10946 if (ret || btrfs_mixed_space_info(space_info)) {
10947 btrfs_put_block_group(block_group);
10950 spin_unlock(&fs_info->unused_bgs_lock);
10952 mutex_lock(&fs_info->delete_unused_bgs_mutex);
10954 /* Don't want to race with allocators so take the groups_sem */
10955 down_write(&space_info->groups_sem);
10956 spin_lock(&block_group->lock);
10957 if (block_group->reserved || block_group->pinned ||
10958 btrfs_block_group_used(&block_group->item) ||
10960 list_is_singular(&block_group->list)) {
10962 * We want to bail if we made new allocations or have
10963 * outstanding allocations in this block group. We do
10964 * the ro check in case balance is currently acting on
10965 * this block group.
10967 trace_btrfs_skip_unused_block_group(block_group);
10968 spin_unlock(&block_group->lock);
10969 up_write(&space_info->groups_sem);
10972 spin_unlock(&block_group->lock);
10974 /* We don't want to force the issue, only flip if it's ok. */
10975 ret = inc_block_group_ro(block_group, 0);
10976 up_write(&space_info->groups_sem);
10983 * Want to do this before we do anything else so we can recover
10984 * properly if we fail to join the transaction.
10986 trans = btrfs_start_trans_remove_block_group(fs_info,
10987 block_group->key.objectid);
10988 if (IS_ERR(trans)) {
10989 btrfs_dec_block_group_ro(block_group);
10990 ret = PTR_ERR(trans);
10995 * We could have pending pinned extents for this block group,
10996 * just delete them, we don't care about them anymore.
10998 start = block_group->key.objectid;
10999 end = start + block_group->key.offset - 1;
11001 * Hold the unused_bg_unpin_mutex lock to avoid racing with
11002 * btrfs_finish_extent_commit(). If we are at transaction N,
11003 * another task might be running finish_extent_commit() for the
11004 * previous transaction N - 1, and have seen a range belonging
11005 * to the block group in freed_extents[] before we were able to
11006 * clear the whole block group range from freed_extents[]. This
11007 * means that task can lookup for the block group after we
11008 * unpinned it from freed_extents[] and removed it, leading to
11009 * a BUG_ON() at btrfs_unpin_extent_range().
11011 mutex_lock(&fs_info->unused_bg_unpin_mutex);
11012 ret = clear_extent_bits(&fs_info->freed_extents[0], start, end,
11015 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
11016 btrfs_dec_block_group_ro(block_group);
11019 ret = clear_extent_bits(&fs_info->freed_extents[1], start, end,
11022 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
11023 btrfs_dec_block_group_ro(block_group);
11026 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
11028 /* Reset pinned so btrfs_put_block_group doesn't complain */
11029 spin_lock(&space_info->lock);
11030 spin_lock(&block_group->lock);
11032 update_bytes_pinned(fs_info, space_info, -block_group->pinned);
11033 space_info->bytes_readonly += block_group->pinned;
11034 percpu_counter_add_batch(&space_info->total_bytes_pinned,
11035 -block_group->pinned,
11036 BTRFS_TOTAL_BYTES_PINNED_BATCH);
11037 block_group->pinned = 0;
11039 spin_unlock(&block_group->lock);
11040 spin_unlock(&space_info->lock);
11042 /* DISCARD can flip during remount */
11043 trimming = btrfs_test_opt(fs_info, DISCARD);
11045 /* Implicit trim during transaction commit. */
11047 btrfs_get_block_group_trimming(block_group);
11050 * Btrfs_remove_chunk will abort the transaction if things go
11053 ret = btrfs_remove_chunk(trans, block_group->key.objectid);
11057 btrfs_put_block_group_trimming(block_group);
11062 * If we're not mounted with -odiscard, we can just forget
11063 * about this block group. Otherwise we'll need to wait
11064 * until transaction commit to do the actual discard.
11067 spin_lock(&fs_info->unused_bgs_lock);
11069 * A concurrent scrub might have added us to the list
11070 * fs_info->unused_bgs, so use a list_move operation
11071 * to add the block group to the deleted_bgs list.
11073 list_move(&block_group->bg_list,
11074 &trans->transaction->deleted_bgs);
11075 spin_unlock(&fs_info->unused_bgs_lock);
11076 btrfs_get_block_group(block_group);
11079 btrfs_end_transaction(trans);
11081 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
11082 btrfs_put_block_group(block_group);
11083 spin_lock(&fs_info->unused_bgs_lock);
11085 spin_unlock(&fs_info->unused_bgs_lock);
11088 int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
11090 struct btrfs_super_block *disk_super;
11096 disk_super = fs_info->super_copy;
11097 if (!btrfs_super_root(disk_super))
11100 features = btrfs_super_incompat_flags(disk_super);
11101 if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
11104 flags = BTRFS_BLOCK_GROUP_SYSTEM;
11105 ret = create_space_info(fs_info, flags);
11110 flags = BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA;
11111 ret = create_space_info(fs_info, flags);
11113 flags = BTRFS_BLOCK_GROUP_METADATA;
11114 ret = create_space_info(fs_info, flags);
11118 flags = BTRFS_BLOCK_GROUP_DATA;
11119 ret = create_space_info(fs_info, flags);
11125 int btrfs_error_unpin_extent_range(struct btrfs_fs_info *fs_info,
11126 u64 start, u64 end)
11128 return unpin_extent_range(fs_info, start, end, false);
11132 * It used to be that old block groups would be left around forever.
11133 * Iterating over them would be enough to trim unused space. Since we
11134 * now automatically remove them, we also need to iterate over unallocated
11137 * We don't want a transaction for this since the discard may take a
11138 * substantial amount of time. We don't require that a transaction be
11139 * running, but we do need to take a running transaction into account
11140 * to ensure that we're not discarding chunks that were released or
11141 * allocated in the current transaction.
11143 * Holding the chunks lock will prevent other threads from allocating
11144 * or releasing chunks, but it won't prevent a running transaction
11145 * from committing and releasing the memory that the pending chunks
11146 * list head uses. For that, we need to take a reference to the
11147 * transaction and hold the commit root sem. We only need to hold
11148 * it while performing the free space search since we have already
11149 * held back allocations.
11151 static int btrfs_trim_free_extents(struct btrfs_device *device, u64 *trimmed)
11153 u64 start = SZ_1M, len = 0, end = 0;
11158 /* Discard not supported = nothing to do. */
11159 if (!blk_queue_discard(bdev_get_queue(device->bdev)))
11162 /* Not writable = nothing to do. */
11163 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
11166 /* No free space = nothing to do. */
11167 if (device->total_bytes <= device->bytes_used)
11173 struct btrfs_fs_info *fs_info = device->fs_info;
11176 ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
11180 find_first_clear_extent_bit(&device->alloc_state, start,
11182 CHUNK_TRIMMED | CHUNK_ALLOCATED);
11184 /* Ensure we skip the reserved area in the first 1M */
11185 start = max_t(u64, start, SZ_1M);
11188 * If find_first_clear_extent_bit find a range that spans the
11189 * end of the device it will set end to -1, in this case it's up
11190 * to the caller to trim the value to the size of the device.
11192 end = min(end, device->total_bytes - 1);
11194 len = end - start + 1;
11196 /* We didn't find any extents */
11198 mutex_unlock(&fs_info->chunk_mutex);
11203 ret = btrfs_issue_discard(device->bdev, start, len,
11206 set_extent_bits(&device->alloc_state, start,
11209 mutex_unlock(&fs_info->chunk_mutex);
11217 if (fatal_signal_pending(current)) {
11218 ret = -ERESTARTSYS;
11229 * Trim the whole filesystem by:
11230 * 1) trimming the free space in each block group
11231 * 2) trimming the unallocated space on each device
11233 * This will also continue trimming even if a block group or device encounters
11234 * an error. The return value will be the last error, or 0 if nothing bad
11237 int btrfs_trim_fs(struct btrfs_fs_info *fs_info, struct fstrim_range *range)
11239 struct btrfs_block_group_cache *cache = NULL;
11240 struct btrfs_device *device;
11241 struct list_head *devices;
11247 u64 dev_failed = 0;
11252 cache = btrfs_lookup_first_block_group(fs_info, range->start);
11253 for (; cache; cache = next_block_group(cache)) {
11254 if (cache->key.objectid >= (range->start + range->len)) {
11255 btrfs_put_block_group(cache);
11259 start = max(range->start, cache->key.objectid);
11260 end = min(range->start + range->len,
11261 cache->key.objectid + cache->key.offset);
11263 if (end - start >= range->minlen) {
11264 if (!block_group_cache_done(cache)) {
11265 ret = cache_block_group(cache, 0);
11271 ret = wait_block_group_cache_done(cache);
11278 ret = btrfs_trim_block_group(cache,
11284 trimmed += group_trimmed;
11294 btrfs_warn(fs_info,
11295 "failed to trim %llu block group(s), last error %d",
11296 bg_failed, bg_ret);
11297 mutex_lock(&fs_info->fs_devices->device_list_mutex);
11298 devices = &fs_info->fs_devices->devices;
11299 list_for_each_entry(device, devices, dev_list) {
11300 ret = btrfs_trim_free_extents(device, &group_trimmed);
11307 trimmed += group_trimmed;
11309 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
11312 btrfs_warn(fs_info,
11313 "failed to trim %llu device(s), last error %d",
11314 dev_failed, dev_ret);
11315 range->len = trimmed;
11322 * btrfs_{start,end}_write_no_snapshotting() are similar to
11323 * mnt_{want,drop}_write(), they are used to prevent some tasks from writing
11324 * data into the page cache through nocow before the subvolume is snapshoted,
11325 * but flush the data into disk after the snapshot creation, or to prevent
11326 * operations while snapshotting is ongoing and that cause the snapshot to be
11327 * inconsistent (writes followed by expanding truncates for example).
11329 void btrfs_end_write_no_snapshotting(struct btrfs_root *root)
11331 percpu_counter_dec(&root->subv_writers->counter);
11332 cond_wake_up(&root->subv_writers->wait);
11335 int btrfs_start_write_no_snapshotting(struct btrfs_root *root)
11337 if (atomic_read(&root->will_be_snapshotted))
11340 percpu_counter_inc(&root->subv_writers->counter);
11342 * Make sure counter is updated before we check for snapshot creation.
11345 if (atomic_read(&root->will_be_snapshotted)) {
11346 btrfs_end_write_no_snapshotting(root);
11352 void btrfs_wait_for_snapshot_creation(struct btrfs_root *root)
11357 ret = btrfs_start_write_no_snapshotting(root);
11360 wait_var_event(&root->will_be_snapshotted,
11361 !atomic_read(&root->will_be_snapshotted));
11365 void btrfs_mark_bg_unused(struct btrfs_block_group_cache *bg)
11367 struct btrfs_fs_info *fs_info = bg->fs_info;
11369 spin_lock(&fs_info->unused_bgs_lock);
11370 if (list_empty(&bg->bg_list)) {
11371 btrfs_get_block_group(bg);
11372 trace_btrfs_add_unused_block_group(bg);
11373 list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
11375 spin_unlock(&fs_info->unused_bgs_lock);